From c89f0960ebc72298eb1d181aa4b75f33f4dbfa24 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:40:59 +0000 Subject: [PATCH 1/9] fix(mcp): Enforce the session scope in the API transport The org/project limit of `limitToTarget` was checked call by call: each lookup that an ID alone names (issues, short IDs, events, traces, replays, Feedback, `@latest`) had its own assert, and each list had to remember to pass the scope's project. Anything new, or anything missed (`trace logs `, `sentry api organizations//...`, the preprod downloads that send the token around the transport), was not checked at all. The limit is now enforced once, where every request the CLI sends with a credential goes: `scopeRequest` in `target-scope.ts`, called from the authenticated fetch in `sentry-client.ts` (before the response cache, so cached responses are checked too) and, through `withTargetScope`, from the two fetches that send around it (share links, preprod downloads). A scoped invocation fails closed: - Paths must name the scope's organization and, in a project scope, its project. - In a project scope, organization endpoints that return every project's data are filtered to the scope's project (a missing `project` or `-1` gets the scope's ID; another project is refused). - Lookups by an ID alone are checked by their response's project; a request that reads or changes what an ID names (`PUT issues//`, `issues//events/`, `trace-meta`, `trace-logs`) looks it up first. - Any other request, such as one to an endpoint added later, is refused before it is sent. The rules are in `target-scope-rules.ts`. The per-command asserts and project narrowing from the two previous commits are removed; only the `event view` fallback keeps rethrowing a `ResolutionError`, so a refusal isn't turned into an org-wide search. `target-scope-coverage.test.ts` fails when a source file fetches around the transport without the scope. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/library-usage.md | 2 +- packages/cli/src/commands/event/view.ts | 16 +- packages/cli/src/commands/feedback/utils.ts | 13 +- packages/cli/src/commands/issue/utils.ts | 16 +- packages/cli/src/commands/replay/view.ts | 26 +- packages/cli/src/lib/api/events.ts | 31 +- packages/cli/src/lib/api/issues.ts | 21 +- packages/cli/src/lib/api/preprod-artifacts.ts | 10 +- packages/cli/src/lib/api/replays.ts | 2 - packages/cli/src/lib/api/traces.ts | 38 -- packages/cli/src/lib/sentry-client.ts | 35 +- packages/cli/src/lib/target-scope-rules.ts | 375 ++++++++++++++++ packages/cli/src/lib/target-scope.ts | 402 ++++++++++++++++-- .../cli/test/lib/sdk-limit-to-target.test.ts | 24 +- .../test/lib/target-scope-coverage.test.ts | 77 ++++ packages/cli/test/lib/target-scope.test.ts | 306 ++++++++++--- 16 files changed, 1129 insertions(+), 265 deletions(-) create mode 100644 packages/cli/src/lib/target-scope-rules.ts create mode 100644 packages/cli/test/lib/target-scope-coverage.test.ts diff --git a/apps/cli-docs/src/content/docs/library-usage.md b/apps/cli-docs/src/content/docs/library-usage.md index feb5e5604c..0447a9fe84 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -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. 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` | — | Extra HTTP headers for self-hosted instances behind a reverse proxy (same as [`SENTRY_CUSTOM_HEADERS`](../configuration/#sentry_custom_headers)); ignored for sentry.io | diff --git a/packages/cli/src/commands/event/view.ts b/packages/cli/src/commands/event/view.ts index b2a7a76fb2..6a96044b0c 100644 --- a/packages/cli/src/commands/event/view.ts +++ b/packages/cli/src/commands/event/view.ts @@ -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"; @@ -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 @@ -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), diff --git a/packages/cli/src/commands/feedback/utils.ts b/packages/cli/src/commands/feedback/utils.ts index 650b13e949..1a9157d65b 100644 --- a/packages/cli/src/commands/feedback/utils.ts +++ b/packages/cli/src/commands/feedback/utils.ts @@ -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"; @@ -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) { @@ -77,7 +67,6 @@ async function resolveFeedbackSelector( ); } - assertIssueInScope(org, latest); setOrgProjectContext( [org], latest.project?.slug ? [latest.project.slug] : [], diff --git a/packages/cli/src/commands/issue/utils.ts b/packages/cli/src/commands/issue/utils.ts index 7a90bc8038..1f60e9ecf0 100644 --- a/packages/cli/src/commands/issue/utils.ts +++ b/packages/cli/src/commands/issue/utils.ts @@ -58,7 +58,6 @@ 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 { setOrgProjectContext } from "../../lib/telemetry.js"; import { isAllDigits, shellQuote } from "../../lib/utils.js"; import type { SentryIssue } from "../../types/index.js"; @@ -600,15 +599,14 @@ async function resolveSelector( * @param org - Organization slug * @param project - Project slug to look in, selected by its numeric ID * (a `project:` 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 { const projects = project ? await resolveProjectIdsInOrg(org, [project]) @@ -635,7 +633,6 @@ export async function findSelectorIssue( ], ); } - assertIssueInScope(org, issue); return issue; } @@ -665,18 +662,13 @@ 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 }; } diff --git a/packages/cli/src/commands/replay/view.ts b/packages/cli/src/commands/replay/view.ts index 609a23ba9c..a5d113c865 100644 --- a/packages/cli/src/commands/replay/view.ts +++ b/packages/cli/src/commands/replay/view.ts @@ -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, @@ -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 `//` target * has to be checked against the replay's own project. @@ -176,7 +171,6 @@ export async function validateReplayProjectScope( ): Promise { const { expectedProjectId, org, project, replay, replayId } = scope; const command = scope.command ?? "view"; - await assertReplayInTargetScope(org, replayId, replay); if (!project) { return; } @@ -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 { - 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, diff --git a/packages/cli/src/lib/api/events.ts b/packages/cli/src/lib/api/events.ts index 24eb32631d..29af5164c9 100644 --- a/packages/cli/src/lib/api/events.ts +++ b/packages/cli/src/lib/api/events.ts @@ -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, @@ -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 { - assertProjectInScope(orgSlug, projectSlug, `Event ${eventId}`); const config = getOrgSdkConfig(); const result = await getProjectEvent({ @@ -141,15 +136,11 @@ 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 { - assertOrgInScope(orgSlug, `Event ${eventId}`); const config = getOrgSdkConfig(); const result = await sdkResolveAnEventId({ @@ -157,9 +148,17 @@ export async function resolveEventInOrg( path: { organization_id_or_slug: orgSlug, event_id: eventId }, }); - let data: { organizationSlug: string; projectSlug: string; event: unknown }; try { - data = unwrapResult(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) { @@ -167,16 +166,6 @@ export async function resolveEventInOrg( } 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}. */ diff --git a/packages/cli/src/lib/api/issues.ts b/packages/cli/src/lib/api/issues.ts index 2624caed70..c7e77a969c 100644 --- a/packages/cli/src/lib/api/issues.ts +++ b/packages/cli/src/lib/api/issues.ts @@ -31,7 +31,7 @@ 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 { withTargetScope } from "../target-scope.js"; import { getOrgSdkConfig, @@ -326,24 +326,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 { - 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(result, "Failed to get issue"); - assertIssueInScope(orgSlug, issue); - return issue; + return unwrapResult(result, "Failed to get issue"); } /** @@ -404,8 +399,6 @@ 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, @@ -413,7 +406,6 @@ export async function getIssueByShortId( options?: { collapse?: IssueCollapseField[] }, ): Promise { const normalizedShortId = shortId.toUpperCase(); - assertOrgInScope(orgSlug, `Issue ${normalizedShortId}`); const config = getOrgSdkConfig(); let data: { group?: SentryIssue }; @@ -453,7 +445,6 @@ export async function getIssueByShortId( "Issue not found", ); } - assertIssueInScope(orgSlug, data.group); return data.group; } @@ -759,13 +750,11 @@ 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`). + const fetchUnauthenticated = withTargetScope(async (input, init) => { response = await customFetch(input, init); return response; - }; + }); let result: Awaited>; try { diff --git a/packages/cli/src/lib/api/preprod-artifacts.ts b/packages/cli/src/lib/api/preprod-artifacts.ts index 8c25581c2d..21e49876ac 100644 --- a/packages/cli/src/lib/api/preprod-artifacts.ts +++ b/packages/cli/src/lib/api/preprod-artifacts.ts @@ -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, @@ -175,14 +176,18 @@ export async function downloadBuildArtifact( destPath: string, ): Promise { const headers: Record = {}; + // 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 }); if (!(response.ok && response.body)) { throw new ApiError( "Failed to download build artifact", @@ -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", diff --git a/packages/cli/src/lib/api/replays.ts b/packages/cli/src/lib/api/replays.ts index b9acb364ae..cfd0ae7f5c 100644 --- a/packages/cli/src/lib/api/replays.ts +++ b/packages/cli/src/lib/api/replays.ts @@ -26,7 +26,6 @@ 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, @@ -306,7 +305,6 @@ export async function resolveReplay( replayOrTraceId: string, options: Pick = {}, ): Promise { - assertOrgInScope(orgSlug, `Replay ${replayOrTraceId}`); try { return await getReplay(orgSlug, replayOrTraceId); } catch (error) { diff --git a/packages/cli/src/lib/api/traces.ts b/packages/cli/src/lib/api/traces.ts index 314c02366a..ac93958d48 100644 --- a/packages/cli/src/lib/api/traces.ts +++ b/packages/cli/src/lib/api/traces.ts @@ -37,11 +37,6 @@ 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 { @@ -163,48 +158,15 @@ 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 { - 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 { const regionUrl = await resolveOrgRegion(orgSlug); const shared = { additionalAttributes: options.additionalAttributes }; diff --git a/packages/cli/src/lib/sentry-client.ts b/packages/cli/src/lib/sentry-client.ts index 69dde02a79..7981c25c95 100644 --- a/packages/cli/src/lib/sentry-client.ts +++ b/packages/cli/src/lib/sentry-client.ts @@ -65,6 +65,7 @@ import { lookupCachedResponse, storeCachedResponse, } from "./response-cache.js"; +import { scopeRequest } from "./target-scope.js"; import { isManualHttpTracing, withTracingSpan } from "./telemetry.js"; import { assertCredentialScope, @@ -504,17 +505,26 @@ function createAuthenticatedFetch( const method = init?.method ?? (input instanceof Request ? input.method : "GET"); const path = extractUrlPath(input); - const response = await transport.request(input, init, { + // Keyed by the SDK's Request, so read from `input` itself. + const responseBody = + method.toUpperCase() !== "GET" + ? "stream" + : ((input instanceof Request + ? sdkResponseBodyModes.get(input) + : undefined) ?? (options.bufferResponseBody ? "buffer" : "stream")); + // A target-scoped invocation (`limitToTarget`) refuses a request + // outside its scope here, for every caller. Its own lookups come back + // through this fetch. + const scoped = await scopeRequest(input, init, (lookup) => + scopedFetch(lookup), + ); + if (scoped.response) { + return scoped.response; + } + const response = await transport.request(scoped.input, init, { validateRedirects: options.validatedRedirects === true, idempotent: options.idempotent === true, - // Keyed by the SDK's Request, so read from `input` itself. - responseBody: - method.toUpperCase() !== "GET" - ? "stream" - : ((input instanceof Request - ? sdkResponseBodyModes.get(input) - : undefined) ?? - (options.bufferResponseBody ? "buffer" : "stream")), + responseBody, }); if (response.status === 429) { throw new RateLimitError( @@ -523,16 +533,21 @@ function createAuthenticatedFetch( await readErrorDetail(response), ); } + await scoped.verify(response); return response; }; // Every API response, fresh or cached, seeds shell completion, so no API // function has to remember to. Awaited so a command that exits right // after its request still stores the entities. - return async (input, init) => + const scopedFetch = async ( + input: Request | string | URL, + init?: RequestInit, + ): Promise => await seedCompletions( extractInputUrl(input), await authenticatedFetch(input, init), ); + return scopedFetch; } /** Singleton authenticated fetch instance - reused across all requests */ diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts new file mode 100644 index 0000000000..1e50ac6303 --- /dev/null +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -0,0 +1,375 @@ +/** + * The endpoint rules of a target-scoped invocation (`limitToTarget`), read + * by `scopeRequest` in `target-scope.ts`. Paths are relative to `/api/0/`: + * `:name` is one segment, `**` is any number of them. + * + * In a project scope, a request no rule matches is refused. Add a rule when + * a command needs a new endpoint, and pick how it stays in the project. + */ + +/** How a matched request stays in the scope's project. */ +type ScopeEnforcement = + /** The path names the scope's project, as `:project`. */ + | { kind: "project-path" } + /** + * An organization endpoint that takes a `project` filter: one is added + * when the request has none, and another project is refused. + */ + | { kind: "project-filter" } + /** + * A lookup by an ID alone: the response's projects (slugs or numeric IDs) + * must include the scope's. + */ + | { + kind: "response"; + projects: (body: unknown) => (string | undefined)[]; + /** A response that names no project (an empty trace) is let through. */ + emptyIsInScope?: boolean; + /** The path the response proves in scope, for {@link LookUpFirst}. */ + path?: (params: Record) => string; + } + | LookUpFirst; + +/** + * A request that reads or changes something an ID names, without saying + * its project: what it names is looked up first, through a `response` + * rule. A request that names nothing to look up is refused. + */ +type LookUpFirst = { + kind: "look-up-first"; + lookups: ( + params: Record, + url: URL, + ) => { path: string; query?: string }[]; +}; + +export type ScopeRule = { + pattern: string; + /** Methods the rule covers; reads (`GET`, `HEAD`) when omitted. */ + methods?: readonly string[]; + /** What the request names, for the error (`Issue 123`). */ + subject?: (params: Record) => string; + enforce: ScopeEnforcement; +}; + +type SimpleRule = Pick; + +const READS = ["GET", "HEAD"] as const; +const ANY_METHOD = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"] as const; + +/** Path prefixes whose next segment is an organization. */ +export const ORG_PATH_PREFIXES: ReadonlySet = new Set([ + "organizations", + "projects", + "teams", + "customers", +]); + +/** Account reads that name no organization, allowed in any scope. */ +export const ACCOUNT_READS: readonly SimpleRule[] = [ + // The API index: the token's user and scopes. + { pattern: "" }, + { pattern: "auth/" }, + { pattern: "users/me/" }, +]; + +/** + * Organization settings a project scope reads, with no project's issues, + * events or other data in them. + */ +export const ORG_SETTINGS: readonly SimpleRule[] = [ + { pattern: "organizations/:org/" }, + { pattern: "organizations/:org/projects/" }, + { pattern: "organizations/:org/teams/" }, + { pattern: "organizations/:org/members/" }, + { pattern: "organizations/:org/environments/" }, + { pattern: "organizations/:org/integrations/" }, + { pattern: "organizations/:org/integrations/:integration/" }, + { pattern: "organizations/:org/repos/" }, + { pattern: "organizations/:org/sentry-app-components/" }, + { pattern: "organizations/:org/dashboards/" }, + { pattern: "organizations/:org/dashboards/:dashboard/" }, + { pattern: "organizations/:org/dashboards/:dashboard/revisions/" }, + { pattern: "organizations/:org/workflows/:workflow/" }, +]; + +/** `value` as an object, or `{}` when it is not one. */ +export function record(value: unknown): Record { + return typeof value === "object" && value !== null + ? (value as Record) + : {}; +} + +function ref(value: unknown): string | undefined { + return typeof value === "string" || typeof value === "number" + ? String(value) + : undefined; +} + +/** `{ project: { slug, id } }`, as issues and monitors carry it. */ +function projectOf(body: unknown): (string | undefined)[] { + const project = record(record(body).project); + return [ref(project.slug), ref(project.id)]; +} + +/** Every `project_slug`/`project_id` of a trace's span tree. */ +function traceProjects(spans: unknown): (string | undefined)[] { + if (!Array.isArray(spans)) { + return [undefined]; + } + return spans.flatMap((span) => { + const fields = record(span); + return [ + ref(fields.project_slug), + ref(fields.project_id), + ...(Array.isArray(fields.children) ? traceProjects(fields.children) : []), + ]; + }); +} + +/** `organizations////`, from a rule's params. */ +function orgPath(kind: string, param: string) { + return (params: Record): string => + `organizations/${encodeURIComponent(params.org ?? "")}/${kind}/${encodeURIComponent(params[param] ?? "")}/`; +} + +const issuePath = orgPath("issues", "issue"); +const tracePath = orgPath("trace", "trace"); +const monitorPath = orgPath("monitors", "monitor"); +const detectorPath = orgPath("detectors", "detector"); +const releasePath = orgPath("releases", "version"); + +/** A trace lookup for `trace-meta` and `trace-logs`, over the same period. */ +function traceLookup( + params: Record, + url: URL, +): { path: string; query: string } { + const query = new URLSearchParams(); + for (const name of ["statsPeriod", "start", "end"]) { + const value = url.searchParams.get(name); + if (value) { + query.set(name, value); + } + } + if (!query.has("statsPeriod") && !query.has("start")) { + query.set("statsPeriod", "14d"); + } + return { path: tracePath(params), query: query.toString() }; +} + +const PROJECT_FILTERED = [ + "issues/", + "events/", + "events-timeseries/", + "events-dropped/", + "trace-items/attributes/", + "replays/", + "replay-count/", + "monitors/", + "detectors/", + "workflows/", + "releases/", + "agents/conversations/", +].map((path): ScopeRule => ({ + pattern: `organizations/:org/${path}`, + // Bulk issue changes (`PUT issues/?id=...`) are filtered the same way. + methods: path === "issues/" ? ["GET", "HEAD", "PUT", "DELETE"] : READS, + enforce: { kind: "project-filter" }, +})); + +/** The rules of a project scope, first match wins. */ +export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ + { + pattern: "projects/:org/:project/**", + methods: ANY_METHOD, + subject: ({ org, project }) => `Project ${org}/${project}`, + enforce: { kind: "project-path" }, + }, + { + pattern: "organizations/:org/projects/:project/**", + methods: ANY_METHOD, + subject: ({ org, project }) => `Project ${org}/${project}`, + enforce: { kind: "project-path" }, + }, + { + pattern: "organizations/:org/issues/:issue/", + subject: ({ issue }) => `Issue ${issue}`, + enforce: { kind: "response", projects: projectOf, path: issuePath }, + }, + { + pattern: "organizations/:org/issues/:issue/**", + methods: ANY_METHOD, + subject: ({ issue }) => `Issue ${issue}`, + enforce: { + kind: "look-up-first", + lookups: (params) => [{ path: issuePath(params) }], + }, + }, + { + pattern: "organizations/:org/shortids/:issue/", + subject: ({ issue }) => `Issue ${issue?.toUpperCase()}`, + enforce: { + kind: "response", + projects: (body) => [ + ref(record(body).projectSlug), + ...projectOf(record(body).group), + ], + }, + }, + { + pattern: "organizations/:org/shared/issues/:share/", + subject: ({ share }) => `Shared issue ${share}`, + enforce: { kind: "response", projects: projectOf }, + }, + { + pattern: "organizations/:org/eventids/:event/", + subject: ({ event }) => `Event ${event}`, + enforce: { + kind: "response", + projects: (body) => [ref(record(body).projectSlug)], + }, + }, + { + // The trace endpoints read every project of the trace, whatever + // `project` filter they get: a trace is in scope when one of its + // spans is in the scope's project. + pattern: "organizations/:org/trace/:trace/", + subject: ({ trace }) => `Trace ${trace}`, + enforce: { + kind: "response", + projects: traceProjects, + emptyIsInScope: true, + path: tracePath, + }, + }, + { + pattern: "organizations/:org/trace-meta/:trace/", + subject: ({ trace }) => `Trace ${trace}`, + enforce: { + kind: "look-up-first", + lookups: (params, url) => [traceLookup(params, url)], + }, + }, + { + pattern: "organizations/:org/trace-logs/", + subject: () => "Trace logs", + enforce: { + kind: "look-up-first", + lookups: (params, url) => + url.searchParams + .getAll("traceId") + .map((trace) => traceLookup({ ...params, trace }, url)), + }, + }, + { + pattern: "organizations/:org/replays/:replay/", + subject: ({ replay }) => `Replay ${replay}`, + enforce: { + kind: "response", + projects: (body) => [ref(record(record(body).data).project_id)], + }, + }, + { + pattern: "organizations/:org/monitors/:monitor/", + subject: ({ monitor }) => `Monitor ${monitor}`, + enforce: { kind: "response", projects: projectOf, path: monitorPath }, + }, + { + pattern: "organizations/:org/monitors/:monitor/**", + methods: ANY_METHOD, + subject: ({ monitor }) => `Monitor ${monitor}`, + enforce: { + kind: "look-up-first", + lookups: (params) => [{ path: monitorPath(params) }], + }, + }, + { + pattern: "organizations/:org/detectors/:detector/", + subject: ({ detector }) => `Alert ${detector}`, + enforce: { + kind: "response", + projects: (body) => [ref(record(body).projectId)], + path: detectorPath, + }, + }, + { + pattern: "organizations/:org/detectors/:detector/**", + methods: ANY_METHOD, + subject: ({ detector }) => `Alert ${detector}`, + enforce: { + kind: "look-up-first", + lookups: (params) => [{ path: detectorPath(params) }], + }, + }, + { + // A release can span projects; one with the scope's project is in it. + pattern: "organizations/:org/releases/:version/", + subject: ({ version }) => `Release ${version}`, + enforce: { + kind: "response", + projects: (body) => { + const projects = record(body).projects; + return Array.isArray(projects) + ? projects.flatMap((project) => [ + ref(record(project).slug), + ref(record(project).id), + ]) + : [undefined]; + }, + path: releasePath, + }, + }, + { + pattern: "organizations/:org/releases/:version/**", + subject: ({ version }) => `Release ${version}`, + enforce: { + kind: "look-up-first", + lookups: (params) => [{ path: releasePath(params) }], + }, + }, + ...PROJECT_FILTERED, +]; + +type Match = { rule: T; params: Record }; + +/** Match path segments against a pattern; `undefined` when they differ. */ +function matchPattern( + pattern: string, + segments: readonly string[], +): Record | undefined { + const parts = pattern.split("/").filter(Boolean); + const params: Record = {}; + for (const [index, part] of parts.entries()) { + if (part === "**") { + return params; + } + const segment = segments[index]; + if (segment === undefined) { + return; + } + if (part.startsWith(":")) { + params[part.slice(1)] = segment; + } else if (part !== segment) { + return; + } + } + return parts.length === segments.length ? params : undefined; +} + +/** The first rule that covers `method` and `segments`. */ +export function matchScopeRule( + rules: readonly T[], + method: string, + segments: readonly string[], +): Match | undefined { + for (const rule of rules) { + if (!(rule.methods ?? READS).includes(method)) { + continue; + } + const params = matchPattern(rule.pattern, segments); + if (params) { + return { rule, params }; + } + } + return; +} diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 86cb5bf2cc..0422ce194a 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -2,17 +2,46 @@ * The organization and project an SDK invocation is limited to: the `org` * and `project` of `createSentrySDK()`, unless `limitToTarget` is `false`. * - * The caller checks the targets a call names, but not what an ID alone - * names: a numeric issue ID, an event, trace or replay ID, a share link, or a - * selector such as `@latest` says nothing about its project. Lookups check - * what they find with {@link assertProjectInScope} (or - * {@link assertIssueInScope}) before a command reads or changes it. + * The limit is enforced in one place, the API transport: every request the + * CLI sends with a credential goes through {@link scopeRequest}, so no + * command or API function checks it on its own. A scoped invocation fails + * closed: a request is sent only when a rule below says how it stays in + * scope, and any other request, such as one to an endpoint added later, is + * refused before it is sent. + * + * How a request stays in scope: + * + * - Its path names the scope's organization (`organizations//...`, + * `projects//...`) and, in a project scope, its project + * (`projects///...`). + * - In a project scope, an organization endpoint that returns data of every + * project (issue, event, replay and release lists) is filtered to the + * scope's project: a request without a `project` filter gets one, and a + * request with another project is refused. + * - In a project scope, a lookup by an ID alone (an issue, event, trace, + * replay, monitor or alert ID, a short ID, a share link) is checked + * against the project of what it finds, before the command sees it. A + * request that reads or changes something an ID names first looks it up. + * - A few account reads every invocation may need ({@link ACCOUNT_READS}) + * and organization settings with no project data ({@link ORG_SETTINGS}). */ -import type { SentryIssue } from "../types/index.js"; +import type { ScopeRule } from "./target-scope-rules.js"; import { sentry } from "./app-identity.js"; import { getEnv, SCOPE_ORG_ENV_VAR, SCOPE_PROJECT_ENV_VAR } from "./env.js"; import { ResolutionError } from "./errors.js"; +import { extractInputUrl } from "./fetch-input.js"; +import { logger } from "./logger.js"; +import { + ACCOUNT_READS, + matchScopeRule, + ORG_PATH_PREFIXES, + ORG_SETTINGS, + PROJECT_SCOPE_RULES, + record, +} from "./target-scope-rules.js"; + +const log = logger.withTag("target-scope"); /** The organization, and project if any, an invocation is limited to. */ type TargetScope = { org: string; project?: string }; @@ -46,8 +75,12 @@ function listCommand(subject: string, scope: TargetScope, target: string) { return sentry`issue list ${listTarget}`; } +function scopeLabel(scope: TargetScope): string { + return scope.project ? `${scope.org}/${scope.project}` : scope.org; +} + function outsideScope(subject: string, scope: TargetScope): ResolutionError { - const target = scope.project ? `${scope.org}/${scope.project}` : scope.org; + const target = scopeLabel(scope); return new ResolutionError( subject, `is outside this session's scope (${target})`, @@ -56,54 +89,341 @@ function outsideScope(subject: string, scope: TargetScope): ResolutionError { ); } +/** Refuse an organization outside the scope, before a request to it. */ +function assertOrgInScope( + org: string, + subject: string, + scope: TargetScope, +): void { + if (org !== scope.org) { + throw outsideScope(subject, scope); + } +} + +/** A fetch that sends a request the scope already allows. */ +type Send = (input: string) => Promise; + +/** What the transport sends for a request, and the check of its response. */ +type ScopedRequest = { + /** The request to send: the caller's, or one with a `project` filter. */ + input: Request | string | URL; + /** A response to return instead of sending it (a failed lookup). */ + response?: Response; + /** + * Refuse a response outside the scope. + * @throws {ResolutionError} When it is outside the scope + */ + verify: (response: Response) => Promise; +}; + +const NOTHING_TO_VERIFY = async (): Promise => { + // The request alone keeps it in scope. +}; + +/** The scope projects' IDs this process looked up, by scope and host. */ +const projectIds = new Map>(); + +/** Paths a `response` rule found in scope, by scope and host. */ +const foundInScope = new Set(); + +/** @internal Test-only: forget the lookups of earlier invocations. */ +export function __resetScopeLookupsForTests(): void { + projectIds.clear(); + foundInScope.clear(); +} + +/** The parts of a request a rule reads. */ +type RequestContext = { + scope: TargetScope & { project: string }; + url: URL; + method: string; + send: Send; +}; + +function lookupKey({ scope, url }: RequestContext, path: string): string { + return `${scopeLabel(scope)}|${url.origin}/api/0/${path}`; +} + +/** The numeric ID of the scope's project, looked up once per process. */ +function scopeProjectId(context: RequestContext): Promise { + const { scope, url, send } = context; + const path = `projects/${encodeURIComponent(scope.org)}/${encodeURIComponent(scope.project)}/`; + const key = lookupKey(context, path); + let pending = projectIds.get(key); + if (!pending) { + pending = (async () => { + const response = await send(`${url.origin}/api/0/${path}`); + const id = response.ok ? record(await readJson(response)).id : undefined; + if (typeof id !== "string" && typeof id !== "number") { + throw new ResolutionError( + `Project ${scopeLabel(scope)}`, + `could not be looked up (HTTP ${response.status})`, + sentry`project view ${scopeLabel(scope)}`, + ["This session filters its requests by the project's ID."], + ); + } + return String(id); + })(); + projectIds.set(key, pending); + pending.catch(() => projectIds.delete(key)); + } + return pending; +} + +/** Project slugs are never entirely numeric, so digits are a project ID. */ +const NUMERIC_ID = /^\d+$/; + +/** + * Whether one of `refs`, project slugs or numeric IDs, is the scope's + * project. The scope project's ID is looked up only when `refs` has no slug. + */ +async function anyScopeProject( + context: RequestContext, + refs: readonly (string | undefined)[], +): Promise { + const known = refs.filter((ref) => ref !== undefined); + const ids = known.filter((ref) => NUMERIC_ID.test(ref)); + if (ids.length < known.length) { + return known.includes(context.scope.project); + } + return ids.length > 0 && ids.includes(await scopeProjectId(context)); +} + +/** The `project` filter that asks for every project. */ +const ALL_PROJECTS = "-1"; + /** - * Refuse an organization outside the invocation's limit, before a request - * to it. + * Filter an organization endpoint to the scope's project: a request with + * no filter, or one for every project (`-1`), gets the scope's; a request + * for another project is refused. + */ +async function filterToProject( + context: RequestContext, + input: Request | string | URL, + subject: string, +): Promise { + const { url, scope } = context; + const requested = [ + ...url.searchParams.getAll("project"), + ...url.searchParams.getAll("projectSlug"), + ].filter((project) => project !== ALL_PROJECTS); + if (requested.length > 0) { + for (const project of requested) { + if (!(await anyScopeProject(context, [project]))) { + throw outsideScope(subject, scope); + } + } + if (!url.searchParams.getAll("project").includes(ALL_PROJECTS)) { + return input; + } + } + const filtered = new URL(url); + const kept = filtered.searchParams + .getAll("project") + .filter((project) => project !== ALL_PROJECTS); + filtered.searchParams.delete("project"); + for (const project of kept) { + filtered.searchParams.append("project", project); + } + if (requested.length === 0) { + filtered.searchParams.append("project", await scopeProjectId(context)); + } + return input instanceof Request + ? new Request(filtered, input) + : filtered.toString(); +} + +/** A response body as JSON, or `undefined` when it is not JSON. */ +async function readJson(response: Response): Promise { + try { + return await response.clone().json(); + } catch (error) { + // Not JSON, so it names no project: a `response` rule refuses it. + log.debug(`Response of ${response.url} is not JSON`, error); + return; + } +} + +/** + * Look up what a request names before it reads or changes it, unless an + * earlier lookup found it in scope. The lookup goes through `send`, so its + * `response` rule refuses it when it is outside the scope. * - * @param org - The organization a lookup asks - * @param subject - What is looked up, for the error (`Issue 123`) - * @throws {ResolutionError} When `org` is not the limit's organization + * @returns The failed lookup's response, to return instead, or `undefined` */ -export function assertOrgInScope(org: string, subject: string): void { - const scope = getTargetScope(); - if (scope && org !== scope.org) { - throw outsideScope(subject, scope); +async function lookUpFirst( + context: RequestContext, + { path, query }: { path: string; query?: string }, +): Promise { + if (foundInScope.has(lookupKey(context, path))) { + return; + } + const response = await context.send( + `${context.url.origin}/api/0/${path}${query ? `?${query}` : ""}`, + ); + if (!response.ok) { + return response; + } + if (!foundInScope.has(lookupKey(context, path))) { + // The lookup named no project (an empty trace): nothing to read. + throw outsideScope( + `${context.method} ${context.url.pathname}`, + context.scope, + ); + } + return; +} + +/** Remember that `path` is in scope, so later requests skip the lookup. */ +function rememberInScope(context: RequestContext, path: string): void { + foundInScope.add(lookupKey(context, path)); +} + +/** Apply a project-scope rule: the request to send, and its check. */ +async function applyRule( + rule: ScopeRule, + params: Record, + context: RequestContext, + input: Request | string | URL, +): Promise { + const { scope } = context; + const subject = + rule.subject?.(params) ?? `${context.method} ${context.url.pathname}`; + switch (rule.enforce.kind) { + case "project-path": + if (!(await anyScopeProject(context, [params.project]))) { + throw outsideScope(subject, scope); + } + return { input, verify: NOTHING_TO_VERIFY }; + case "project-filter": + return { + input: await filterToProject(context, input, subject), + verify: NOTHING_TO_VERIFY, + }; + case "response": { + const { projects, path, emptyIsInScope } = rule.enforce; + return { + input, + verify: async (response) => { + if (!response.ok) { + return; + } + const refs = projects(await readJson(response)); + // An empty result (`[]` for a trace) names no project's data. + if (refs.length === 0 && emptyIsInScope) { + return; + } + if (!(await anyScopeProject(context, refs))) { + throw outsideScope(subject, scope); + } + if (path) { + rememberInScope(context, path(params)); + } + }, + }; + } + case "look-up-first": { + const targets = rule.enforce.lookups(params, context.url); + if (targets.length === 0) { + throw outsideScope(subject, scope); + } + for (const target of targets) { + const failed = await lookUpFirst(context, target); + if (failed) { + return { input, response: failed, verify: NOTHING_TO_VERIFY }; + } + } + return { input, verify: NOTHING_TO_VERIFY }; + } + default: + throw outsideScope(subject, scope); } } /** - * Refuse something a lookup found outside the invocation's limit. Something - * whose project is unknown is refused in a project-limited invocation. + * Decide how a request stays in the invocation's scope. Every request the + * transport sends with a credential goes through here. * - * @param org - The organization it was found in - * @param project - The slug of its project, if known - * @param subject - What was found, for the error (`Event abc`) - * @throws {ResolutionError} When it is in another organization or project + * @param input - The request + * @param init - Its options, for the method + * @param send - Sends a lookup the scope needs (the scope project's ID, or + * what an ID names); its requests come through here too + * @returns The request to send and the check of its response + * @throws {ResolutionError} When the request is outside the scope */ -export function assertProjectInScope( - org: string, - project: string | undefined, - subject: string, -): void { - assertOrgInScope(org, subject); +export async function scopeRequest( + input: Request | string | URL, + init: RequestInit | undefined, + send: Send, +): Promise { const scope = getTargetScope(); - if (scope?.project && project !== scope.project) { + if (!scope) { + return { input, verify: NOTHING_TO_VERIFY }; + } + const url = new URL(extractInputUrl(input)); + const method = ( + init?.method ?? (input instanceof Request ? input.method : "GET") + ).toUpperCase(); + const subject = `${method} ${url.pathname}`; + const path = url.pathname.startsWith("/api/0/") + ? url.pathname.slice("/api/0/".length) + : undefined; + if (path === undefined) { throw outsideScope(subject, scope); } + const segments = path.split("/").filter(Boolean).map(decodeURIComponent); + + // Every organization path names the scope's organization. + const [prefix, org] = segments; + const namesOrg = prefix !== undefined && ORG_PATH_PREFIXES.has(prefix); + if (namesOrg && org !== undefined) { + assertOrgInScope(org, subject, scope); + } + if (matchScopeRule(ACCOUNT_READS, method, segments)) { + return { input, verify: NOTHING_TO_VERIFY }; + } + if (!scope.project) { + if (namesOrg && org !== undefined) { + return { input, verify: NOTHING_TO_VERIFY }; + } + throw outsideScope(subject, scope); + } + if (matchScopeRule(ORG_SETTINGS, method, segments)) { + return { input, verify: NOTHING_TO_VERIFY }; + } + const match = matchScopeRule(PROJECT_SCOPE_RULES, method, segments); + if (!match) { + throw outsideScope(subject, scope); + } + return await applyRule( + match.rule, + match.params, + { scope: { ...scope, project: scope.project }, url, method, send }, + input, + ); } /** - * Refuse an issue outside the invocation's limit, as - * {@link assertProjectInScope} does. - * - * @param org - The organization the issue was found in - * @param issue - The issue a lookup found - * @throws {ResolutionError} When the issue is in another organization or - * project + * Wrap a fetch that sends requests outside the authenticated transport + * (a share link's) so the invocation's scope applies to it too. */ -export function assertIssueInScope( - org: string, - issue: Pick, -): void { - assertProjectInScope(org, issue.project?.slug, `Issue ${issue.id}`); +export function withTargetScope( + fetchFn: ( + input: Request | string | URL, + init?: RequestInit, + ) => Promise, +): (input: Request | string | URL, init?: RequestInit) => Promise { + const scoped = async ( + input: Request | string | URL, + init?: RequestInit, + ): Promise => { + const request = await scopeRequest(input, init, (lookup) => scoped(lookup)); + if (request.response) { + return request.response; + } + const response = await fetchFn(request.input, init); + await request.verify(response); + return response; + }; + return scoped; } diff --git a/packages/cli/test/lib/sdk-limit-to-target.test.ts b/packages/cli/test/lib/sdk-limit-to-target.test.ts index 83120d8958..cc6b3f4f7a 100644 --- a/packages/cli/test/lib/sdk-limit-to-target.test.ts +++ b/packages/cli/test/lib/sdk-limit-to-target.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, test } from "vitest"; import createSentrySDK from "../../src/index.js"; +import { __resetScopeLookupsForTests } from "../../src/lib/target-scope.js"; import issueFixture from "../fixtures/issue.json"; import { mockFetch, useTestConfigDir } from "../helpers.js"; @@ -30,14 +31,17 @@ function sentryApi(): typeof fetch { }); } -function viewIssue(options: { limitToTarget?: boolean }): Promise { - const sdk = createSentrySDK({ +function sdkFor(options: { limitToTarget?: boolean }) { + return createSentrySDK({ token: `sntryu_${"a".repeat(64)}`, org: "acme", project: "web", ...options, }); - return sdk.run("issue", "view", "200") as Promise; +} + +function viewIssue(options: { limitToTarget?: boolean }): Promise { + return sdkFor(options).run("issue", "view", "200") as Promise; } describe("createSentrySDK({ org, project })", () => { @@ -45,6 +49,7 @@ describe("createSentrySDK({ org, project })", () => { let originalFetch: typeof fetch; beforeEach(() => { + __resetScopeLookupsForTests(); originalFetch = globalThis.fetch; globalThis.fetch = sentryApi(); }); @@ -64,4 +69,17 @@ describe("createSentrySDK({ org, project })", () => { shortId: "API-1", }); }); + + // `sentry api` sends a path the caller picks; the transport refuses it + // like any other request. + test.each([ + "organizations/other/issues/", + "/api/0/organizations/other/issues/", + "projects/acme/api/", + "issues/200/", + ])("refuses `sentry api %s`", async (path) => { + await expect(sdkFor({}).run("api", path)).rejects.toThrow( + /outside this session's scope \(acme\/web\)/, + ); + }); }); diff --git a/packages/cli/test/lib/target-scope-coverage.test.ts b/packages/cli/test/lib/target-scope-coverage.test.ts new file mode 100644 index 0000000000..044a133f0d --- /dev/null +++ b/packages/cli/test/lib/target-scope-coverage.test.ts @@ -0,0 +1,77 @@ +/** + * A target-scoped invocation (`limitToTarget`) is enforced in the API + * transport, so a request that goes around it is not checked. This test + * fails when a source file sends a request with `fetch()` or `customFetch()` + * itself, unless it applies the scope (`withTargetScope`) or is known not + * to send the CLI's credential to the Sentry API. + */ + +import { readdirSync, readFileSync } from "node:fs"; +import { join, relative } from "node:path"; +import { describe, expect, test } from "vitest"; + +const SRC = join(import.meta.dirname, "../../src"); + +/** Files that send requests without the CLI's Sentry credential. */ +const WITHOUT_SENTRY_CREDENTIAL = [ + // The transport itself, and the helper it and others fetch with. + "lib/sentry-client.ts", + "lib/custom-ca.ts", + // The login flow, before there is a credential. + "lib/oauth.ts", + // Telemetry envelopes, to the DSN. + "lib/envelope/transport.ts", + // CLI upgrades, release notes and Sentry's status page. + "lib/binary.ts", + "lib/delta-upgrade.ts", + "lib/ghcr.ts", + "lib/release-notes.ts", + "lib/api/status-page.ts", + // Services outside the Sentry API: `sentry init`'s docs agent and the + // games leaderboard. + "lib/docs-service.ts", + "lib/games/leaderboard-api.ts", + // Local servers: Sentry Local and the React Native bundler. + "commands/local/daemon.ts", + "commands/local/server.ts", + "commands/react-native/xcode.ts", +]; + +/** A `fetch(` or `customFetch(` call, outside comments. */ +const FETCH_CALL = /(?:^|[^.\w])(?:fetch|customFetch)\(/; +const COMMENT_LINE = /^\s*(?:\*|\/\/|\/\*)/; + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = join(dir, entry.name); + if (entry.isDirectory()) { + return sourceFiles(path); + } + return entry.name.endsWith(".ts") ? [path] : []; + }); +} + +describe("the target scope", () => { + test("covers every request the CLI sends with its credential", () => { + const unguarded = sourceFiles(SRC) + .map((path) => ({ + file: relative(SRC, path), + source: readFileSync(path, "utf8"), + })) + .filter( + ({ source }) => + source + .split("\n") + .some( + (line) => !COMMENT_LINE.test(line) && FETCH_CALL.test(line), + ) && !source.includes("withTargetScope"), + ) + .map(({ file }) => file) + .sort(); + // A new file here sends a request around the API transport. Send it + // through `getSdkConfig()`'s fetch, or wrap its fetch in + // `withTargetScope()`; add it above only if it never sends the CLI's + // credential to the Sentry API. + expect(unguarded).toEqual([...WITHOUT_SENTRY_CREDENTIAL].sort()); + }); +}); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 539acb5113..316f7157eb 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -1,8 +1,10 @@ /** - * The issue check of a target-scoped SDK invocation (`limitToTarget`). + * The transport rules of a target-scoped SDK invocation (`limitToTarget`): + * which requests a scope sends as they are, sends filtered to its project, + * checks by their response, or refuses. */ -import { describe, expect, test } from "vitest"; +import { beforeEach, describe, expect, test } from "vitest"; import { SCOPE_ORG_ENV_VAR, SCOPE_PROJECT_ENV_VAR, @@ -10,96 +12,260 @@ import { } from "../../src/lib/env.js"; import { ResolutionError } from "../../src/lib/errors.js"; import { - assertIssueInScope, - assertOrgInScope, - assertProjectInScope, + __resetScopeLookupsForTests, + withTargetScope, } from "../../src/lib/target-scope.js"; -const WEB_ISSUE = { - id: "100", - project: { id: "1", name: "web", slug: "web", platform: null }, +const BASE = "https://sentry.io/api/0/"; +const WEB = { id: "1", slug: "web" }; +const API = { id: "2", slug: "api" }; + +/** Bodies by path: issue 100 is in `web`, issue 200 in `api`. */ +const BODIES: Record = { + "projects/acme/web/": WEB, + "organizations/acme/issues/100/": { id: "100", project: WEB }, + "organizations/acme/issues/200/": { id: "200", project: API }, + "organizations/acme/shortids/WEB-1/": { projectSlug: "web" }, + "organizations/acme/shortids/API-1/": { projectSlug: "api" }, + "organizations/acme/eventids/a/": { projectSlug: "web" }, + "organizations/acme/eventids/b/": { projectSlug: "api" }, + "organizations/acme/replays/a/": { data: { project_id: "1" } }, + "organizations/acme/replays/b/": { data: { project_id: "2" } }, + "organizations/acme/trace/a/": [ + { project_slug: "edge", children: [{ project_slug: "web" }] }, + ], + "organizations/acme/trace/b/": [{ project_slug: "api", children: [] }], + "organizations/acme/trace/empty/": [], + "organizations/acme/detectors/7/": { projectId: "1" }, + "organizations/acme/detectors/8/": { projectId: "2" }, + "organizations/acme/releases/1.0/": { projects: [API, WEB] }, + "organizations/acme/releases/2.0/": { projects: [API] }, }; -function check( - env: Record, - org: string, - issue: Parameters[1], -): void { - withEnv(env, () => assertIssueInScope(org, issue)); +type Sent = { method: string; path: string }; + +/** + * Send `method path` in `scope` through the scope, to the fake API. + * @returns The requests the API got, the scope's lookups first + */ +async function send( + scope: { org?: string; project?: string }, + method: string, + path: string, +): Promise { + const sent: Sent[] = []; + const fetchScoped = withTargetScope(async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + const relative = url.pathname.replace("/api/0/", "") + url.search; + sent.push({ method: request.method, path: relative }); + const body = BODIES[url.pathname.replace("/api/0/", "")]; + return body === undefined + ? Response.json({ detail: "Not found" }, { status: 404 }) + : Response.json(body); + }); + const env: Record = {}; + if (scope.org) { + env[SCOPE_ORG_ENV_VAR] = scope.org; + } + if (scope.project) { + env[SCOPE_PROJECT_ENV_VAR] = scope.project; + } + await withEnv(env, () => fetchScoped(`${BASE}${path}`, { method })); + // Leave out the scope's own lookup of its project's ID. + return sent.filter( + (request) => request.path === path || request.path !== "projects/acme/web/", + ); +} + +const WEB_SCOPE = { org: "acme", project: "web" }; +const ORG_SCOPE = { org: "acme" }; + +/** The request the API got, after the scope's lookups. */ +async function sentAs( + scope: { org?: string; project?: string }, + method: string, + path: string, +): Promise { + const sent = await send(scope, method, path); + return sent.at(-1)?.path; } -describe("assertIssueInScope", () => { - const webScope = { - [SCOPE_ORG_ENV_VAR]: "acme", - [SCOPE_PROJECT_ENV_VAR]: "web", - }; +describe("a project scope", () => { + beforeEach(() => __resetScopeLookupsForTests()); - test("takes any issue without a scope", () => { - expect(() => check({}, "other", WEB_ISSUE)).not.toThrow(); + test.each([ + ["GET", "", "the API index"], + ["GET", "users/me/", "the token's user"], + ["GET", "organizations/acme/", "the organization"], + ["GET", "organizations/acme/projects/", "the organization's projects"], + ["GET", "projects/acme/web/events/a/", "an event of its project"], + ["PUT", "projects/acme/web/", "a change to its project"], + ["GET", "projects/acme/1/", "its project by ID"], + ["GET", "organizations/acme/issues/?project=1", "issues of its project"], + ["GET", "organizations/acme/issues/?project=web", "the same by slug"], + ["GET", "organizations/acme/issues/100/", "an issue of its project"], + ["GET", "organizations/acme/shortids/WEB-1/", "a short ID in it"], + ["GET", "organizations/acme/eventids/a/", "an event ID in it"], + ["GET", "organizations/acme/replays/a/", "a replay of it"], + ["GET", "organizations/acme/trace/a/", "a trace through it"], + ["GET", "organizations/acme/trace/empty/", "an empty trace"], + ["GET", "organizations/acme/detectors/7/", "an alert of it"], + ["GET", "organizations/acme/releases/1.0/", "a release with it"], + ])("sends %s %s (%s) as it is", async (method, path) => { + expect(await sentAs(WEB_SCOPE, method, path)).toBe(path); }); - test("takes an issue of the scope's project", () => { - expect(() => check(webScope, "acme", WEB_ISSUE)).not.toThrow(); + test.each([ + [ + "GET", + "organizations/acme/issues/", + "organizations/acme/issues/?project=1", + ], + [ + "GET", + "organizations/acme/events/?query=foo", + "organizations/acme/events/?query=foo&project=1", + ], + [ + "GET", + "organizations/acme/replays/?project=-1", + "organizations/acme/replays/?project=1", + ], + [ + "PUT", + "organizations/acme/issues/?id=100", + "organizations/acme/issues/?id=100&project=1", + ], + ])("filters %s %s to its project", async (method, path, filtered) => { + expect(await sentAs(WEB_SCOPE, method, path)).toBe(filtered); }); test.each([ + ["PUT", "organizations/acme/issues/100/", "organizations/acme/issues/100/"], + [ + "GET", + "organizations/acme/issues/100/events/latest/", + "organizations/acme/issues/100/", + ], + [ + "GET", + "organizations/acme/trace-meta/a/", + "organizations/acme/trace/a/?statsPeriod=14d", + ], [ - "another project", - "acme", - { - ...WEB_ISSUE, - project: { id: "2", name: "api", slug: "api", platform: null }, - }, + "GET", + "organizations/acme/trace-logs/?traceId=a&statsPeriod=90d", + "organizations/acme/trace/a/?statsPeriod=90d", ], - ["another organization", "other", WEB_ISSUE], - ["an unknown project", "acme", { id: "100" }], - ])("refuses an issue of %s", (_case, org, issue) => { - expect(() => check(webScope, org, issue)).toThrow(ResolutionError); + [ + "DELETE", + "organizations/acme/detectors/7/", + "organizations/acme/detectors/7/", + ], + ])("looks up what %s %s names first", async (method, path, lookup) => { + const sent = await send(WEB_SCOPE, method, path); + expect(sent.map((request) => request.path)).toEqual([lookup, path]); }); - test("takes any project of an organization scope", () => { - expect(() => - check({ [SCOPE_ORG_ENV_VAR]: "acme" }, "acme", { id: "100" }), - ).not.toThrow(); + test("looks up an issue once", async () => { + await send(WEB_SCOPE, "GET", "organizations/acme/issues/100/"); + const sent = await send(WEB_SCOPE, "PUT", "organizations/acme/issues/100/"); + expect(sent.map((request) => request.path)).toEqual([ + "organizations/acme/issues/100/", + ]); + }); + + test.each([ + ["GET", "organizations/other/", "another organization"], + ["GET", "projects/acme/api/events/b/", "another project's path"], + ["GET", "projects/acme/2/", "another project by ID"], + ["GET", "organizations/acme/issues/?project=2", "another project's filter"], + ["GET", "organizations/acme/issues/?projectSlug=api", "the same by slug"], + ["GET", "organizations/acme/issues/200/", "another project's issue"], + ["PUT", "organizations/acme/issues/200/", "a change to it"], + ["GET", "organizations/acme/issues/200/events/", "its events"], + ["GET", "organizations/acme/shortids/API-1/", "its short ID"], + ["GET", "organizations/acme/eventids/b/", "another project's event ID"], + ["GET", "organizations/acme/replays/b/", "another project's replay"], + ["GET", "organizations/acme/trace/b/", "a trace not through it"], + ["GET", "organizations/acme/trace-meta/b/", "that trace's counts"], + ["GET", "organizations/acme/trace-logs/?traceId=b", "that trace's logs"], + ["GET", "organizations/acme/trace-meta/empty/", "an empty trace's counts"], + ["GET", "organizations/acme/trace-logs/", "logs of no trace"], + ["GET", "organizations/acme/detectors/8/", "another project's alert"], + ["DELETE", "organizations/acme/detectors/8/", "a change to it"], + ["GET", "organizations/acme/releases/2.0/", "a release without it"], + // Paths no rule covers. + ["GET", "organizations/", "the organization list"], + ["GET", "issues/200/", "an issue outside an organization path"], + ["POST", "organizations/acme/dashboards/", "an organization write"], + ["GET", "organizations/acme/brand-new-endpoint/", "an unknown endpoint"], + ["GET", "sentry-app-installations/x/external-requests/", "an app install"], + ])("refuses %s %s (%s)", async (method, path) => { + await expect(send(WEB_SCOPE, method, path)).rejects.toThrow( + /outside this session's scope \(acme\/web\)/, + ); + }); + + test("refuses before it sends", async () => { + const sent: string[] = []; + const fetchScoped = withTargetScope(async (input, init) => { + sent.push(new Request(input, init).url); + return Response.json({}); + }); + await withEnv( + { [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" }, + () => + expect( + fetchScoped(`${BASE}organizations/other/issues/`), + ).rejects.toThrow(ResolutionError), + ); + expect(sent).toEqual([]); + }); + + test("refuses a URL outside the API", async () => { + const fetchScoped = withTargetScope(async () => Response.json({})); + await withEnv( + { [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" }, + () => + expect( + fetchScoped("https://sentry.io/organizations/acme/"), + ).rejects.toThrow(ResolutionError), + ); }); }); -describe("the error of a refused lookup", () => { - const webScope = { - [SCOPE_ORG_ENV_VAR]: "acme", - [SCOPE_PROJECT_ENV_VAR]: "web", - }; - - function refusal(subject: string): ResolutionError { - try { - withEnv(webScope, () => assertProjectInScope("acme", "api", subject)); - } catch (error) { - if (error instanceof ResolutionError) { - return error; - } - throw error; - } - throw new Error(`${subject} was not refused`); - } +describe("an organization scope", () => { + beforeEach(() => __resetScopeLookupsForTests()); test.each([ - ["Issue 100", "issue list acme/web"], - ["Event abc", "issue list acme/web"], - ["Trace abc", "trace list acme/web"], - ["Replay abc", "replay list acme/web"], - ])("for %s suggests %s", (subject, command) => { - expect(refusal(subject).hint).toContain(command); + ["GET", "users/me/"], + ["GET", "organizations/acme/brand-new-endpoint/"], + ["POST", "organizations/acme/dashboards/"], + ["GET", "projects/acme/api/events/b/"], + ["GET", "organizations/acme/issues/200/"], + ["POST", "teams/acme/backend/projects/"], + ])("sends %s %s as it is", async (method, path) => { + expect(await sentAs(ORG_SCOPE, method, path)).toBe(path); }); - test("suggests issue list for a trace in an organization scope", () => { - let hint: string | undefined; - try { - withEnv({ [SCOPE_ORG_ENV_VAR]: "acme" }, () => - assertOrgInScope("other", "Trace abc"), - ); - } catch (error) { - hint = error instanceof ResolutionError ? error.hint : undefined; - } - expect(hint).toContain("issue list acme/"); + test.each([ + ["GET", "organizations/other/issues/"], + ["GET", "projects/other/web/"], + ["GET", "organizations/"], + ["GET", "issues/200/"], + ])("refuses %s %s", async (method, path) => { + await expect(send(ORG_SCOPE, method, path)).rejects.toThrow( + /outside this session's scope \(acme\)/, + ); + }); +}); + +describe("no scope", () => { + test("sends any request as it is", async () => { + expect(await sentAs({}, "GET", "organizations/other/issues/")).toBe( + "organizations/other/issues/", + ); }); }); From cacb093dcc268b3c63ffaa0c85db0fd2ae9b2f58 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:07:48 +0000 Subject: [PATCH 2/9] fix(mcp): Allow read-only organization metadata in scoped sessions A project scope refused organization reads that carry no project's data, so DSN detection (the org list, then `dsn-lookup/`) and similar lookups failed in scoped sessions. These GETs are now allowed in every scope: - `organizations/`, `users/:user/` and `seer/models/`; - under `organizations/:org/`: `dsn-lookup/`, `chunk-upload/`, `members/:member/`, `user-teams/`, `integrations/:id/**`, `config/integrations/`, `available-actions/`, `sentry-apps/`, `sentry-app-installations/`, `repos/:repo/commits/`, `code-mappings/`, `discover/saved/[:query/]` and `group-search-views/`; - `teams/:org/:team/**` and `customers/:org/`. Requests to other organizations are still refused, and so is any endpoint no rule covers. Project keys, org auth tokens, SCIM, stats and sessions, preprod and agent conversations stay refused. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/library-usage.md | 2 +- packages/cli/src/lib/target-scope-rules.ts | 33 +++++++++++++---- packages/cli/src/lib/target-scope.ts | 7 ++-- packages/cli/test/lib/target-scope.test.ts | 35 +++++++++++++++++-- 4 files changed, 65 insertions(+), 12 deletions(-) diff --git a/apps/cli-docs/src/content/docs/library-usage.md b/apps/cli-docs/src/content/docs/library-usage.md index 0447a9fe84..6ee4ca2024 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -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 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. 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` | — | Extra HTTP headers for self-hosted instances behind a reverse proxy (same as [`SENTRY_CUSTOM_HEADERS`](../configuration/#sentry_custom_headers)); ignored for sentry.io | diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index 1e50ac6303..ddb04d0d00 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -70,27 +70,48 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [ // The API index: the token's user and scopes. { pattern: "" }, { pattern: "auth/" }, - { pattern: "users/me/" }, + { pattern: "users/:user/" }, + // The user's organizations, which DSN detection and organization + // resolution read. Requests to any but the scope's are still refused. + { pattern: "organizations/" }, + { pattern: "seer/models/" }, ]; /** - * Organization settings a project scope reads, with no project's issues, - * events or other data in them. + * Read-only organization metadata a project scope may read: settings, + * members, integrations and saved views, with no project's issues, events + * or other data in them. */ -export const ORG_SETTINGS: readonly SimpleRule[] = [ +export const ORG_READS: readonly SimpleRule[] = [ { pattern: "organizations/:org/" }, { pattern: "organizations/:org/projects/" }, { pattern: "organizations/:org/teams/" }, + { pattern: "organizations/:org/user-teams/" }, { pattern: "organizations/:org/members/" }, + { pattern: "organizations/:org/members/:member/" }, { pattern: "organizations/:org/environments/" }, + // The project a DSN belongs to: its ID, slug and name. + { pattern: "organizations/:org/dsn-lookup/" }, + { pattern: "organizations/:org/chunk-upload/" }, { pattern: "organizations/:org/integrations/" }, - { pattern: "organizations/:org/integrations/:integration/" }, - { pattern: "organizations/:org/repos/" }, + { pattern: "organizations/:org/integrations/:integration/**" }, + { pattern: "organizations/:org/config/integrations/" }, + { pattern: "organizations/:org/available-actions/" }, + { pattern: "organizations/:org/sentry-apps/" }, + { pattern: "organizations/:org/sentry-app-installations/" }, { pattern: "organizations/:org/sentry-app-components/" }, + { pattern: "organizations/:org/repos/" }, + { pattern: "organizations/:org/repos/:repo/commits/" }, + { pattern: "organizations/:org/code-mappings/" }, { pattern: "organizations/:org/dashboards/" }, { pattern: "organizations/:org/dashboards/:dashboard/" }, { pattern: "organizations/:org/dashboards/:dashboard/revisions/" }, + { pattern: "organizations/:org/discover/saved/" }, + { pattern: "organizations/:org/discover/saved/:query/" }, + { pattern: "organizations/:org/group-search-views/" }, { pattern: "organizations/:org/workflows/:workflow/" }, + { pattern: "teams/:org/:team/**" }, + { pattern: "customers/:org/" }, ]; /** `value` as an object, or `{}` when it is not one. */ diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 0422ce194a..264a8bc657 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -23,7 +23,8 @@ * against the project of what it finds, before the command sees it. A * request that reads or changes something an ID names first looks it up. * - A few account reads every invocation may need ({@link ACCOUNT_READS}) - * and organization settings with no project data ({@link ORG_SETTINGS}). + * and read-only organization metadata with no project's data in it + * ({@link ORG_READS}). */ import type { ScopeRule } from "./target-scope-rules.js"; @@ -36,7 +37,7 @@ import { ACCOUNT_READS, matchScopeRule, ORG_PATH_PREFIXES, - ORG_SETTINGS, + ORG_READS, PROJECT_SCOPE_RULES, record, } from "./target-scope-rules.js"; @@ -388,7 +389,7 @@ export async function scopeRequest( } throw outsideScope(subject, scope); } - if (matchScopeRule(ORG_SETTINGS, method, segments)) { + if (matchScopeRule(ORG_READS, method, segments)) { return { input, verify: NOTHING_TO_VERIFY }; } const match = matchScopeRule(PROJECT_SCOPE_RULES, method, segments); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 316f7157eb..122d15fc70 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -112,6 +112,26 @@ describe("a project scope", () => { ["GET", "organizations/acme/trace/empty/", "an empty trace"], ["GET", "organizations/acme/detectors/7/", "an alert of it"], ["GET", "organizations/acme/releases/1.0/", "a release with it"], + // Read-only organization metadata. + ["GET", "organizations/", "the organization list"], + ["GET", "users/42/", "a user"], + ["GET", "seer/models/", "Seer's models"], + ["GET", "organizations/acme/dsn-lookup/?dsn=x", "a DSN lookup"], + ["GET", "organizations/acme/chunk-upload/", "upload options"], + ["GET", "organizations/acme/members/5/", "a member"], + ["GET", "organizations/acme/user-teams/", "the user's teams"], + ["GET", "organizations/acme/integrations/3/repos/", "integration repos"], + ["GET", "organizations/acme/config/integrations/", "integration providers"], + ["GET", "organizations/acme/available-actions/", "alert actions"], + ["GET", "organizations/acme/sentry-apps/", "custom integrations"], + ["GET", "organizations/acme/sentry-app-installations/", "app installs"], + ["GET", "organizations/acme/repos/4/commits/", "a repo's commits"], + ["GET", "organizations/acme/code-mappings/", "code mappings"], + ["GET", "organizations/acme/discover/saved/", "saved queries"], + ["GET", "organizations/acme/discover/saved/6/", "a saved query"], + ["GET", "organizations/acme/group-search-views/", "issue views"], + ["GET", "teams/acme/backend/members/", "a team's members"], + ["GET", "customers/acme/", "the subscription"], ])("sends %s %s (%s) as it is", async (method, path) => { expect(await sentAs(WEB_SCOPE, method, path)).toBe(path); }); @@ -196,9 +216,19 @@ describe("a project scope", () => { ["GET", "organizations/acme/detectors/8/", "another project's alert"], ["DELETE", "organizations/acme/detectors/8/", "a change to it"], ["GET", "organizations/acme/releases/2.0/", "a release without it"], + ["GET", "organizations/other/dsn-lookup/", "another org's DSN lookup"], // Paths no rule covers. - ["GET", "organizations/", "the organization list"], ["GET", "issues/200/", "an issue outside an organization path"], + ["GET", "projects/", "every organization's projects"], + ["POST", "teams/acme/backend/projects/", "a team write"], + ["PUT", "customers/acme/", "a subscription write"], + ["GET", "organizations/acme/project-keys/", "every project's keys"], + ["GET", "organizations/acme/org-auth-tokens/", "org auth tokens"], + ["GET", "organizations/acme/scim/v2/Users", "SCIM members"], + ["GET", "organizations/acme/stats_v2/", "event counts"], + ["GET", "organizations/acme/sessions/", "session stats"], + ["GET", "organizations/acme/preprodartifacts/1/size-analysis/", "preprod"], + ["GET", "organizations/acme/agents/conversations/9/", "a conversation"], ["POST", "organizations/acme/dashboards/", "an organization write"], ["GET", "organizations/acme/brand-new-endpoint/", "an unknown endpoint"], ["GET", "sentry-app-installations/x/external-requests/", "an app install"], @@ -241,6 +271,7 @@ describe("an organization scope", () => { test.each([ ["GET", "users/me/"], + ["GET", "organizations/"], ["GET", "organizations/acme/brand-new-endpoint/"], ["POST", "organizations/acme/dashboards/"], ["GET", "projects/acme/api/events/b/"], @@ -253,7 +284,7 @@ describe("an organization scope", () => { test.each([ ["GET", "organizations/other/issues/"], ["GET", "projects/other/web/"], - ["GET", "organizations/"], + ["GET", "projects/"], ["GET", "issues/200/"], ])("refuses %s %s", async (method, path) => { await expect(send(ORG_SCOPE, method, path)).rejects.toThrow( From d7a92c1e7e9cc2ff163f1426cf574bf937e6f0e8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:28:37 +0000 Subject: [PATCH 3/9] fix(mcp): Filter by project ID and check mixed project refs in scope Fixes from review of the transport scope guard: - A project-filtered list with only `projectSlug`, or a slug in `project`, was sent as is. Not every endpoint reads those, so it could run unfiltered. It now always gets the scope project's ID. - A response naming the scope project by ID next to other projects' slugs (a trace across projects) was refused: the IDs were ignored as soon as one slug was present. Each ref is now compared with the scope project in its own kind, looking that up once when needed. A project with both a slug and an ID counts once, by slug. - A scope named by numeric project ID waited on its own lookup. Its ID is now used as given, and the scope project's own path passes without a lookup. - `withTargetScope` sent the scope's lookups without the request's headers, so an authenticated download's lookups had no token. They now carry the request's headers. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/target-scope-rules.ts | 22 +++-- packages/cli/src/lib/target-scope.ts | 103 +++++++++++++-------- packages/cli/test/lib/target-scope.test.ts | 71 +++++++++++++- 3 files changed, 149 insertions(+), 47 deletions(-) diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index ddb04d0d00..ebaa650803 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -127,13 +127,21 @@ function ref(value: unknown): string | undefined { : undefined; } +/** + * One project's ref: its slug when it has one, which the scope can check + * without looking up its own project's ID. + */ +function refOf(slug: unknown, id: unknown): string | undefined { + return ref(slug) ?? ref(id); +} + /** `{ project: { slug, id } }`, as issues and monitors carry it. */ function projectOf(body: unknown): (string | undefined)[] { const project = record(record(body).project); - return [ref(project.slug), ref(project.id)]; + return [refOf(project.slug, project.id)]; } -/** Every `project_slug`/`project_id` of a trace's span tree. */ +/** Each span's `project_slug` or `project_id` in a trace's span tree. */ function traceProjects(spans: unknown): (string | undefined)[] { if (!Array.isArray(spans)) { return [undefined]; @@ -141,8 +149,7 @@ function traceProjects(spans: unknown): (string | undefined)[] { return spans.flatMap((span) => { const fields = record(span); return [ - ref(fields.project_slug), - ref(fields.project_id), + refOf(fields.project_slug, fields.project_id), ...(Array.isArray(fields.children) ? traceProjects(fields.children) : []), ]; }); @@ -331,10 +338,9 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ projects: (body) => { const projects = record(body).projects; return Array.isArray(projects) - ? projects.flatMap((project) => [ - ref(record(project).slug), - ref(record(project).id), - ]) + ? projects.map((project) => + refOf(record(project).slug, record(project).id), + ) : [undefined]; }, path: releasePath, diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 264a8bc657..ae07b42387 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -121,15 +121,21 @@ const NOTHING_TO_VERIFY = async (): Promise => { // The request alone keeps it in scope. }; -/** The scope projects' IDs this process looked up, by scope and host. */ -const projectIds = new Map>(); +/** Project slugs are never entirely numeric, so digits are a project ID. */ +const NUMERIC_ID = /^\d+$/; + +/** A scope project's numeric ID and slug. */ +type ScopeProject = { id: string; slug?: string }; + +/** The scope projects this process looked up, by scope and host. */ +const scopeProjects = new Map>(); /** Paths a `response` rule found in scope, by scope and host. */ const foundInScope = new Set(); /** @internal Test-only: forget the lookups of earlier invocations. */ export function __resetScopeLookupsForTests(): void { - projectIds.clear(); + scopeProjects.clear(); foundInScope.clear(); } @@ -145,16 +151,17 @@ function lookupKey({ scope, url }: RequestContext, path: string): string { return `${scopeLabel(scope)}|${url.origin}/api/0/${path}`; } -/** The numeric ID of the scope's project, looked up once per process. */ -function scopeProjectId(context: RequestContext): Promise { +/** The scope's project, looked up once per process. */ +function lookUpScopeProject(context: RequestContext): Promise { const { scope, url, send } = context; const path = `projects/${encodeURIComponent(scope.org)}/${encodeURIComponent(scope.project)}/`; const key = lookupKey(context, path); - let pending = projectIds.get(key); + let pending = scopeProjects.get(key); if (!pending) { pending = (async () => { const response = await send(`${url.origin}/api/0/${path}`); - const id = response.ok ? record(await readJson(response)).id : undefined; + const project = response.ok ? record(await readJson(response)) : {}; + const { id, slug } = project; if (typeof id !== "string" && typeof id !== "number") { throw new ResolutionError( `Project ${scopeLabel(scope)}`, @@ -163,40 +170,60 @@ function scopeProjectId(context: RequestContext): Promise { ["This session filters its requests by the project's ID."], ); } - return String(id); + return { + id: String(id), + slug: typeof slug === "string" ? slug : undefined, + }; })(); - projectIds.set(key, pending); - pending.catch(() => projectIds.delete(key)); + scopeProjects.set(key, pending); + pending.catch(() => scopeProjects.delete(key)); } return pending; } -/** Project slugs are never entirely numeric, so digits are a project ID. */ -const NUMERIC_ID = /^\d+$/; +/** The numeric ID of the scope's project. */ +async function scopeProjectId(context: RequestContext): Promise { + const { project } = context.scope; + return NUMERIC_ID.test(project) + ? project + : (await lookUpScopeProject(context)).id; +} /** * Whether one of `refs`, project slugs or numeric IDs, is the scope's - * project. The scope project's ID is looked up only when `refs` has no slug. + * project. The scope's project is looked up only when it isn't among them + * as given and some ref is the other kind: an ID for a scope named by + * slug, or a slug for one named by ID. */ async function anyScopeProject( context: RequestContext, refs: readonly (string | undefined)[], ): Promise { + const { project } = context.scope; const known = refs.filter((ref) => ref !== undefined); - const ids = known.filter((ref) => NUMERIC_ID.test(ref)); - if (ids.length < known.length) { - return known.includes(context.scope.project); + // Also how the scope project's own lookup (`projects/:org/:project/`) + // passes, so it never waits on itself. + if (known.includes(project)) { + return true; + } + const byId = NUMERIC_ID.test(project); + const otherKind = known.filter((ref) => NUMERIC_ID.test(ref) !== byId); + if (otherKind.length === 0) { + return false; } - return ids.length > 0 && ids.includes(await scopeProjectId(context)); + const { id, slug } = await lookUpScopeProject(context); + const asOtherKind = byId ? slug : id; + return asOtherKind !== undefined && otherKind.includes(asOtherKind); } /** The `project` filter that asks for every project. */ const ALL_PROJECTS = "-1"; /** - * Filter an organization endpoint to the scope's project: a request with - * no filter, or one for every project (`-1`), gets the scope's; a request - * for another project is refused. + * Filter an organization endpoint to the scope's project: a request for + * another project is refused, and one with no numeric `project` filter + * (none, `-1` for every project, or only slugs) gets the scope project's + * ID. Not every endpoint reads `projectSlug`, or slugs in `project`. */ async function filterToProject( context: RequestContext, @@ -204,29 +231,23 @@ async function filterToProject( subject: string, ): Promise { const { url, scope } = context; - const requested = [ - ...url.searchParams.getAll("project"), - ...url.searchParams.getAll("projectSlug"), - ].filter((project) => project !== ALL_PROJECTS); - if (requested.length > 0) { - for (const project of requested) { - if (!(await anyScopeProject(context, [project]))) { - throw outsideScope(subject, scope); - } - } - if (!url.searchParams.getAll("project").includes(ALL_PROJECTS)) { - return input; + const projects = url.searchParams.getAll("project"); + const kept = projects.filter((project) => project !== ALL_PROJECTS); + for (const project of [...kept, ...url.searchParams.getAll("projectSlug")]) { + if (!(await anyScopeProject(context, [project]))) { + throw outsideScope(subject, scope); } } + const hasId = kept.some((project) => NUMERIC_ID.test(project)); + if (hasId && kept.length === projects.length) { + return input; + } const filtered = new URL(url); - const kept = filtered.searchParams - .getAll("project") - .filter((project) => project !== ALL_PROJECTS); filtered.searchParams.delete("project"); for (const project of kept) { filtered.searchParams.append("project", project); } - if (requested.length === 0) { + if (!hasId) { filtered.searchParams.append("project", await scopeProjectId(context)); } return input instanceof Request @@ -406,7 +427,9 @@ export async function scopeRequest( /** * Wrap a fetch that sends requests outside the authenticated transport - * (a share link's) so the invocation's scope applies to it too. + * (a share link's) so the invocation's scope applies to it too. The + * scope's lookups go out with the request's headers, so an authenticated + * download's lookups carry its token. */ export function withTargetScope( fetchFn: ( @@ -418,7 +441,11 @@ export function withTargetScope( input: Request | string | URL, init?: RequestInit, ): Promise => { - const request = await scopeRequest(input, init, (lookup) => scoped(lookup)); + const headers = + init?.headers ?? (input instanceof Request ? input.headers : undefined); + const request = await scopeRequest(input, init, (lookup) => + scoped(lookup, headers ? { headers } : undefined), + ); if (request.response) { return request.response; } diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 122d15fc70..6736effc51 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -23,6 +23,7 @@ const API = { id: "2", slug: "api" }; /** Bodies by path: issue 100 is in `web`, issue 200 in `api`. */ const BODIES: Record = { "projects/acme/web/": WEB, + "projects/acme/1/": WEB, "organizations/acme/issues/100/": { id: "100", project: WEB }, "organizations/acme/issues/200/": { id: "200", project: API }, "organizations/acme/shortids/WEB-1/": { projectSlug: "web" }, @@ -36,6 +37,9 @@ const BODIES: Record = { ], "organizations/acme/trace/b/": [{ project_slug: "api", children: [] }], "organizations/acme/trace/empty/": [], + "organizations/acme/trace/mixed/": [ + { project_slug: "api", children: [{ project_id: 1 }] }, + ], "organizations/acme/detectors/7/": { projectId: "1" }, "organizations/acme/detectors/8/": { projectId: "2" }, "organizations/acme/releases/1.0/": { projects: [API, WEB] }, @@ -103,13 +107,13 @@ describe("a project scope", () => { ["PUT", "projects/acme/web/", "a change to its project"], ["GET", "projects/acme/1/", "its project by ID"], ["GET", "organizations/acme/issues/?project=1", "issues of its project"], - ["GET", "organizations/acme/issues/?project=web", "the same by slug"], ["GET", "organizations/acme/issues/100/", "an issue of its project"], ["GET", "organizations/acme/shortids/WEB-1/", "a short ID in it"], ["GET", "organizations/acme/eventids/a/", "an event ID in it"], ["GET", "organizations/acme/replays/a/", "a replay of it"], ["GET", "organizations/acme/trace/a/", "a trace through it"], ["GET", "organizations/acme/trace/empty/", "an empty trace"], + ["GET", "organizations/acme/trace/mixed/", "a trace naming it by ID"], ["GET", "organizations/acme/detectors/7/", "an alert of it"], ["GET", "organizations/acme/releases/1.0/", "a release with it"], // Read-only organization metadata. @@ -157,6 +161,17 @@ describe("a project scope", () => { "organizations/acme/issues/?id=100", "organizations/acme/issues/?id=100&project=1", ], + // Not every endpoint reads a slug, so the filter is by ID. + [ + "GET", + "organizations/acme/issues/?project=web", + "organizations/acme/issues/?project=web&project=1", + ], + [ + "GET", + "organizations/acme/issues/?projectSlug=web", + "organizations/acme/issues/?projectSlug=web&project=1", + ], ])("filters %s %s to its project", async (method, path, filtered) => { expect(await sentAs(WEB_SCOPE, method, path)).toBe(filtered); }); @@ -238,6 +253,60 @@ describe("a project scope", () => { ); }); + test.each([ + [ + "GET", + "organizations/acme/issues/", + "organizations/acme/issues/?project=1", + ], + ["GET", "projects/acme/1/", "projects/acme/1/"], + ])("by ID sends %s %s as %s", async (method, path, sent) => { + expect(await sentAs({ org: "acme", project: "1" }, method, path)).toBe( + sent, + ); + }); + + test("by ID checks a short ID's slug", async () => { + const sent = await send( + { org: "acme", project: "1" }, + "GET", + "organizations/acme/shortids/WEB-1/", + ); + expect(sent.map((request) => request.path)).toEqual([ + "organizations/acme/shortids/WEB-1/", + "projects/acme/1/", + ]); + }); + + test("by ID refuses another project's short ID", async () => { + await expect( + send( + { org: "acme", project: "1" }, + "GET", + "organizations/acme/shortids/API-1/", + ), + ).rejects.toThrow(/outside this session's scope \(acme\/1\)/); + }); + + test("sends its lookups with the request's headers", async () => { + const lookups: (string | null)[] = []; + const fetchScoped = withTargetScope(async (input, init) => { + const request = new Request(input, init); + if (request.url.endsWith("/projects/acme/web/")) { + lookups.push(request.headers.get("Authorization")); + } + return Response.json(WEB); + }); + await withEnv( + { [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" }, + () => + fetchScoped(`${BASE}organizations/acme/issues/`, { + headers: { Authorization: "Bearer t" }, + }), + ); + expect(lookups).toEqual(["Bearer t"]); + }); + test("refuses before it sends", async () => { const sent: string[] = []; const fetchScoped = withTargetScope(async (input, init) => { From 849e1960988f07feb7c810b2d895b904574b5641 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:37:14 +0000 Subject: [PATCH 4/9] fix(mcp): Send only project IDs in a scoped project filter A scoped request with a slug in `project` kept the slug next to the scope project's ID. Sentry reads slugs there now, but older versions integer-cast every `project` value and refuse the request. Once checked, slugs and `-1` are dropped from `project`, so the filter carries only numeric IDs, the scope project's when there are none. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/target-scope.ts | 25 +++++++++++----------- packages/cli/test/lib/target-scope.test.ts | 5 +++-- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index ae07b42387..8927a5ded7 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -221,9 +221,10 @@ const ALL_PROJECTS = "-1"; /** * Filter an organization endpoint to the scope's project: a request for - * another project is refused, and one with no numeric `project` filter - * (none, `-1` for every project, or only slugs) gets the scope project's - * ID. Not every endpoint reads `projectSlug`, or slugs in `project`. + * another project is refused, and the rest are sent with `project` set to + * numeric IDs, the scope project's when they have none. A slug or `-1` in + * `project` is dropped once checked, since older Sentry versions read only + * IDs there; not every endpoint reads `projectSlug` either. */ async function filterToProject( context: RequestContext, @@ -232,23 +233,23 @@ async function filterToProject( ): Promise { const { url, scope } = context; const projects = url.searchParams.getAll("project"); - const kept = projects.filter((project) => project !== ALL_PROJECTS); - for (const project of [...kept, ...url.searchParams.getAll("projectSlug")]) { + const requested = projects.filter((project) => project !== ALL_PROJECTS); + for (const project of [ + ...requested, + ...url.searchParams.getAll("projectSlug"), + ]) { if (!(await anyScopeProject(context, [project]))) { throw outsideScope(subject, scope); } } - const hasId = kept.some((project) => NUMERIC_ID.test(project)); - if (hasId && kept.length === projects.length) { + const ids = requested.filter((project) => NUMERIC_ID.test(project)); + if (ids.length > 0 && ids.length === projects.length) { return input; } const filtered = new URL(url); filtered.searchParams.delete("project"); - for (const project of kept) { - filtered.searchParams.append("project", project); - } - if (!hasId) { - filtered.searchParams.append("project", await scopeProjectId(context)); + for (const id of ids.length > 0 ? ids : [await scopeProjectId(context)]) { + filtered.searchParams.append("project", id); } return input instanceof Request ? new Request(filtered, input) diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 6736effc51..5c5fabd7df 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -161,11 +161,12 @@ describe("a project scope", () => { "organizations/acme/issues/?id=100", "organizations/acme/issues/?id=100&project=1", ], - // Not every endpoint reads a slug, so the filter is by ID. + // Older Sentry versions read only IDs in `project`, and not every + // endpoint reads `projectSlug`, so the filter is by ID. [ "GET", "organizations/acme/issues/?project=web", - "organizations/acme/issues/?project=web&project=1", + "organizations/acme/issues/?project=1", ], [ "GET", From a574eab1bc121645c2e4c9afd4c0d583e3bb0042 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:47:31 +0000 Subject: [PATCH 5/9] fix(mcp): Adapt the transport scope to main On `main`, the CLI compiles with `noPropertyAccessFromIndexSignature` and `exactOptionalPropertyTypes`, so the scope rules read response fields by key and a scope project's slug may be `undefined`. Objectstore uploads (`snapshots upload`) also landed on `main`. They send the pre-signed token Sentry issues for them, not the CLI's credential, so the coverage test lists `lib/objectstore.ts` with the other senders the scope does not need to guard. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/target-scope-rules.ts | 26 ++++++++++--------- packages/cli/src/lib/target-scope.ts | 4 +-- .../test/lib/target-scope-coverage.test.ts | 2 ++ 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index ebaa650803..e3cc1b0291 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -137,8 +137,8 @@ function refOf(slug: unknown, id: unknown): string | undefined { /** `{ project: { slug, id } }`, as issues and monitors carry it. */ function projectOf(body: unknown): (string | undefined)[] { - const project = record(record(body).project); - return [refOf(project.slug, project.id)]; + const project = record(record(body)["project"]); + return [refOf(project["slug"], project["id"])]; } /** Each span's `project_slug` or `project_id` in a trace's span tree. */ @@ -149,8 +149,10 @@ function traceProjects(spans: unknown): (string | undefined)[] { return spans.flatMap((span) => { const fields = record(span); return [ - refOf(fields.project_slug, fields.project_id), - ...(Array.isArray(fields.children) ? traceProjects(fields.children) : []), + refOf(fields["project_slug"], fields["project_id"]), + ...(Array.isArray(fields["children"]) + ? traceProjects(fields["children"]) + : []), ]; }); } @@ -158,7 +160,7 @@ function traceProjects(spans: unknown): (string | undefined)[] { /** `organizations////`, from a rule's params. */ function orgPath(kind: string, param: string) { return (params: Record): string => - `organizations/${encodeURIComponent(params.org ?? "")}/${kind}/${encodeURIComponent(params[param] ?? "")}/`; + `organizations/${encodeURIComponent(params["org"] ?? "")}/${kind}/${encodeURIComponent(params[param] ?? "")}/`; } const issuePath = orgPath("issues", "issue"); @@ -239,8 +241,8 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ enforce: { kind: "response", projects: (body) => [ - ref(record(body).projectSlug), - ...projectOf(record(body).group), + ref(record(body)["projectSlug"]), + ...projectOf(record(body)["group"]), ], }, }, @@ -254,7 +256,7 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ subject: ({ event }) => `Event ${event}`, enforce: { kind: "response", - projects: (body) => [ref(record(body).projectSlug)], + projects: (body) => [ref(record(body)["projectSlug"])], }, }, { @@ -294,7 +296,7 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ subject: ({ replay }) => `Replay ${replay}`, enforce: { kind: "response", - projects: (body) => [ref(record(record(body).data).project_id)], + projects: (body) => [ref(record(record(body)["data"])["project_id"])], }, }, { @@ -316,7 +318,7 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ subject: ({ detector }) => `Alert ${detector}`, enforce: { kind: "response", - projects: (body) => [ref(record(body).projectId)], + projects: (body) => [ref(record(body)["projectId"])], path: detectorPath, }, }, @@ -336,10 +338,10 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ enforce: { kind: "response", projects: (body) => { - const projects = record(body).projects; + const projects = record(body)["projects"]; return Array.isArray(projects) ? projects.map((project) => - refOf(record(project).slug, record(project).id), + refOf(record(project)["slug"], record(project)["id"]), ) : [undefined]; }, diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 8927a5ded7..4f48e741bc 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -125,7 +125,7 @@ const NOTHING_TO_VERIFY = async (): Promise => { const NUMERIC_ID = /^\d+$/; /** A scope project's numeric ID and slug. */ -type ScopeProject = { id: string; slug?: string }; +type ScopeProject = { id: string; slug?: string | undefined }; /** The scope projects this process looked up, by scope and host. */ const scopeProjects = new Map>(); @@ -314,7 +314,7 @@ async function applyRule( rule.subject?.(params) ?? `${context.method} ${context.url.pathname}`; switch (rule.enforce.kind) { case "project-path": - if (!(await anyScopeProject(context, [params.project]))) { + if (!(await anyScopeProject(context, [params["project"]]))) { throw outsideScope(subject, scope); } return { input, verify: NOTHING_TO_VERIFY }; diff --git a/packages/cli/test/lib/target-scope-coverage.test.ts b/packages/cli/test/lib/target-scope-coverage.test.ts index 044a133f0d..618623bb50 100644 --- a/packages/cli/test/lib/target-scope-coverage.test.ts +++ b/packages/cli/test/lib/target-scope-coverage.test.ts @@ -31,6 +31,8 @@ const WITHOUT_SENTRY_CREDENTIAL = [ // games leaderboard. "lib/docs-service.ts", "lib/games/leaderboard-api.ts", + // Objectstore uploads, with the pre-signed token Sentry issues for them. + "lib/objectstore.ts", // Local servers: Sentry Local and the React Native bundler. "commands/local/daemon.ts", "commands/local/server.ts", From 7a9798c6c2e956e129326c93c4ce9365ae868c69 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:06:53 +0000 Subject: [PATCH 6/9] test(mcp): Check the list command a transport refusal suggests Refs #2237 --- packages/cli/test/lib/target-scope.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 5c5fabd7df..96d6731b26 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -308,6 +308,19 @@ describe("a project scope", () => { expect(lookups).toEqual(["Bearer t"]); }); + test.each([ + ["organizations/acme/issues/200/", "issue list acme/web"], + ["organizations/acme/eventids/b/", "issue list acme/web"], + ["organizations/acme/trace/b/", "trace list acme/web"], + ["organizations/acme/replays/b/", "replay list acme/web"], + ])("suggests the list command for GET %s", async (path, command) => { + const refused = await send(WEB_SCOPE, "GET", path).catch( + (error: unknown) => error, + ); + expect(refused).toBeInstanceOf(ResolutionError); + expect((refused as ResolutionError).hint).toContain(command); + }); + test("refuses before it sends", async () => { const sent: string[] = []; const fetchScoped = withTargetScope(async (input, init) => { @@ -361,6 +374,15 @@ describe("an organization scope", () => { /outside this session's scope \(acme\)/, ); }); + test("suggests issue list for another organization's trace", async () => { + const refused = await send( + ORG_SCOPE, + "GET", + "organizations/other/trace/b/", + ).catch((error: unknown) => error); + expect(refused).toBeInstanceOf(ResolutionError); + expect((refused as ResolutionError).hint).toContain("issue list acme/"); + }); }); describe("no scope", () => { From 4511dea0d3976a16a566c992c17a6902d55d5626 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:27:23 +0000 Subject: [PATCH 7/9] test(cli): List the wizard's credential-free requests in the scope coverage test `sentry wizard`, merged from main, fetches Sentry's public release registry and writes example code with fetch() calls into the user's project. Neither sends the CLI's credential to the Sentry API. --- packages/cli/test/lib/target-scope-coverage.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/cli/test/lib/target-scope-coverage.test.ts b/packages/cli/test/lib/target-scope-coverage.test.ts index 618623bb50..f9e06e307a 100644 --- a/packages/cli/test/lib/target-scope-coverage.test.ts +++ b/packages/cli/test/lib/target-scope-coverage.test.ts @@ -37,6 +37,14 @@ const WITHOUT_SENTRY_CREDENTIAL = [ "commands/local/daemon.ts", "commands/local/server.ts", "commands/react-native/xcode.ts", + // `sentry wizard`: Sentry's public release registry, and example code + // it writes into the user's project. + "lib/wizard/utils/release-registry.ts", + "lib/wizard/cloudflare/templates.ts", + "lib/wizard/nextjs/templates.ts", + "lib/wizard/react-router/sdk-example.ts", + "lib/wizard/remix/sdk-example.ts", + "lib/wizard/sveltekit/templates.ts", ]; /** A `fetch(` or `customFetch(` call, outside comments. */ From 6d0755bae8f6b759692e1c3768468ac7ccfff519 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:13:44 +0000 Subject: [PATCH 8/9] fix(cli): look up a share link's scope project with the token getSharedIssue sends the share request without the bearer token, and the target scope's project lookup went out the same way. When the session names its project by ID and the share payload by slug (or the reverse), that lookup got 401 and an in-scope share was refused. withTargetScope now takes an optional lookup sender, and getSharedIssue passes the authenticated transport, which still refuses an untrusted host. --- packages/cli/src/lib/api/issues.ts | 7 +++- packages/cli/src/lib/target-scope.ts | 10 +++-- .../cli/test/lib/api/shared-issues.test.ts | 41 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/lib/api/issues.ts b/packages/cli/src/lib/api/issues.ts index c7e77a969c..7cd7c71027 100644 --- a/packages/cli/src/lib/api/issues.ts +++ b/packages/cli/src/lib/api/issues.ts @@ -31,6 +31,7 @@ import { } from "../custom-ca.js"; import { applyCustomHeaders } from "../custom-headers.js"; import { ApiError, ValidationError } from "../errors.js"; +import { getSdkConfig } from "../sentry-client.js"; import { withTargetScope } from "../target-scope.js"; import { @@ -750,11 +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; - // It still applies the invocation's target scope (`limitToTarget`). + // 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>; try { diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 4f48e741bc..d685dd0b1b 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -430,13 +430,15 @@ export async function scopeRequest( * Wrap a fetch that sends requests outside the authenticated transport * (a share link's) so the invocation's scope applies to it too. The * scope's lookups go out with the request's headers, so an authenticated - * download's lookups carry its token. + * download's lookups carry its token. A fetch without the token passes + * `lookup`, which sends them instead. */ export function withTargetScope( fetchFn: ( input: Request | string | URL, init?: RequestInit, ) => Promise, + lookup?: Send, ): (input: Request | string | URL, init?: RequestInit) => Promise { const scoped = async ( input: Request | string | URL, @@ -444,8 +446,10 @@ export function withTargetScope( ): Promise => { const headers = init?.headers ?? (input instanceof Request ? input.headers : undefined); - const request = await scopeRequest(input, init, (lookup) => - scoped(lookup, headers ? { headers } : undefined), + const request = await scopeRequest( + input, + init, + lookup ?? ((path) => scoped(path, headers ? { headers } : undefined)), ); if (request.response) { return request.response; diff --git a/packages/cli/test/lib/api/shared-issues.test.ts b/packages/cli/test/lib/api/shared-issues.test.ts index 745db1433d..a7db8434a5 100644 --- a/packages/cli/test/lib/api/shared-issues.test.ts +++ b/packages/cli/test/lib/api/shared-issues.test.ts @@ -5,7 +5,13 @@ import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { getSharedIssue } from "../../../src/lib/api/issues.js"; import { setAuthToken } from "../../../src/lib/db/auth.js"; +import { + SCOPE_ORG_ENV_VAR, + SCOPE_PROJECT_ENV_VAR, + withEnv, +} from "../../../src/lib/env.js"; import { ApiError } from "../../../src/lib/errors.js"; +import { __resetScopeLookupsForTests } from "../../../src/lib/target-scope.js"; import { mockFetch, useEnvSandbox, useTestConfigDir } from "../../helpers.js"; describe("getSharedIssue", () => { @@ -54,6 +60,41 @@ describe("getSharedIssue", () => { expect(request?.headers.has("Authorization")).toBe(false); }); + test("looks up a scope's project with the token when the share names it the other way", async () => { + setAuthToken("test-token"); + __resetScopeLookupsForTests(); + const requests: Request[] = []; + globalThis.fetch = mockFetch(async (input, init) => { + const request = new Request(input, init); + requests.push(request); + if (new URL(request.url).pathname === "/api/0/projects/example-org/42/") { + return request.headers.has("Authorization") + ? Response.json({ id: "42", slug: "example-project" }) + : Response.json({ detail: "Unauthorized" }, { status: 401 }); + } + return Response.json({ + id: "12345", + project: { slug: "example-project" }, + }); + }); + + // The session names its project by ID; the share payload by slug. + const result = await withEnv( + { + ...process.env, + [SCOPE_ORG_ENV_VAR]: "example-org", + [SCOPE_PROJECT_ENV_VAR]: "42", + }, + () => getSharedIssue("https://sentry.io", "example-org", "share-id"), + ); + + expect(result.id).toBe("12345"); + const share = requests.find((request) => + request.url.includes("/shared/issues/"), + ); + expect(share?.headers.has("Authorization")).toBe(false); + }); + test.each([ ["null body", null], ["missing id", {}], From bf67348be4573ca6d2813f0e1c2e2c8d7ea3fa5f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:19:23 +0000 Subject: [PATCH 9/9] fix(cli): widen an empty trace lookup to 90 days trace-meta and trace-logs look the trace up first, over the request's period (14d by default). A trace with in-scope spans only past that window came back empty and was refused, while trace view, which retries 90d, showed it. A relative period now retries the lookup at 90d before refusing. --- packages/cli/src/lib/target-scope-rules.ts | 38 +++++++++++++++------- packages/cli/src/lib/target-scope.ts | 33 ++++++++++--------- packages/cli/test/lib/target-scope.test.ts | 21 +++++++++++- 3 files changed, 64 insertions(+), 28 deletions(-) diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index e3cc1b0291..92b9e8fe02 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -37,12 +37,15 @@ type ScopeEnforcement = */ type LookUpFirst = { kind: "look-up-first"; - lookups: ( - params: Record, - url: URL, - ) => { path: string; query?: string }[]; + lookups: (params: Record, url: URL) => ScopeLookup[]; }; +/** + * A lookup to send, with its query; `widerQuery` is tried when the first + * names no project (an empty trace). + */ +export type ScopeLookup = { path: string; query?: string; widerQuery?: string }; + export type ScopeRule = { pattern: string; /** Methods the rule covers; reads (`GET`, `HEAD`) when omitted. */ @@ -169,11 +172,15 @@ const monitorPath = orgPath("monitors", "monitor"); const detectorPath = orgPath("detectors", "detector"); const releasePath = orgPath("releases", "version"); -/** A trace lookup for `trace-meta` and `trace-logs`, over the same period. */ -function traceLookup( - params: Record, - url: URL, -): { path: string; query: string } { +/** The widest relative window a trace lookup tries, as `trace view` does. */ +const WIDEST_TRACE_PERIOD = "90d"; + +/** + * A trace lookup for `trace-meta` and `trace-logs`, over the same period. + * A relative period is widened to {@link WIDEST_TRACE_PERIOD} when the trace + * is empty in it, so a trace whose spans are older still proves in scope. + */ +function traceLookup(params: Record, url: URL): ScopeLookup { const query = new URLSearchParams(); for (const name of ["statsPeriod", "start", "end"]) { const value = url.searchParams.get(name); @@ -181,10 +188,17 @@ function traceLookup( query.set(name, value); } } - if (!query.has("statsPeriod") && !query.has("start")) { - query.set("statsPeriod", "14d"); + if (query.has("start")) { + return { path: tracePath(params), query: query.toString() }; } - return { path: tracePath(params), query: query.toString() }; + const period = query.get("statsPeriod") ?? "14d"; + return { + path: tracePath(params), + query: `statsPeriod=${period}`, + ...(period === WIDEST_TRACE_PERIOD + ? {} + : { widerQuery: `statsPeriod=${WIDEST_TRACE_PERIOD}` }), + }; } const PROJECT_FILTERED = [ diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index d685dd0b1b..97a5d0df4d 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -27,7 +27,7 @@ * ({@link ORG_READS}). */ -import type { ScopeRule } from "./target-scope-rules.js"; +import type { ScopeLookup, ScopeRule } from "./target-scope-rules.js"; import { sentry } from "./app-identity.js"; import { getEnv, SCOPE_ORG_ENV_VAR, SCOPE_PROJECT_ENV_VAR } from "./env.js"; import { ResolutionError } from "./errors.js"; @@ -276,25 +276,28 @@ async function readJson(response: Response): Promise { */ async function lookUpFirst( context: RequestContext, - { path, query }: { path: string; query?: string }, + { path, query, widerQuery }: ScopeLookup, ): Promise { - if (foundInScope.has(lookupKey(context, path))) { + const key = lookupKey(context, path); + if (foundInScope.has(key)) { return; } - const response = await context.send( - `${context.url.origin}/api/0/${path}${query ? `?${query}` : ""}`, - ); - if (!response.ok) { - return response; - } - if (!foundInScope.has(lookupKey(context, path))) { - // The lookup named no project (an empty trace): nothing to read. - throw outsideScope( - `${context.method} ${context.url.pathname}`, - context.scope, + for (const attempt of widerQuery ? [query, widerQuery] : [query]) { + const response = await context.send( + `${context.url.origin}/api/0/${path}${attempt ? `?${attempt}` : ""}`, ); + if (!response.ok) { + return response; + } + if (foundInScope.has(key)) { + return; + } } - return; + // The lookup named no project (an empty trace): nothing to read. + throw outsideScope( + `${context.method} ${context.url.pathname}`, + context.scope, + ); } /** Remember that `path` is in scope, so later requests skip the lookup. */ diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 96d6731b26..5283d94e4b 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -37,6 +37,11 @@ const BODIES: Record = { ], "organizations/acme/trace/b/": [{ project_slug: "api", children: [] }], "organizations/acme/trace/empty/": [], + // Trace `old` has spans in `web` only past the default 14 days. + "organizations/acme/trace/old/": [], + "organizations/acme/trace/old/?statsPeriod=90d": [ + { project_slug: "web", children: [] }, + ], "organizations/acme/trace/mixed/": [ { project_slug: "api", children: [{ project_id: 1 }] }, ], @@ -63,7 +68,8 @@ async function send( const url = new URL(request.url); const relative = url.pathname.replace("/api/0/", "") + url.search; sent.push({ method: request.method, path: relative }); - const body = BODIES[url.pathname.replace("/api/0/", "")]; + const body = + BODIES[relative] ?? BODIES[url.pathname.replace("/api/0/", "")]; return body === undefined ? Response.json({ detail: "Not found" }, { status: 404 }) : Response.json(body); @@ -204,6 +210,19 @@ describe("a project scope", () => { expect(sent.map((request) => request.path)).toEqual([lookup, path]); }); + test("widens a trace lookup that is empty in the request's period", async () => { + const sent = await send( + WEB_SCOPE, + "GET", + "organizations/acme/trace-meta/old/", + ); + expect(sent.map((request) => request.path)).toEqual([ + "organizations/acme/trace/old/?statsPeriod=14d", + "organizations/acme/trace/old/?statsPeriod=90d", + "organizations/acme/trace-meta/old/", + ]); + }); + test("looks up an issue once", async () => { await send(WEB_SCOPE, "GET", "organizations/acme/issues/100/"); const sent = await send(WEB_SCOPE, "PUT", "organizations/acme/issues/100/");