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, 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 |
| `limitToTarget` | `boolean` | `true` | Refuse any request outside `org` and `project`, including what an ID alone names (`12345`, `@latest`, an event ID). With a `project`, requests the CLI has no rule for, such as organization-wide writes, are refused too; read-only organization metadata, such as DSN lookups, stays allowed. 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
16 changes: 4 additions & 12 deletions packages/cli/src/commands/event/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ import {
} from "../../lib/sentry-url-parser.js";
import { buildEventSearchUrl } from "../../lib/sentry-web-urls.js";
import { getSpanTreeLines } from "../../lib/span-tree.js";
import { getTargetScope } from "../../lib/target-scope.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import type { InferOutput } from "valibot";
import type { SentryEvent } from "../../types/index.js";
Expand Down Expand Up @@ -881,7 +880,8 @@ async function tryEventFallbacks(
}
} catch (sameOrgError) {
// Propagate auth errors (a global problem, such as an expired token) and
// an event outside the invocation's target scope.
// a request the invocation's target scope refuses: falling back to
// other organizations would hide it.
if (
sameOrgError instanceof AuthError ||
sameOrgError instanceof ResolutionError
Expand Down Expand Up @@ -1144,16 +1144,8 @@ async function resolveIssueIdShortcut(
parsed.type === ProjectSpecificationType.Explicit
? parsed.project
: undefined;
// A target-scoped invocation checks the issue (`getIssueInOrg`) before it
// reads the issue's events: the ID names no project, and an explicit one
// need not be the issue's.
const scopedProject = getTargetScope()
? (await getIssueInOrg(org, issueId, { collapse: ISSUE_DETAIL_COLLAPSE }))
.project?.slug
: undefined;
const knownProject = explicitProject ?? scopedProject;
const projectPromise = knownProject
? Promise.resolve(knownProject)
const projectPromise = explicitProject
? Promise.resolve(explicitProject)
: tryResolveIssueProject(org, issueId);
const [event, project] = await Promise.all([
getLatestEvent(org, issueId),
Expand Down
13 changes: 1 addition & 12 deletions packages/cli/src/commands/feedback/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ import {
parseIssueArgument,
} from "../../lib/issue-arguments.js";
import { resolveEffectiveOrg } from "../../lib/region.js";
import {
resolveOrg,
resolveProjectIdsInOrg,
} from "../../lib/resolve-target.js";
import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js";
import { resolveOrg } from "../../lib/resolve-target.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import type { SentryFeedback } from "../../types/index.js";
import { buildCommandHint, resolveIssue } from "../issue/utils.js";
Expand Down Expand Up @@ -57,15 +53,9 @@ async function resolveFeedbackSelector(
);
}

// A project-scoped invocation picks the latest Feedback of its project.
const scopeProject = getTargetScope()?.project;
const [projectId] = scopeProject
? await resolveProjectIdsInOrg(org, [scopeProject])
: [];
const { feedback } = await listFeedback(org, "", {
limit: 1,
status: "unresolved",
projectId,
});
const latest = feedback[0];
if (!latest) {
Expand All @@ -77,7 +67,6 @@ async function resolveFeedbackSelector(
);
}

assertIssueInScope(org, latest);
setOrgProjectContext(
[org],
latest.project?.slug ? [latest.project.slug] : [],
Expand Down
20 changes: 7 additions & 13 deletions packages/cli/src/commands/issue/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import {
} from "../../lib/resolve-target.js";
import { applySentryUrlContext } from "../../lib/sentry-url-parser.js";
import { buildIssueUrl } from "../../lib/sentry-web-urls.js";
import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js";
import { getTargetScope } from "../../lib/target-scope.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import { isAllDigits, shellQuote } from "../../lib/utils.js";
import type { SentryIssue } from "../../types/index.js";
Expand Down Expand Up @@ -600,15 +600,14 @@ async function resolveSelector(
* @param org - Organization slug
* @param project - Project slug to look in, selected by its numeric ID
* (a `project:<slug>` filter misses projects that are not actively
* selected, #1317); omit for the whole organization, or for the project
* of the invocation's target scope when it has one
* @throws {ResolutionError} When no unresolved issue matches, the project
* does not exist, or the issue is outside the target scope
* selected, #1317); omit for the whole organization
* @throws {ResolutionError} When no unresolved issue matches, or the
* project does not exist
*/
export async function findSelectorIssue(
selector: IssueSelector,
org: string,
project = getTargetScope()?.project,
project?: string,
): Promise<SentryIssue> {
const projects = project
? await resolveProjectIdsInOrg(org, [project])
Expand All @@ -635,7 +634,6 @@ export async function findSelectorIssue(
],
);
}
assertIssueInScope(org, issue);
return issue;
}

Expand Down Expand Up @@ -665,22 +663,18 @@ async function resolveIssueSearch(
throw new ContextError("Organization", commandHint);
}
const { org } = resolved;
const scopeProject = getTargetScope()?.project;
const { data: issues, nextCursor } = await listIssuesPaginated(org, "", {
query,
perPage: SEARCH_CANDIDATES,
collapse: ISSUE_DETAIL_COLLAPSE,
projects: scopeProject
? await resolveProjectIdsInOrg(org, [scopeProject])
: undefined,
});
const [issue] = issues;
if (issue && issues.length === 1) {
assertIssueInScope(org, issue);
return { org, issue };
}

// In a project scope, the search ran in that project alone.
// In a project scope, the transport filters the search to that project.
const scopeProject = getTargetScope()?.project;
const searched = scopeProject ? `${org}/${scopeProject}` : org;
const listCommand = sentry`issue list ${org}/${scopeProject ?? ""} --query ${shellQuote(query)}`;
if (!issue) {
Expand Down
26 changes: 1 addition & 25 deletions packages/cli/src/commands/replay/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ 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 @@ -165,8 +161,7 @@ type ReplayProjectScope = {
};

/**
* Reject a replay that is not in the project the user named, or outside the
* invocation's target scope (`limitToTarget`).
* Reject a replay that is not in the project the user named.
*
* 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 @@ -176,7 +171,6 @@ 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 @@ -209,24 +203,6 @@ 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}`);
}

async function fetchReplayActivity(
org: string,
replay: ReplayDetails,
Expand Down
31 changes: 10 additions & 21 deletions packages/cli/src/lib/api/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ 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 @@ -61,16 +60,12 @@ 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 @@ -141,42 +136,36 @@ 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 {
data = unwrapResult<typeof data>(result, "Failed to resolve event ID");
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,
};
} 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
24 changes: 8 additions & 16 deletions packages/cli/src/lib/api/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ import {
} from "../custom-ca.js";
import { applyCustomHeaders } from "../custom-headers.js";
import { ApiError, ValidationError } from "../errors.js";
import { assertIssueInScope, assertOrgInScope } from "../target-scope.js";
import { getSdkConfig } from "../sentry-client.js";
import { withTargetScope } from "../target-scope.js";

import {
getOrgSdkConfig,
Expand Down Expand Up @@ -326,24 +327,19 @@ export async function listIssuesAllPages(
* @param orgSlug - Organization slug (used for region routing)
* @param issueId - Numeric issue ID
* @param options - Optional collapse fields to skip expensive backend queries
* @throws {ResolutionError} When the issue is outside the invocation's
* target scope (`limitToTarget`)
*/
export async function getIssueInOrg(
orgSlug: string,
issueId: string,
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
assertOrgInScope(orgSlug, `Issue ${issueId}`);
const collapse = toIssueDetailsCollapse(options?.collapse);
const result = await getOrganizationIssue({
...getOrgSdkConfig(),
path: { organization_id_or_slug: orgSlug, issue_id: issueId },
...(collapse && { query: { collapse } }),
});
const issue = unwrapResult<SentryIssue>(result, "Failed to get issue");
assertIssueInScope(orgSlug, issue);
return issue;
return unwrapResult<SentryIssue>(result, "Failed to get issue");
}

/**
Expand Down Expand Up @@ -404,16 +400,13 @@ export async function findIssueInOrgs(
* @param orgSlug - Organization slug
* @param shortId - Short ID (e.g., "CLI-G5", "SPOTLIGHT-ELECTRON-4D")
* @param options - Optional collapse fields to skip expensive backend queries
* @throws {ResolutionError} When the issue is outside the invocation's
* target scope (`limitToTarget`)
*/
export async function getIssueByShortId(
orgSlug: string,
shortId: string,
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
const normalizedShortId = shortId.toUpperCase();
assertOrgInScope(orgSlug, `Issue ${normalizedShortId}`);
const config = getOrgSdkConfig();

let data: { group?: SentryIssue };
Expand Down Expand Up @@ -453,7 +446,6 @@ export async function getIssueByShortId(
"Issue not found",
);
}
assertIssueInScope(orgSlug, data.group);
return data.group;
}

Expand Down Expand Up @@ -759,13 +751,13 @@ export async function getSharedIssue(
// The share URL's host may not be the logged-in one, so this goes out
// without the authenticated transport and its bearer token.
let response: Response | undefined;
const fetchUnauthenticated = async (
input: string | URL | Request,
init?: RequestInit,
) => {
// It still applies the invocation's target scope (`limitToTarget`), whose
// own project lookups need the token, so they go through the
// authenticated transport, which refuses an untrusted host.
const fetchUnauthenticated = withTargetScope(async (input, init) => {
response = await customFetch(input, init);
return response;
};
}, getSdkConfig(normalizedBase).fetch);

let result: Awaited<ReturnType<typeof getOrganizationSharedIssue>>;
try {
Expand Down
10 changes: 8 additions & 2 deletions packages/cli/src/lib/api/preprod-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { getAuthToken } from "../db/auth.js";
import { ApiError, TimeoutError, ValidationError } from "../errors.js";
import { logger } from "../logger.js";
import { resolveOrgRegion } from "../region.js";
import { withTargetScope } from "../target-scope.js";
import {
ASSEMBLE_MAX_WAIT_MS,
ASSEMBLE_POLL_INTERVAL_MS,
Expand Down Expand Up @@ -175,14 +176,18 @@ export async function downloadBuildArtifact(
destPath: string,
): Promise<void> {
const headers: Record<string, string> = {};
// A download from the API goes out with the token, so the invocation's
// target scope applies to it; a presigned URL elsewhere carries neither.
let send = customFetch;
if (isRegionOrigin(url, regionUrl)) {
send = withTargetScope(customFetch);
const token = getAuthToken();
if (token) {
headers["Authorization"] = formatAuthHeader(token);
}
}

const response = await customFetch(url, { headers });
const response = await send(url, { headers });
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
if (!(response.ok && response.body)) {
throw new ApiError(
"Failed to download build artifact",
Expand Down Expand Up @@ -633,7 +638,8 @@ export async function openSnapshotArchive(
if (token) {
headers["Authorization"] = formatAuthHeader(token);
}
const response = await customFetch(url, { headers });
// Sent with the token outside the transport, so apply the target scope.
const response = await withTargetScope(customFetch)(url, { headers });
if (!response.ok) {
throw new ApiError(
"Failed to download snapshot archive",
Expand Down
Loading
Loading