diff --git a/apps/cli-docs/src/content/docs/library-usage.md b/apps/cli-docs/src/content/docs/library-usage.md index feb5e5604c..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 an issue, event, trace or replay outside `org` and `project`, even one an ID alone names (`12345`, `@latest`, an event ID). Set `false` to use `org` and `project` only as defaults | +| `limitToTarget` | `boolean` | `true` | Refuse any request outside `org` and `project`, including what an ID alone names (`12345`, `@latest`, an event ID). With a `project`, requests the CLI has no rule for, such as organization-wide writes, are refused too; read-only organization metadata, such as DSN lookups, stays allowed. Set `false` to use `org` and `project` only as defaults | | `text` | `boolean` | `false` | Return human-readable text instead of parsed JSON (`run()` only) | | `cwd` | `string` | `process.cwd()` | Working directory for DSN auto-detection | | `headers` | `Record` | — | 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 d3a91208d8..d820ff86a5 100644 --- a/packages/cli/src/commands/issue/utils.ts +++ b/packages/cli/src/commands/issue/utils.ts @@ -58,7 +58,7 @@ import { } from "../../lib/resolve-target.js"; import { applySentryUrlContext } from "../../lib/sentry-url-parser.js"; import { buildIssueUrl } from "../../lib/sentry-web-urls.js"; -import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js"; +import { getTargetScope } from "../../lib/target-scope.js"; import { setOrgProjectContext } from "../../lib/telemetry.js"; import { isAllDigits, shellQuote } from "../../lib/utils.js"; import type { SentryIssue } from "../../types/index.js"; @@ -600,15 +600,14 @@ async function resolveSelector( * @param org - Organization slug * @param project - Project slug to look in, selected by its numeric ID * (a `project:` 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 +634,6 @@ export async function findSelectorIssue( ], ); } - assertIssueInScope(org, issue); return issue; } @@ -665,22 +663,18 @@ async function resolveIssueSearch( throw new ContextError("Organization", commandHint); } const { org } = resolved; - const scopeProject = getTargetScope()?.project; const { data: issues, nextCursor } = await listIssuesPaginated(org, "", { query, perPage: SEARCH_CANDIDATES, collapse: ISSUE_DETAIL_COLLAPSE, - projects: scopeProject - ? await resolveProjectIdsInOrg(org, [scopeProject]) - : undefined, }); const [issue] = issues; if (issue && issues.length === 1) { - assertIssueInScope(org, issue); return { org, issue }; } - // In a project scope, the search ran in that project alone. + // In a project scope, the transport filters the search to that project. + const scopeProject = getTargetScope()?.project; const searched = scopeProject ? `${org}/${scopeProject}` : org; const listCommand = sentry`issue list ${org}/${scopeProject ?? ""} --query ${shellQuote(query)}`; if (!issue) { 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..7cd7c71027 100644 --- a/packages/cli/src/lib/api/issues.ts +++ b/packages/cli/src/lib/api/issues.ts @@ -31,7 +31,8 @@ import { } from "../custom-ca.js"; import { applyCustomHeaders } from "../custom-headers.js"; import { ApiError, ValidationError } from "../errors.js"; -import { assertIssueInScope, assertOrgInScope } from "../target-scope.js"; +import { getSdkConfig } from "../sentry-client.js"; +import { withTargetScope } from "../target-scope.js"; import { getOrgSdkConfig, @@ -326,24 +327,19 @@ export async function listIssuesAllPages( * @param orgSlug - Organization slug (used for region routing) * @param issueId - Numeric issue ID * @param options - Optional collapse fields to skip expensive backend queries - * @throws {ResolutionError} When the issue is outside the invocation's - * target scope (`limitToTarget`) */ export async function getIssueInOrg( orgSlug: string, issueId: string, options?: { collapse?: IssueCollapseField[] }, ): Promise { - 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 +400,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 +407,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 +446,6 @@ export async function getIssueByShortId( "Issue not found", ); } - assertIssueInScope(orgSlug, data.group); return data.group; } @@ -759,13 +751,13 @@ export async function getSharedIssue( // The share URL's host may not be the logged-in one, so this goes out // without the authenticated transport and its bearer token. let response: Response | undefined; - const fetchUnauthenticated = async ( - input: string | URL | Request, - init?: RequestInit, - ) => { + // It still applies the invocation's target scope (`limitToTarget`), whose + // own project lookups need the token, so they go through the + // authenticated transport, which refuses an untrusted host. + const fetchUnauthenticated = withTargetScope(async (input, init) => { response = await customFetch(input, init); return response; - }; + }, getSdkConfig(normalizedBase).fetch); let result: Awaited>; 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..92b9e8fe02 --- /dev/null +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -0,0 +1,418 @@ +/** + * 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) => 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. */ + 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/: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/" }, +]; + +/** + * 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_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/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. */ +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; +} + +/** + * 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 [refOf(project["slug"], project["id"])]; +} + +/** 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]; + } + return spans.flatMap((span) => { + const fields = record(span); + return [ + refOf(fields["project_slug"], 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"); + +/** 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); + if (value) { + query.set(name, value); + } + } + if (query.has("start")) { + 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 = [ + "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.map((project) => + refOf(record(project)["slug"], 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..97a5d0df4d 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -2,17 +2,47 @@ * 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 read-only organization metadata with no project's data in it + * ({@link ORG_READS}). */ -import type { SentryIssue } from "../types/index.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"; +import { extractInputUrl } from "./fetch-input.js"; +import { logger } from "./logger.js"; +import { + ACCOUNT_READS, + matchScopeRule, + ORG_PATH_PREFIXES, + ORG_READS, + 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 +76,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 +90,376 @@ 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. +}; + +/** 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 | undefined }; + +/** 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 { + scopeProjects.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 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 = scopeProjects.get(key); + if (!pending) { + pending = (async () => { + const response = await send(`${url.origin}/api/0/${path}`); + 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)}`, + `could not be looked up (HTTP ${response.status})`, + sentry`project view ${scopeLabel(scope)}`, + ["This session filters its requests by the project's ID."], + ); + } + return { + id: String(id), + slug: typeof slug === "string" ? slug : undefined, + }; + })(); + scopeProjects.set(key, pending); + pending.catch(() => scopeProjects.delete(key)); + } + return pending; +} + +/** 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'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); + // 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; + } + 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 for + * 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, + input: Request | string | URL, + subject: string, +): Promise { + const { url, scope } = context; + const projects = url.searchParams.getAll("project"); + 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 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 id of ids.length > 0 ? ids : [await scopeProjectId(context)]) { + filtered.searchParams.append("project", id); + } + 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; + } +} + /** - * Refuse an organization outside the invocation's limit, before a request - * to it. + * 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, widerQuery }: ScopeLookup, +): Promise { + const key = lookupKey(context, path); + if (foundInScope.has(key)) { + return; + } + 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; + } + } + // 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. */ +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_READS, 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. The + * scope's lookups go out with the request's headers, so an authenticated + * download's lookups carry its token. A fetch without the token passes + * `lookup`, which sends them instead. */ -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, + lookup?: Send, +): (input: Request | string | URL, init?: RequestInit) => Promise { + const scoped = async ( + input: Request | string | URL, + init?: RequestInit, + ): Promise => { + const headers = + init?.headers ?? (input instanceof Request ? input.headers : undefined); + const request = await scopeRequest( + input, + init, + lookup ?? ((path) => scoped(path, headers ? { headers } : undefined)), + ); + 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/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", {}], 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..f9e06e307a --- /dev/null +++ b/packages/cli/test/lib/target-scope-coverage.test.ts @@ -0,0 +1,87 @@ +/** + * 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", + // 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", + "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. */ +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..5283d94e4b 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,402 @@ 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, + "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" }, + "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/": [], + // 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 }] }, + ], + "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[relative] ?? 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/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. + ["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); }); - 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", + ], + // 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=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); }); test.each([ + ["PUT", "organizations/acme/issues/100/", "organizations/acme/issues/100/"], [ - "another project", - "acme", - { - ...WEB_ISSUE, - project: { id: "2", name: "api", slug: "api", platform: null }, - }, + "GET", + "organizations/acme/issues/100/events/latest/", + "organizations/acme/issues/100/", ], - ["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); + [ + "GET", + "organizations/acme/trace-meta/a/", + "organizations/acme/trace/a/?statsPeriod=14d", + ], + [ + "GET", + "organizations/acme/trace-logs/?traceId=a&statsPeriod=90d", + "organizations/acme/trace/a/?statsPeriod=90d", + ], + [ + "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("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/", + ]); }); -}); -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; + 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"], + ["GET", "organizations/other/dsn-lookup/", "another org's DSN lookup"], + // Paths no rule covers. + ["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"], + ])("refuses %s %s (%s)", async (method, path) => { + await expect(send(WEB_SCOPE, method, path)).rejects.toThrow( + /outside this session's scope \(acme\/web\)/, + ); + }); + + 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")); } - throw error; - } - throw new Error(`${subject} was not refused`); - } + 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.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); - }); - - 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/"); + ["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) => { + 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("an organization scope", () => { + beforeEach(() => __resetScopeLookupsForTests()); + + test.each([ + ["GET", "users/me/"], + ["GET", "organizations/"], + ["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.each([ + ["GET", "organizations/other/issues/"], + ["GET", "projects/other/web/"], + ["GET", "projects/"], + ["GET", "issues/200/"], + ])("refuses %s %s", async (method, path) => { + await expect(send(ORG_SCOPE, method, path)).rejects.toThrow( + /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", () => { + test("sends any request as it is", async () => { + expect(await sentAs({}, "GET", "organizations/other/issues/")).toBe( + "organizations/other/issues/", + ); }); });