diff --git a/apps/cli-docs/src/content/docs/library-usage.md b/apps/cli-docs/src/content/docs/library-usage.md index d784190615..63b6bd40fb 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -169,8 +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 | +| `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/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index 92e7d6c431..f9bf2e6877 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 1b97c1827f..26edc8a9a5 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 1a9157d65b..650b13e949 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 1f60e9ecf0..d3a91208d8 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,21 +665,28 @@ 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 }; } - 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"], ); @@ -684,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/src/lib/api/issues.ts b/packages/cli/src/lib/api/issues.ts index 60ad388844..73c8117357 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 6b601a3812..b7346c71aa 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()` 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"; +/** 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 b0216b2038..294090f141 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,7 +37,8 @@ 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, + * 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( @@ -56,6 +62,12 @@ function buildIsolatedEnv( if (options?.project) { env["SENTRY_PROJECT"] = options.project; } + if (options?.limitToTarget !== false && 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"; } @@ -303,7 +315,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 +378,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 +458,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 +525,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/src/lib/sdk-types.ts b/packages/cli/src/lib/sdk-types.ts index 04cb1a88fb..1cf8912f5b 100644 --- a/packages/cli/src/lib/sdk-types.ts +++ b/packages/cli/src/lib/sdk-types.ts @@ -37,6 +37,15 @@ export type SentryOptions = { */ project?: string; + /** + * Treat `org` and `project` as a limit, not only as defaults (default + * `true`). A command then refuses an issue outside them, including one + * named by an ID that says nothing about its project (a numeric ID, a + * share link, `@latest`). Has no effect without `org`. Set `false` to use + * `org` and `project` only as defaults. + */ + 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 0000000000..5f971848c5 --- /dev/null +++ b/packages/cli/src/lib/target-scope.ts @@ -0,0 +1,77 @@ +/** + * 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` + * 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/commands/issue/utils.test.ts b/packages/cli/test/commands/issue/utils.test.ts index 7852659790..372ab4501b 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" }, 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 0000000000..83120d8958 --- /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/sdk-run-failure.test.ts b/packages/cli/test/lib/sdk-run-failure.test.ts new file mode 100644 index 0000000000..7b060dc81a --- /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(); + }); +}); 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 0000000000..3005e024ff --- /dev/null +++ b/packages/cli/test/lib/target-scope.test.ts @@ -0,0 +1,61 @@ +/** + * 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", name: "web", slug: "web", platform: null }, +}; + +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", name: "api", slug: "api", platform: null }, + }, + ], + ["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(); + }); +});