From 9b4fc5e8c66e33bd82a52a6ac798b2bc435e5f65 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:40:07 +0000 Subject: [PATCH 1/4] fix(sdk): Reject run() when a command fails The SDK's fake process started with `exitCode: 0`. Stricli records a failure with `exitCode ??= code`, which a 0 swallows, so `sdk.run()` resolved `undefined` for a command that failed, such as one whose API request returned 404. The exit code now starts unset, as on Node's own `process`. Ported from the same fix in #1922, which the scope checks in this stack need: a refused request has to reach the caller as an error. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/sdk-invoke.ts | 25 +++++++-------- packages/cli/test/lib/sdk-run-failure.test.ts | 32 +++++++++++++++++++ 2 files changed, 43 insertions(+), 14 deletions(-) create mode 100644 packages/cli/test/lib/sdk-run-failure.test.ts diff --git a/packages/cli/src/lib/sdk-invoke.ts b/packages/cli/src/lib/sdk-invoke.ts index b0216b203..ecc28cf45 100644 --- a/packages/cli/src/lib/sdk-invoke.ts +++ b/packages/cli/src/lib/sdk-invoke.ts @@ -303,7 +303,8 @@ type CaptureContext = { stdin: NodeJS.ReadStream & { fd: 0 }; env: NodeJS.ProcessEnv; cwd: () => string; - exitCode: number; + /** Unset until something fails, as on Node's own `process`. */ + exitCode: number | undefined; }; stdout: Writer; stderr: Writer; @@ -365,7 +366,9 @@ async function buildCaptureContext( stdin: process.stdin, env, cwd: () => cwd, - exitCode: 0, + // Unset, as on Node's `process`: Stricli's `run()` records a failure + // with `exitCode ??= code`, which a 0 here would swallow. + exitCode: undefined, }; if (opts?.abortSignal) { @@ -443,11 +446,9 @@ async function executeWithCapture( await flushTelemetry(); // Check exit code (Stricli sets it without throwing for some errors) - if (captureCtx.context.process.exitCode !== 0) { - throw buildSdkError( - captureCtx.stderrChunks, - captureCtx.context.process.exitCode, - ); + const exitCode = captureCtx.context.process.exitCode ?? 0; + if (exitCode !== 0) { + throw buildSdkError(captureCtx.stderrChunks, exitCode); } return parseOutput( @@ -512,13 +513,9 @@ function executeWithStream( }); // Check exit code — Stricli sets it without throwing for some errors - if (captureCtx.context.process.exitCode !== 0) { - channel.error( - buildSdkError( - captureCtx.stderrChunks, - captureCtx.context.process.exitCode, - ), - ); + const exitCode = captureCtx.context.process.exitCode ?? 0; + if (exitCode !== 0) { + channel.error(buildSdkError(captureCtx.stderrChunks, exitCode)); } else { // Drain any raw stdout the command wrote directly (via stdout.write) // instead of yielding via captureObject — e.g. a binary Uint8Array diff --git a/packages/cli/test/lib/sdk-run-failure.test.ts b/packages/cli/test/lib/sdk-run-failure.test.ts new file mode 100644 index 000000000..7b060dc81 --- /dev/null +++ b/packages/cli/test/lib/sdk-run-failure.test.ts @@ -0,0 +1,32 @@ +/** + * `sdk.run()` rejects when the command fails, including a failure that + * Stricli records only in the process's exit code. + */ + +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import createSentrySDK from "../../src/index.js"; +import { mockFetch, useTestConfigDir } from "../helpers.js"; + +describe("sdk.run() failures", () => { + useTestConfigDir("sdk-run-failure-"); + let originalFetch: typeof fetch; + + beforeEach(() => { + originalFetch = globalThis.fetch; + globalThis.fetch = mockFetch(async () => + Response.json({ detail: "Not found" }, { status: 404 }), + ); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + }); + + test("rejects when the command fails", async () => { + const sdk = createSentrySDK({ + token: `sntryu_${"a".repeat(64)}`, + org: "acme", + }); + await expect(sdk.run("issue", "view", "200")).rejects.toThrow(); + }); +}); From db2dc1fbac71ddf6619e83f0fc85451a7f072505 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:19:46 +0000 Subject: [PATCH 2/4] fix(mcp): Check an issue an ID alone names against the session's project In a project-scoped `sentry mcp --commands` session, the command surface checks the targets a call names, but a numeric issue ID, an issue URL, a share link, a selector (`@latest`), or search text names no project, so `issue view 12345` or `issue resolve 12345` reached an issue in another project of the same organization. The stdio runner now passes `limitToTarget` to the CLI SDK, which makes the session's org and project a limit instead of a default. Issue lookups check the issue they find before a command reads or changes it: `getIssueInOrg` and `getIssueByShortId` refuse another organization before the request and another project after it, the issue and Feedback selectors and issue search look only in the session's project, and `event view` checks a numeric issue before it reads the issue's events. Fixes #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/library-usage.md | 1 + packages/cli/script/check-env-coverage.ts | 8 ++ packages/cli/src/commands/event/view.ts | 13 +++- packages/cli/src/commands/feedback/utils.ts | 13 +++- packages/cli/src/commands/issue/utils.ts | 16 +++- packages/cli/src/lib/api/issues.ts | 12 ++- packages/cli/src/lib/env.ts | 9 +++ packages/cli/src/lib/sdk-invoke.ts | 18 ++++- packages/cli/src/lib/sdk-types.ts | 8 ++ packages/cli/src/lib/target-scope.ts | 77 +++++++++++++++++++ packages/cli/test/lib/target-scope.test.ts | 55 +++++++++++++ 11 files changed, 219 insertions(+), 11 deletions(-) create mode 100644 packages/cli/src/lib/target-scope.ts create mode 100644 packages/cli/test/lib/target-scope.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 d78419061..869769949 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -171,6 +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 | Default organization slug | | `project` | `string` | Auto-detected | Default project slug | +| `limitToTarget` | `boolean` | `false` | Refuse an issue outside `org` and `project`, even one an ID alone names (`12345`, `@latest`) | | `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/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index c07ddd5fc..08c384ae4 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -72,6 +72,14 @@ const INTERNAL_ENV_VARS = new Map([ "SENTRY_CLI_NO_PERSISTENCE", "set by createSentrySDK() unless persist: true, for one invocation", ], + [ + "SENTRY_CLI_SCOPE_ORG", + "set by createSentrySDK({ limitToTarget: true }), for one invocation", + ], + [ + "SENTRY_CLI_SCOPE_PROJECT", + "set by createSentrySDK({ limitToTarget: true }), for one invocation", + ], ["SENTRY_RN_BUNDLE_COMMAND", "internal react-native wrapper plumbing"], ["SENTRY_RN_NO_DEBUG_ID", "internal react-native wrapper plumbing"], ["SENTRY_RN_REAL_HERMES_CLI_PATH", "internal react-native wrapper plumbing"], diff --git a/packages/cli/src/commands/event/view.ts b/packages/cli/src/commands/event/view.ts index 1b97c1827..26edc8a9a 100644 --- a/packages/cli/src/commands/event/view.ts +++ b/packages/cli/src/commands/event/view.ts @@ -78,6 +78,7 @@ 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"; @@ -1139,8 +1140,16 @@ async function resolveIssueIdShortcut( parsed.type === ProjectSpecificationType.Explicit ? parsed.project : undefined; - const projectPromise = explicitProject - ? Promise.resolve(explicitProject) + // 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) : 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 1a9157d65..650b13e94 100644 --- a/packages/cli/src/commands/feedback/utils.ts +++ b/packages/cli/src/commands/feedback/utils.ts @@ -16,7 +16,11 @@ import { parseIssueArgument, } from "../../lib/issue-arguments.js"; import { resolveEffectiveOrg } from "../../lib/region.js"; -import { resolveOrg } from "../../lib/resolve-target.js"; +import { + resolveOrg, + resolveProjectIdsInOrg, +} from "../../lib/resolve-target.js"; +import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js"; import { setOrgProjectContext } from "../../lib/telemetry.js"; import type { SentryFeedback } from "../../types/index.js"; import { buildCommandHint, resolveIssue } from "../issue/utils.js"; @@ -53,9 +57,15 @@ 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) { @@ -67,6 +77,7 @@ 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 1f60e9ecf..7a90bc803 100644 --- a/packages/cli/src/commands/issue/utils.ts +++ b/packages/cli/src/commands/issue/utils.ts @@ -58,6 +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 { setOrgProjectContext } from "../../lib/telemetry.js"; import { isAllDigits, shellQuote } from "../../lib/utils.js"; import type { SentryIssue } from "../../types/index.js"; @@ -599,14 +600,15 @@ 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 - * @throws {ResolutionError} When no unresolved issue matches, or the - * project does not exist + * 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 */ export async function findSelectorIssue( selector: IssueSelector, org: string, - project?: string, + project = getTargetScope()?.project, ): Promise { const projects = project ? await resolveProjectIdsInOrg(org, [project]) @@ -633,6 +635,7 @@ export async function findSelectorIssue( ], ); } + assertIssueInScope(org, issue); return issue; } @@ -662,13 +665,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 }; } diff --git a/packages/cli/src/lib/api/issues.ts b/packages/cli/src/lib/api/issues.ts index 60ad38884..73c811735 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 { assertIssueInScope, assertOrgInScope } from "../target-scope.js"; import { getOrgSdkConfig, @@ -325,19 +326,24 @@ 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, issueId); const collapse = toIssueDetailsCollapse(options?.collapse); const result = await getOrganizationIssue({ ...getOrgSdkConfig(), path: { organization_id_or_slug: orgSlug, issue_id: issueId }, ...(collapse && { query: { collapse } }), }); - return unwrapResult(result, "Failed to get issue"); + const issue = unwrapResult(result, "Failed to get issue"); + assertIssueInScope(orgSlug, issue); + return issue; } /** @@ -398,6 +404,8 @@ 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, @@ -405,6 +413,7 @@ export async function getIssueByShortId( options?: { collapse?: IssueCollapseField[] }, ): Promise { const normalizedShortId = shortId.toUpperCase(); + assertOrgInScope(orgSlug, normalizedShortId); const config = getOrgSdkConfig(); let data: { group?: SentryIssue }; @@ -444,6 +453,7 @@ export async function getIssueByShortId( "Issue not found", ); } + assertIssueInScope(orgSlug, data.group); return data.group; } diff --git a/packages/cli/src/lib/env.ts b/packages/cli/src/lib/env.ts index 6b601a381..a9374508e 100644 --- a/packages/cli/src/lib/env.ts +++ b/packages/cli/src/lib/env.ts @@ -86,3 +86,12 @@ export const NO_PERSISTENCE_ENV_VAR = "SENTRY_CLI_NO_PERSISTENCE"; export function isPersistenceDisabled(): boolean { return getEnv()[NO_PERSISTENCE_ENV_VAR] === "1"; } + +/** + * Internal env vars `createSentrySDK({ limitToTarget: true })` sets to the + * organization and project an invocation is limited to. See + * `target-scope.ts`. + */ +export const SCOPE_ORG_ENV_VAR = "SENTRY_CLI_SCOPE_ORG"; +/** See {@link SCOPE_ORG_ENV_VAR}. */ +export const SCOPE_PROJECT_ENV_VAR = "SENTRY_CLI_SCOPE_PROJECT"; diff --git a/packages/cli/src/lib/sdk-invoke.ts b/packages/cli/src/lib/sdk-invoke.ts index ecc28cf45..a3bf10ec5 100644 --- a/packages/cli/src/lib/sdk-invoke.ts +++ b/packages/cli/src/lib/sdk-invoke.ts @@ -18,7 +18,12 @@ import { homedir } from "node:os"; import type { Span } from "@sentry/core"; import type { Writer } from "../types/index.js"; import { type AsyncChannel, createAsyncChannel } from "./async-channel.js"; -import { NO_PERSISTENCE_ENV_VAR, withInvocation } from "./env.js"; +import { + NO_PERSISTENCE_ENV_VAR, + SCOPE_ORG_ENV_VAR, + SCOPE_PROJECT_ENV_VAR, + withInvocation, +} from "./env.js"; import { stringifyUnknown } from "./errors.js"; import { SentryError, type SentryOptions } from "./sdk-types.js"; import generatedStreamingCommands from "../generated/streaming-commands.json" with { type: "json" }; @@ -32,8 +37,9 @@ const STREAMING_COMMANDS: StreamingCommands = generatedStreamingCommands; /** * Build an isolated env from options, starting from `options.env` or the - * consumer's process.env. Sets auth token, host URL, default org/project, - * output format, and the no-persistence flag. + * consumer's process.env. Sets auth token, host URL, default org/project + * (and the target scope with `limitToTarget`), output format, and the + * no-persistence flag. */ function buildIsolatedEnv( options?: SentryOptions, @@ -56,6 +62,12 @@ function buildIsolatedEnv( if (options?.project) { env["SENTRY_PROJECT"] = options.project; } + if (options?.limitToTarget && options.org) { + env[SCOPE_ORG_ENV_VAR] = options.org; + if (options.project) { + env[SCOPE_PROJECT_ENV_VAR] = options.project; + } + } if (jsonByDefault && !options?.text) { env["SENTRY_OUTPUT_FORMAT"] = "json"; } diff --git a/packages/cli/src/lib/sdk-types.ts b/packages/cli/src/lib/sdk-types.ts index 04cb1a88f..5d7dea0d5 100644 --- a/packages/cli/src/lib/sdk-types.ts +++ b/packages/cli/src/lib/sdk-types.ts @@ -37,6 +37,14 @@ export type SentryOptions = { */ project?: string; + /** + * Treat `org` and `project` as a limit, not only as defaults (default + * `false`). A command then refuses an issue outside them, including one + * named by an ID that says nothing about its project (a numeric ID, a + * share link, `@latest`). Has no effect without `org`. + */ + limitToTarget?: boolean; + /** * Return human-readable text instead of parsed JSON. * When `true`, the `run()` function returns a `string` instead of a parsed object. diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts new file mode 100644 index 000000000..4106e0a03 --- /dev/null +++ b/packages/cli/src/lib/target-scope.ts @@ -0,0 +1,77 @@ +/** + * The organization and project an SDK invocation is limited to + * (`createSentrySDK({ limitToTarget: true })`). + * + * The caller checks the targets a call names, but not an issue that an ID + * alone names: a numeric ID, a share link, or a selector such as `@latest` + * says nothing about its project. Issue lookups check the issue they find + * with {@link assertIssueInScope} before a command reads or changes it. + */ + +import type { SentryIssue } from "../types/index.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"; + +/** The organization, and project if any, an invocation is limited to. */ +type TargetScope = { org: string; project?: string }; + +/** The current invocation's limit, or `undefined` when it has none. */ +export function getTargetScope(): TargetScope | undefined { + const env = getEnv(); + const org = env[SCOPE_ORG_ENV_VAR]; + if (!org) { + return; + } + const project = env[SCOPE_PROJECT_ENV_VAR]; + return project ? { org, project } : { org }; +} + +function outsideScope(issueId: string, scope: TargetScope): ResolutionError { + const target = scope.project ? `${scope.org}/${scope.project}` : scope.org; + return new ResolutionError( + `Issue ${issueId}`, + `is outside this session's scope (${target})`, + sentry`issue list ${scope.project ? target : `${target}/`}`, + [`This session can only read or change issues in ${target}.`], + ); +} + +/** + * Refuse an organization outside the invocation's limit, before a request + * to it. + * + * @param org - The organization a lookup asks + * @param issueId - The issue as given, for the error + * @throws {ResolutionError} When `org` is not the limit's organization + */ +export function assertOrgInScope(org: string, issueId: string): void { + const scope = getTargetScope(); + if (scope && org !== scope.org) { + throw outsideScope(issueId, scope); + } +} + +/** + * Refuse an issue outside the invocation's limit. An issue whose project is + * unknown is refused in a project-limited invocation. + * + * @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 + */ +export function assertIssueInScope( + org: string, + issue: Pick, +): void { + const scope = getTargetScope(); + if (!scope) { + return; + } + const issueId = issue.id ?? ""; + assertOrgInScope(org, issueId); + if (scope.project && issue.project?.slug !== scope.project) { + throw outsideScope(issueId, scope); + } +} diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts new file mode 100644 index 000000000..eaea06f98 --- /dev/null +++ b/packages/cli/test/lib/target-scope.test.ts @@ -0,0 +1,55 @@ +/** + * The issue check of a target-scoped SDK invocation (`limitToTarget`). + */ + +import { describe, expect, test } from "vitest"; +import { + SCOPE_ORG_ENV_VAR, + SCOPE_PROJECT_ENV_VAR, + withEnv, +} from "../../src/lib/env.js"; +import { ResolutionError } from "../../src/lib/errors.js"; +import { assertIssueInScope } from "../../src/lib/target-scope.js"; + +const WEB_ISSUE = { id: "100", project: { id: "1", slug: "web" } }; + +function check( + env: Record, + org: string, + issue: Parameters[1], +): void { + withEnv(env, () => assertIssueInScope(org, issue)); +} + +describe("assertIssueInScope", () => { + const webScope = { + [SCOPE_ORG_ENV_VAR]: "acme", + [SCOPE_PROJECT_ENV_VAR]: "web", + }; + + test("takes any issue without a scope", () => { + expect(() => check({}, "other", WEB_ISSUE)).not.toThrow(); + }); + + test("takes an issue of the scope's project", () => { + expect(() => check(webScope, "acme", WEB_ISSUE)).not.toThrow(); + }); + + test.each([ + [ + "another project", + "acme", + { ...WEB_ISSUE, project: { id: "2", slug: "api" } }, + ], + ["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); + }); + + test("takes any project of an organization scope", () => { + expect(() => + check({ [SCOPE_ORG_ENV_VAR]: "acme" }, "acme", { id: "100" }), + ).not.toThrow(); + }); +}); From 25e63d8b3eaace0d8a22c35164f51d352998fca1 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:09:14 +0000 Subject: [PATCH 3/4] fix(sdk): Limit createSentrySDK() to its org and project by default `limitToTarget` now defaults to `true`: with `org` (and `project`) set, `createSentrySDK()` refuses an issue outside them, including one an ID alone names (`issue view 12345`, `@latest`). Pass `limitToTarget: false` to use `org` and `project` only as defaults, as before. `sentry mcp --commands` still passes `limitToTarget: true` explicitly, so its sessions don't depend on the default. BREAKING CHANGE: `createSentrySDK({ org, project })` no longer reads or changes issues outside `org`/`project`. Callers that use them only to skip typing the slug and look up issues elsewhere must pass `limitToTarget: false`. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/content/docs/library-usage.md | 6 +- packages/cli/src/lib/env.ts | 4 +- packages/cli/src/lib/sdk-invoke.ts | 8 +-- packages/cli/src/lib/sdk-types.ts | 5 +- packages/cli/src/lib/target-scope.ts | 6 +- .../cli/test/lib/sdk-limit-to-target.test.ts | 67 +++++++++++++++++++ packages/cli/test/lib/target-scope.test.ts | 10 ++- 7 files changed, 90 insertions(+), 16 deletions(-) create mode 100644 packages/cli/test/lib/sdk-limit-to-target.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 869769949..63b6bd40f 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -169,9 +169,9 @@ const sdk = createSentrySDK({ token: "...", text: true, cwd: "/my/project" }); |--------|------|---------|-------------| | `token` | `string` | Auto-detected | Auth token for this invocation | | `url` | `string` | `sentry.io` | Sentry instance URL for self-hosted | -| `org` | `string` | Auto-detected | Default organization slug | -| `project` | `string` | Auto-detected | Default project slug | -| `limitToTarget` | `boolean` | `false` | Refuse an issue outside `org` and `project`, even one an ID alone names (`12345`, `@latest`) | +| `org` | `string` | Auto-detected | Organization slug; also a limit while `limitToTarget` is on | +| `project` | `string` | Auto-detected | Project slug; also a limit while `limitToTarget` is on | +| `limitToTarget` | `boolean` | `true` | Refuse an issue outside `org` and `project`, even one an ID alone names (`12345`, `@latest`). Set `false` to use `org` and `project` only as defaults | | `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/env.ts b/packages/cli/src/lib/env.ts index a9374508e..b7346c71a 100644 --- a/packages/cli/src/lib/env.ts +++ b/packages/cli/src/lib/env.ts @@ -88,8 +88,8 @@ export function isPersistenceDisabled(): boolean { } /** - * Internal env vars `createSentrySDK({ limitToTarget: true })` sets to the - * organization and project an invocation is limited to. See + * Internal env vars `createSentrySDK()` sets to the organization and project + * an invocation is limited to, unless `limitToTarget` is `false`. See * `target-scope.ts`. */ export const SCOPE_ORG_ENV_VAR = "SENTRY_CLI_SCOPE_ORG"; diff --git a/packages/cli/src/lib/sdk-invoke.ts b/packages/cli/src/lib/sdk-invoke.ts index a3bf10ec5..294090f14 100644 --- a/packages/cli/src/lib/sdk-invoke.ts +++ b/packages/cli/src/lib/sdk-invoke.ts @@ -37,9 +37,9 @@ const STREAMING_COMMANDS: StreamingCommands = generatedStreamingCommands; /** * Build an isolated env from options, starting from `options.env` or the - * consumer's process.env. Sets auth token, host URL, default org/project - * (and the target scope with `limitToTarget`), output format, and the - * no-persistence flag. + * consumer's process.env. Sets auth token, host URL, org/project (as + * defaults and, unless `limitToTarget` is `false`, as the target scope), + * output format, and the no-persistence flag. */ function buildIsolatedEnv( options?: SentryOptions, @@ -62,7 +62,7 @@ function buildIsolatedEnv( if (options?.project) { env["SENTRY_PROJECT"] = options.project; } - if (options?.limitToTarget && options.org) { + if (options?.limitToTarget !== false && options?.org) { env[SCOPE_ORG_ENV_VAR] = options.org; if (options.project) { env[SCOPE_PROJECT_ENV_VAR] = options.project; diff --git a/packages/cli/src/lib/sdk-types.ts b/packages/cli/src/lib/sdk-types.ts index 5d7dea0d5..1cf8912f5 100644 --- a/packages/cli/src/lib/sdk-types.ts +++ b/packages/cli/src/lib/sdk-types.ts @@ -39,9 +39,10 @@ export type SentryOptions = { /** * Treat `org` and `project` as a limit, not only as defaults (default - * `false`). A command then refuses an issue outside them, including one + * `true`). A command then refuses an issue outside them, including one * named by an ID that says nothing about its project (a numeric ID, a - * share link, `@latest`). Has no effect without `org`. + * share link, `@latest`). Has no effect without `org`. Set `false` to use + * `org` and `project` only as defaults. */ limitToTarget?: boolean; diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 4106e0a03..5f971848c 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -1,6 +1,6 @@ /** - * The organization and project an SDK invocation is limited to - * (`createSentrySDK({ limitToTarget: true })`). + * 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 an issue that an ID * alone names: a numeric ID, a share link, or a selector such as `@latest` @@ -69,7 +69,7 @@ export function assertIssueInScope( if (!scope) { return; } - const issueId = issue.id ?? ""; + const issueId = issue.id; assertOrgInScope(org, issueId); if (scope.project && issue.project?.slug !== scope.project) { throw outsideScope(issueId, scope); diff --git a/packages/cli/test/lib/sdk-limit-to-target.test.ts b/packages/cli/test/lib/sdk-limit-to-target.test.ts new file mode 100644 index 000000000..83120d895 --- /dev/null +++ b/packages/cli/test/lib/sdk-limit-to-target.test.ts @@ -0,0 +1,67 @@ +/** + * `createSentrySDK({ org, project })` limits commands to that project by + * default; `limitToTarget: false` makes `org` and `project` only defaults. + * The checks themselves are covered in `target-scope.test.ts`. + */ + +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import createSentrySDK from "../../src/index.js"; +import issueFixture from "../fixtures/issue.json"; +import { mockFetch, useTestConfigDir } from "../helpers.js"; + +/** Issue 200 is in `api`, outside the SDK's `acme/web`. */ +const API_ISSUE = { + ...issueFixture, + id: "200", + shortId: "API-1", + project: { id: "2", slug: "api", name: "API", platform: "python" }, +}; + +function sentryApi(): typeof fetch { + return mockFetch(async (input, init) => { + const path = new URL(new Request(input, init).url).pathname; + if (path === "/api/0/organizations/acme/") { + return Response.json({ id: "9", slug: "acme", name: "Acme" }); + } + if (path === "/api/0/organizations/acme/issues/200/") { + return Response.json(API_ISSUE); + } + return Response.json({ detail: "Not found" }, { status: 404 }); + }); +} + +function viewIssue(options: { limitToTarget?: boolean }): Promise { + const sdk = createSentrySDK({ + token: `sntryu_${"a".repeat(64)}`, + org: "acme", + project: "web", + ...options, + }); + return sdk.run("issue", "view", "200") as Promise; +} + +describe("createSentrySDK({ org, project })", () => { + useTestConfigDir("sdk-limit-to-target-"); + let originalFetch: typeof fetch; + + beforeEach(() => { + originalFetch = globalThis.fetch; + globalThis.fetch = sentryApi(); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + }); + + test("refuses another project's issue by default", async () => { + await expect(viewIssue({})).rejects.toThrow( + /Issue 200 is outside this session's scope \(acme\/web\)/, + ); + }); + + test("reads it with limitToTarget: false", async () => { + expect(await viewIssue({ limitToTarget: false })).toMatchObject({ + shortId: "API-1", + }); + }); +}); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index eaea06f98..3005e024f 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -11,7 +11,10 @@ import { import { ResolutionError } from "../../src/lib/errors.js"; import { assertIssueInScope } from "../../src/lib/target-scope.js"; -const WEB_ISSUE = { id: "100", project: { id: "1", slug: "web" } }; +const WEB_ISSUE = { + id: "100", + project: { id: "1", name: "web", slug: "web", platform: null }, +}; function check( env: Record, @@ -39,7 +42,10 @@ describe("assertIssueInScope", () => { [ "another project", "acme", - { ...WEB_ISSUE, project: { id: "2", slug: "api" } }, + { + ...WEB_ISSUE, + project: { id: "2", name: "api", slug: "api", platform: null }, + }, ], ["another organization", "other", WEB_ISSUE], ["an unknown project", "acme", { id: "100" }], From b9062ad00a5f376b63b5cd3dac51a34d61aaffae 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:38:50 +0000 Subject: [PATCH 4/4] fix(cli): Name the scope project in issue search errors In a project-scoped session, the issue search runs in that project alone, so the no-match and several-match errors name it, and their recovery command lists that project's issues. --- packages/cli/src/commands/issue/utils.ts | 8 +++--- .../cli/test/commands/issue/utils.test.ts | 26 ++++++++++++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/commands/issue/utils.ts b/packages/cli/src/commands/issue/utils.ts index 7a90bc803..d3a91208d 100644 --- a/packages/cli/src/commands/issue/utils.ts +++ b/packages/cli/src/commands/issue/utils.ts @@ -680,11 +680,13 @@ async function resolveIssueSearch( return { org, issue }; } - const listCommand = sentry`issue list ${org}/ --query ${shellQuote(query)}`; + // In a project scope, the search ran in that project alone. + const searched = scopeProject ? `${org}/${scopeProject}` : org; + const listCommand = sentry`issue list ${org}/${scopeProject ?? ""} --query ${shellQuote(query)}`; if (!issue) { throw new ResolutionError( `Search ${shellQuote(query)}`, - `matched no issues in '${org}'`, + `matched no issues in '${searched}'`, listCommand, ["Pass an issue ID or short ID instead, e.g. CLI-G or 123456789"], ); @@ -692,7 +694,7 @@ async function resolveIssueSearch( const count = nextCursor ? `${issues.length}+` : String(issues.length); throw new ResolutionError( `Search ${shellQuote(query)}`, - `matched ${count} issues in '${org}'`, + `matched ${count} issues in '${searched}'`, listCommand, issues.map( (candidate) => diff --git a/packages/cli/test/commands/issue/utils.test.ts b/packages/cli/test/commands/issue/utils.test.ts index 785265979..372ab4501 100644 --- a/packages/cli/test/commands/issue/utils.test.ts +++ b/packages/cli/test/commands/issue/utils.test.ts @@ -2331,7 +2331,13 @@ describe("resolveIssue with share URLs", () => { }); describe("resolveIssue with search text", () => { - useEnvSandbox(["SENTRY_ORG", "SENTRY_PROJECT", "SENTRY_DSN"]); + useEnvSandbox([ + "SENTRY_ORG", + "SENTRY_PROJECT", + "SENTRY_DSN", + "SENTRY_CLI_SCOPE_ORG", + "SENTRY_CLI_SCOPE_PROJECT", + ]); /** Issues the search returns, and the queries it got */ function mockSearch( @@ -2340,6 +2346,9 @@ describe("resolveIssue with search text", () => { const queries: URLSearchParams[] = []; globalThis.fetch = mockFetch(async (input, init) => { const url = new URL(new Request(input, init).url); + if (url.pathname === "/api/0/projects/my-org/web/") { + return Response.json({ id: "7", slug: "web" }); + } if (url.pathname === "/api/0/organizations/my-org/issues/") { queries.push(url.searchParams); return Response.json( @@ -2378,6 +2387,21 @@ describe("resolveIssue with search text", () => { ); }); + test("in a project scope, no match names the project it searched", async () => { + process.env["SENTRY_CLI_SCOPE_ORG"] = "my-org"; + process.env["SENTRY_CLI_SCOPE_PROJECT"] = "web"; + const queries = mockSearch([]); + const error = await resolve("login timeout").catch((e: unknown) => e); + expect(queries[0]?.getAll("project")).toEqual(["7"]); + expect(error).toBeInstanceOf(ResolutionError); + expect((error as ResolutionError).message).toContain( + "matched no issues in 'my-org/web'", + ); + expect((error as ResolutionError).hint).toBe( + "sentry issue list my-org/web --query 'login timeout'", + ); + }); + test("several matches are a ResolutionError listing them", async () => { mockSearch([ { id: "1", shortId: "CLI-G", title: "Login timeout" },