Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/cli-docs/src/content/docs/library-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ const sdk = createSentrySDK({ token: "...", text: true, cwd: "/my/project" });
| `url` | `string` | `sentry.io` | Sentry instance URL for self-hosted |
| `org` | `string` | Auto-detected | Organization slug; also a limit while `limitToTarget` is on |
| `project` | `string` | Auto-detected | Project slug; also a limit while `limitToTarget` is on |
| `limitToTarget` | `boolean` | `true` | Refuse an issue outside `org` and `project`, even one an ID alone names (`12345`, `@latest`). Set `false` to use `org` and `project` only as defaults |
| `limitToTarget` | `boolean` | `true` | Refuse an issue, event, trace or replay outside `org` and `project`, even one an ID alone names (`12345`, `@latest`, an event ID). Set `false` to use `org` and `project` only as defaults |
| `text` | `boolean` | `false` | Return human-readable text instead of parsed JSON (`run()` only) |
| `cwd` | `string` | `process.cwd()` | Working directory for DSN auto-detection |
| `headers` | `Record<string, string>` | — | Extra HTTP headers for self-hosted instances behind a reverse proxy (same as [`SENTRY_CUSTOM_HEADERS`](../configuration/#sentry_custom_headers)); ignored for sentry.io |
Expand Down
8 changes: 6 additions & 2 deletions packages/cli/src/commands/event/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -880,8 +880,12 @@ async function tryEventFallbacks(
return resolved;
}
} catch (sameOrgError) {
// Propagate auth errors — they indicate a global problem (expired token)
if (sameOrgError instanceof AuthError) {
// Propagate auth errors (a global problem, such as an expired token) and
// an event outside the invocation's target scope.
if (
sameOrgError instanceof AuthError ||
sameOrgError instanceof ResolutionError
) {
throw sameOrgError;
}
if (sameOrgError instanceof ApiError && sameOrgError.status === 429) {
Expand Down
36 changes: 30 additions & 6 deletions packages/cli/src/commands/replay/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ import {
} from "../../lib/resolve-target.js";
import { applySentryUrlContext } from "../../lib/sentry-url-parser.js";
import { buildReplayUrl } from "../../lib/sentry-web-urls.js";
import {
assertProjectInScope,
getTargetScope,
} from "../../lib/target-scope.js";
import type {
ReplayActivityEvent,
ReplayDetails,
Expand Down Expand Up @@ -161,7 +165,8 @@ type ReplayProjectScope = {
};

/**
* Reject a replay that is not in the project the user named.
* Reject a replay that is not in the project the user named, or outside the
* invocation's target scope (`limitToTarget`).
*
* Replays are looked up org-wide, so an explicit `<org>/<project>/<id>` target
* has to be checked against the replay's own project.
Expand All @@ -171,6 +176,7 @@ export async function validateReplayProjectScope(
): Promise<void> {
const { expectedProjectId, org, project, replay, replayId } = scope;
const command = scope.command ?? "view";
await assertReplayInTargetScope(org, replayId, replay);
if (!project) {
return;
}
Expand Down Expand Up @@ -203,6 +209,24 @@ export async function validateReplayProjectScope(
}
}

/**
* Refuse a replay outside the invocation's target scope. A replay without a
* project, such as an archived one, is refused in a project scope.
*/
async function assertReplayInTargetScope(
org: string,
replayId: string,
replay: ReplayDetails,
): Promise<void> {
const scopeProject = getTargetScope()?.project;
let project: string | undefined;
if (scopeProject && replay.project_id) {
const { id } = await getProject(org, scopeProject);
project = String(id) === replay.project_id ? scopeProject : undefined;
}
assertProjectInScope(org, project, `Replay ${replayId}`);
}

Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
async function fetchReplayActivity(
org: string,
replay: ReplayDetails,
Expand Down Expand Up @@ -397,11 +421,6 @@ export const viewCommand = buildCommand({
throw error;
}

if (flags.web) {
await openInBrowser(buildReplayUrl(resolved.org, replay.id), "replay");
return;
}

await validateReplayProjectScope({
org: resolved.org,
project: resolved.project,
Expand All @@ -410,6 +429,11 @@ export const viewCommand = buildCommand({
replay,
});

if (flags.web) {
await openInBrowser(buildReplayUrl(resolved.org, replay.id), "replay");
return;
}

const enrichment = await enrichReplayView(resolved.org, replay);
const data: ReplayViewData = {
org: resolved.org,
Expand Down
31 changes: 21 additions & 10 deletions packages/cli/src/lib/api/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import pLimit from "p-limit";
import type { IssueEvent, SentryEvent } from "../../types/index.js";

import { ApiError, AuthError } from "../errors.js";
import { assertOrgInScope, assertProjectInScope } from "../target-scope.js";

import {
API_MAX_PER_PAGE,
Expand Down Expand Up @@ -60,12 +61,16 @@ export async function getLatestEvent(
/**
* Get a specific event by ID.
* Uses region-aware routing for multi-region support.
*
* @throws {ResolutionError} When `orgSlug`/`projectSlug` is outside the
* invocation's target scope (`limitToTarget`)
*/
export async function getEvent(
orgSlug: string,
projectSlug: string,
eventId: string,
): Promise<SentryEvent> {
assertProjectInScope(orgSlug, projectSlug, `Event ${eventId}`);
const config = getOrgSdkConfig();

const result = await getProjectEvent({
Expand Down Expand Up @@ -136,36 +141,42 @@ export type ResolvedEvent = {
*
* Returns the resolved org, project, and full event on success,
* or null if the event is not found in the given org.
*
* @throws {ResolutionError} When the org, or the event's project, is outside
* the invocation's target scope (`limitToTarget`)
*/
export async function resolveEventInOrg(
orgSlug: string,
eventId: string,
): Promise<ResolvedEvent | null> {
assertOrgInScope(orgSlug, `Event ${eventId}`);
const config = getOrgSdkConfig();

const result = await sdkResolveAnEventId({
...config,
path: { organization_id_or_slug: orgSlug, event_id: eventId },
});

let data: { organizationSlug: string; projectSlug: string; event: unknown };
try {
const data = unwrapResult<{
organizationSlug: string;
projectSlug: string;
event: unknown;
}>(result, "Failed to resolve event ID");
return {
org: data.organizationSlug,
project: data.projectSlug,
event: data.event as SentryEvent,
};
data = unwrapResult<typeof data>(result, "Failed to resolve event ID");
} catch (error) {
// 404 means the event doesn't exist in this org — not an error
if (error instanceof ApiError && error.status === 404) {
return null;
}
throw error;
}
assertProjectInScope(
data.organizationSlug,
data.projectSlug,
`Event ${eventId}`,
);
return {
org: data.organizationSlug,
project: data.projectSlug,
event: data.event as SentryEvent,
};
}

/** Options for {@link findEventAcrossOrgs}. */
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/lib/api/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ export async function getIssueInOrg(
issueId: string,
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
assertOrgInScope(orgSlug, issueId);
assertOrgInScope(orgSlug, `Issue ${issueId}`);
const collapse = toIssueDetailsCollapse(options?.collapse);
const result = await getOrganizationIssue({
...getOrgSdkConfig(),
Expand Down Expand Up @@ -413,7 +413,7 @@ export async function getIssueByShortId(
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
const normalizedShortId = shortId.toUpperCase();
assertOrgInScope(orgSlug, normalizedShortId);
assertOrgInScope(orgSlug, `Issue ${normalizedShortId}`);
const config = getOrgSdkConfig();

let data: { group?: SentryIssue };
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/lib/api/replays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import { ApiError } from "../errors.js";
import { logger } from "../logger.js";
import { resolveOrgRegion } from "../region.js";
import { assertOrgInScope } from "../target-scope.js";

import {
API_MAX_PER_PAGE,
Expand Down Expand Up @@ -305,6 +306,7 @@ export async function resolveReplay(
replayOrTraceId: string,
options: Pick<ListReplaysOptions, "projectSlugs"> = {},
): Promise<ReplayDetails> {
assertOrgInScope(orgSlug, `Replay ${replayOrTraceId}`);
try {
return await getReplay(orgSlug, replayOrTraceId);
} catch (error) {
Expand Down
38 changes: 38 additions & 0 deletions packages/cli/src/lib/api/traces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ export type { TraceItemAttribute, TraceItemDetail } from "../../types/index.js";
import { logger } from "../logger.js";
import { resolveOrgRegion } from "../region.js";
import { getSdkClientConfig } from "../sentry-sdk-client.js";
import {
assertOrgInScope,
assertProjectInScope,
getTargetScope,
} from "../target-scope.js";
import { isAllDigits } from "../utils.js";

import {
Expand Down Expand Up @@ -158,15 +163,48 @@ async function requestTrace(
* - Known event `timestamp` → one query around that instant (no retry).
* - Unknown time → `statsPeriod=14d`, then `90d` if the first response is empty.
*
* In a project-limited invocation (`limitToTarget`), a trace with no span
* in that project is refused. A trace that has one keeps the spans of every
* project it calls into.
*
* @param orgSlug - Organization slug
* @param traceId - The trace ID (from event.contexts.trace.trace_id)
* @param options - Optional timestamp and additional attributes
* @returns Array of root spans with nested children
* @throws {ResolutionError} When the trace is outside the invocation's
* target scope
*/
export async function getDetailedTrace(
orgSlug: string,
traceId: string,
options: GetDetailedTraceOptions = {},
): Promise<TraceSpan[]> {
assertOrgInScope(orgSlug, `Trace ${traceId}`);
const spans = await fetchDetailedTrace(orgSlug, traceId, options);
const scopeProject = getTargetScope()?.project;
if (scopeProject && spans.length > 0) {
assertProjectInScope(
orgSlug,
hasSpanInProject(spans, scopeProject) ? scopeProject : undefined,
`Trace ${traceId}`,
);
}
return spans;
}

/** Whether a span of the tree, at any depth, is in `projectSlug`. */
function hasSpanInProject(spans: TraceSpan[], projectSlug: string): boolean {
return spans.some(
(span) =>
span.project_slug === projectSlug ||
hasSpanInProject(span.children ?? [], projectSlug),
);
}

async function fetchDetailedTrace(
orgSlug: string,
traceId: string,
options: GetDetailedTraceOptions,
): Promise<TraceSpan[]> {
const regionUrl = await resolveOrgRegion(orgSlug);
const shared = { additionalAttributes: options.additionalAttributes };
Expand Down
9 changes: 5 additions & 4 deletions packages/cli/src/lib/sdk-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ export type SentryOptions = {

/**
* Treat `org` and `project` as a limit, not only as defaults (default
* `true`). A command then refuses an issue outside them, including one
* named by an ID that says nothing about its project (a numeric ID, a
* share link, `@latest`). Has no effect without `org`. Set `false` to use
* `org` and `project` only as defaults.
* `true`). A command then refuses an issue, event, trace or replay
* outside them, including one named by an ID that says nothing about its
* project (a numeric issue ID, an event ID, a share link, `@latest`). Has
* no effect without `org`. Set `false` to use `org` and `project` only as
* defaults.
*/
limitToTarget?: boolean;

Expand Down
Loading
Loading