From f98497e659a132bea9601583f7ebacf5609adff8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:22:16 +0000 Subject: [PATCH 1/7] feat(mcp): Build the scope rules from Sentry's x-sentry-project-scope The scope rules of `limitToTarget` were a hand-written endpoint table. Sentry now declares them with the `x-sentry-project-scope` OpenAPI extension, which `@sentry/api` carries as `ApiOperation.projectScope`. `script/generate-api-schema.ts` extracts them at build time into `src/generated/project-scope-operations.json`, as it does the idempotent writes, and `target-scope-rules.ts` builds its rules from them: - `org-metadata`: an organization read the project scope may send. - `filter`: an organization endpoint filtered to the scope's project. - `response:`: a lookup by an ID alone, checked by the project IDs at the pointer of its response; requests under its path look it up first. Hand rules remain only where the schema can't say it: project paths, account reads, getsentry's `customers/`, endpoints the schema doesn't publish (short IDs, event IDs, share links, traces), `trace-meta` and `trace-logs` (they ignore `project`), and release writes (a release spans projects). This needs a `@sentry/api` release with `projectScope`. Until then the generated list is empty and a project scope refuses the endpoints it would cover. The scope tests run on a fixture of the declarations, and `target-scope-catalog.test.ts` checks the fixture against the catalog once it has them. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/script/generate-api-schema.ts | 33 +- packages/cli/script/lib/api-schema.ts | 21 ++ packages/cli/src/global.d.ts | 5 + packages/cli/src/lib/target-scope-rules.ts | 329 +++++++++--------- .../fixtures/project-scope-operations.json | 257 ++++++++++++++ .../cli/test/lib/sdk-limit-to-target.test.ts | 13 +- .../cli/test/lib/target-scope-catalog.test.ts | 27 ++ packages/cli/test/lib/target-scope.test.ts | 11 +- .../test/script/generate-api-schema.test.ts | 37 +- 9 files changed, 569 insertions(+), 164 deletions(-) create mode 100644 packages/cli/test/fixtures/project-scope-operations.json create mode 100644 packages/cli/test/lib/target-scope-catalog.test.ts diff --git a/packages/cli/script/generate-api-schema.ts b/packages/cli/script/generate-api-schema.ts index 65f0acab45..aafc2fdb52 100644 --- a/packages/cli/script/generate-api-schema.ts +++ b/packages/cli/script/generate-api-schema.ts @@ -2,20 +2,28 @@ * Generate the CLI discovery index from the installed SDK's operation catalog. * * Usage: pnpm ts script/generate.ts schema - * Outputs: src/generated/api-schema.json and src/generated/idempotent-operations.json + * Outputs: src/generated/api-schema.json, src/generated/idempotent-operations.json + * and src/generated/project-scope-operations.json */ import { mkdir, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { operations } from "@sentry/api/operations"; import { selectIdempotentWrites } from "@sentry/api/client"; -import { projectApiOperations } from "./lib/api-schema.js"; +import { + projectApiOperations, + selectProjectScopeOperations, +} from "./lib/api-schema.js"; import { logger } from "../src/lib/logger.js"; const OUTPUT_PATH = "src/generated/api-schema.json"; const IDEMPOTENT_OUTPUT_PATH = "src/generated/idempotent-operations.json"; +const PROJECT_SCOPE_OUTPUT_PATH = "src/generated/project-scope-operations.json"; -/** Write the endpoint index and the idempotent write operations. */ +/** + * Write the endpoint index, the idempotent write operations and the + * operations' project scopes. + */ export async function emit(): Promise { const endpoints = projectApiOperations(operations); @@ -36,4 +44,23 @@ export async function emit(): Promise { logger.success( `Generated ${IDEMPOTENT_OUTPUT_PATH} (${idempotentOperations.length} operations)`, ); + + const projectScopeOperations = selectProjectScopeOperations(operations); + + await writeFile( + PROJECT_SCOPE_OUTPUT_PATH, + JSON.stringify(projectScopeOperations, null, 2), + ); + + if (projectScopeOperations.length === 0) { + // Scoped sessions still work, but refuse every endpoint the catalog + // would have covered. + logger.warn( + `${PROJECT_SCOPE_OUTPUT_PATH} is empty: this @sentry/api has no projectScope`, + ); + } else { + logger.success( + `Generated ${PROJECT_SCOPE_OUTPUT_PATH} (${projectScopeOperations.length} operations)`, + ); + } } diff --git a/packages/cli/script/lib/api-schema.ts b/packages/cli/script/lib/api-schema.ts index 9d8f567ce9..d31d4f603d 100644 --- a/packages/cli/script/lib/api-schema.ts +++ b/packages/cli/script/lib/api-schema.ts @@ -3,6 +3,7 @@ import { API_BASE_PATH } from "@sentry/api/client"; import type { ApiOperation } from "@sentry/api/operations"; import type { ApiEndpoint } from "../../src/lib/api-schema.js"; +import type { ProjectScopeOperation } from "../../src/lib/target-scope-rules.js"; /** * Keep CLI grouping, output names and legacy deprecation detection local. @@ -45,3 +46,23 @@ function deriveResource(url: string): string { .filter((s) => s.length > 0 && !s.startsWith("{")); return segments.at(-1) ?? "unknown"; } + +/** + * The operations Sentry declares an `x-sentry-project-scope` for, other + * than `path` (the scope rules match project paths themselves), for + * `target-scope-rules.ts`. `@sentry/api` carries it as `projectScope`. + */ +export function selectProjectScopeOperations( + catalog: readonly { method: string; path: string; projectScope?: string }[], +): ProjectScopeOperation[] { + return catalog + .flatMap(({ method, path, projectScope }) => + projectScope && projectScope !== "path" + ? [{ method, path, scope: projectScope }] + : [], + ) + .sort( + (a, b) => + a.path.localeCompare(b.path) || a.method.localeCompare(b.method), + ); +} diff --git a/packages/cli/src/global.d.ts b/packages/cli/src/global.d.ts index 76f1ae59e3..c584d8ac77 100644 --- a/packages/cli/src/global.d.ts +++ b/packages/cli/src/global.d.ts @@ -52,3 +52,8 @@ declare module "*/generated/idempotent-operations.json" { const operations: unknown; export default operations; } + +declare module "*/generated/project-scope-operations.json" { + const operations: unknown; + export default operations; +} diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index e3cc1b0291..dbbdcd5f29 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -3,10 +3,19 @@ * 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. + * Most rules come from Sentry's schema: endpoints declare how they stay in + * a project with the `x-sentry-project-scope` OpenAPI extension, which the + * `@sentry/api` catalog carries as `projectScope`, and + * `script/generate-api-schema.ts` extracts at build time (see + * {@link catalogRules}). The rest are written here ({@link OVERRIDES}). + * + * In a project scope, a request no rule matches is refused. When a command + * needs a new endpoint, declare its scope in Sentry; write a rule here only + * when the schema can't say it. */ +import generatedProjectScopes from "../generated/project-scope-operations.json" with { type: "json" }; + /** How a matched request stays in the scope's project. */ type ScopeEnforcement = /** The path names the scope's project, as `:project`. */ @@ -28,7 +37,9 @@ type ScopeEnforcement = /** The path the response proves in scope, for {@link LookUpFirst}. */ path?: (params: Record) => string; } - | LookUpFirst; + | LookUpFirst + /** Refused even though a broader rule would cover it. */ + | { kind: "refused" }; /** * A request that reads or changes something an ID names, without saying @@ -78,41 +89,17 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [ ]; /** - * 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. + * An operation of the `@sentry/api` catalog with an `x-sentry-project-scope` + * other than `path`, as `script/generate-api-schema.ts` extracts it. */ -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/" }, -]; +export type ProjectScopeOperation = { + /** Uppercase HTTP method */ + method: string; + /** OpenAPI path template, such as `/api/0/organizations/{org}/issues/` */ + path: string; + /** `filter`, `org-metadata` or `response:` */ + scope: string; +}; /** `value` as an object, or `{}` when it is not one. */ export function record(value: unknown): Record { @@ -127,6 +114,127 @@ function ref(value: unknown): string | undefined { : undefined; } +/** + * The values at a JSON pointer (RFC 6901), where a `*` segment is every + * element of an array, such as each of a release's `projects`. + */ +function valuesAt(body: unknown, pointer: string): unknown[] { + let values = [body]; + for (const raw of pointer.split("/").slice(1)) { + const segment = raw.replaceAll("~1", "/").replaceAll("~0", "~"); + values = values.flatMap((value) => { + if (segment === "*") { + return Array.isArray(value) ? value : []; + } + return Array.isArray(value) + ? [value[Number(segment)]] + : [record(value)[segment]]; + }); + } + return values; +} + +/** The rule pattern of a catalog path: `{name}` becomes `:name`. */ +function patternOf(path: string): string { + return path.replace(/^\/api\/0\//, "").replace(/\{([^}]+)\}/g, ":$1"); +} + +/** + * What a lookup's last path param names, for errors: `Issue 200` for + * `organizations/:org/issues/:issue_id/`. + */ +function subjectOf(pattern: string) { + const parts = pattern.split("/").filter(Boolean); + const param = parts.at(-1)?.slice(1) ?? ""; + const kind = (parts.at(-2) ?? "").replace(/s$/, "").replaceAll("-", " "); + const label = kind.charAt(0).toUpperCase() + kind.slice(1); + return (params: Record): string => + `${label} ${params[param] ?? ""}`; +} + +/** The concrete path a pattern names, from a rule's params. */ +function pathFrom(pattern: string) { + return (params: Record): string => + pattern.replace(/:([^/]+)/g, (_, name: string) => + encodeURIComponent(params[name] ?? ""), + ); +} + +const RESPONSE_PREFIX = "response:"; + +/** + * The rules Sentry declares for its endpoints with `x-sentry-project-scope`: + * + * - `org-metadata`: an organization read with no project's data in it. + * - `filter`: an organization endpoint filtered to the scope's project. + * - `response:`: a lookup by an ID alone, checked by the project + * IDs at the pointer of its response. A request under its path (`PUT` + * of the same path, or any sub-resource) looks it up first. + */ +export function catalogRules(entries: unknown): { + orgReads: SimpleRule[]; + rules: ScopeRule[]; +} { + const orgReads: SimpleRule[] = []; + const checked: ScopeRule[] = []; + const lookedUpFirst: ScopeRule[] = []; + for (const entry of Array.isArray(entries) ? entries : []) { + const { method, path, scope } = record(entry); + if ( + typeof method !== "string" || + typeof path !== "string" || + typeof scope !== "string" + ) { + continue; + } + const pattern = patternOf(path); + const methods = method === "GET" ? READS : [method]; + if (scope === "org-metadata" && method === "GET") { + orgReads.push({ pattern, methods }); + } else if (scope === "filter") { + checked.push({ pattern, methods, enforce: { kind: "project-filter" } }); + } else if (scope.startsWith(RESPONSE_PREFIX) && method === "GET") { + const pointer = scope.slice(RESPONSE_PREFIX.length); + const own = pathFrom(pattern); + const subject = subjectOf(pattern); + checked.push({ + pattern, + subject, + enforce: { + kind: "response", + projects: (body) => { + const refs = valuesAt(body, pointer).map(ref); + return refs.length > 0 ? refs : [undefined]; + }, + path: own, + }, + }); + lookedUpFirst.push({ + pattern: `${pattern}**`, + methods: ANY_METHOD, + subject, + enforce: { + kind: "look-up-first", + lookups: (params) => [{ path: own(params) }], + }, + }); + } + } + return { orgReads, rules: [...checked, ...lookedUpFirst] }; +} + +const CATALOG = catalogRules(generatedProjectScopes); + +/** + * Read-only organization metadata a project scope may read: what Sentry + * declares `org-metadata`, and the reads its schema doesn't publish. + */ +export const ORG_READS: readonly SimpleRule[] = [ + // getsentry's subscription details, outside Sentry's schema. + { pattern: "customers/:org/" }, + ...CATALOG.orgReads, +]; + /** * One project's ref: its slug when it has one, which the scope can check * without looking up its own project's ID. @@ -135,7 +243,7 @@ function refOf(slug: unknown, id: unknown): string | undefined { return ref(slug) ?? ref(id); } -/** `{ project: { slug, id } }`, as issues and monitors carry it. */ +/** `{ project: { slug, id } }`, as an issue carries it. */ function projectOf(body: unknown): (string | undefined)[] { const project = record(record(body)["project"]); return [refOf(project["slug"], project["id"])]; @@ -150,24 +258,12 @@ function traceProjects(spans: unknown): (string | undefined)[] { const fields = record(span); return [ refOf(fields["project_slug"], fields["project_id"]), - ...(Array.isArray(fields["children"]) - ? traceProjects(fields["children"]) - : []), + ...(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"); +const tracePath = pathFrom("organizations/:org/trace/:trace/"); /** A trace lookup for `trace-meta` and `trace-logs`, over the same period. */ function traceLookup( @@ -187,54 +283,12 @@ function traceLookup( return { path: tracePath(params), query: query.toString() }; } -const PROJECT_FILTERED = [ - "issues/", - "events/", - "events-timeseries/", - "events-dropped/", - "trace-items/attributes/", - "replays/", - "replay-count/", - "monitors/", - "detectors/", - "workflows/", - "releases/", - "agents/conversations/", -].map((path): ScopeRule => ({ - pattern: `organizations/:org/${path}`, - // Bulk issue changes (`PUT issues/?id=...`) are filtered the same way. - methods: path === "issues/" ? ["GET", "HEAD", "PUT", "DELETE"] : READS, - enforce: { kind: "project-filter" }, -})); - -/** The rules of a project scope, first match wins. */ -export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ - { - pattern: "projects/:org/:project/**", - methods: ANY_METHOD, - subject: ({ org, project }) => `Project ${org}/${project}`, - enforce: { kind: "project-path" }, - }, - { - pattern: "organizations/:org/projects/:project/**", - methods: ANY_METHOD, - subject: ({ org, project }) => `Project ${org}/${project}`, - enforce: { kind: "project-path" }, - }, - { - pattern: "organizations/:org/issues/:issue/", - subject: ({ issue }) => `Issue ${issue}`, - enforce: { kind: "response", projects: projectOf, path: issuePath }, - }, - { - pattern: "organizations/:org/issues/:issue/**", - methods: ANY_METHOD, - subject: ({ issue }) => `Issue ${issue}`, - enforce: { - kind: "look-up-first", - lookups: (params) => [{ path: issuePath(params) }], - }, - }, +/** + * Rules the catalog can't give: endpoints Sentry's schema doesn't publish + * (short IDs, event IDs, share links, traces), endpoints that don't do what + * their schema says (`trace-logs` ignores `project`), and release writes. + */ +const OVERRIDES: readonly ScopeRule[] = [ { pattern: "organizations/:org/shortids/:issue/", subject: ({ issue }) => `Issue ${issue?.toUpperCase()}`, @@ -292,71 +346,30 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ }, }, { - 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 }, + // A release can span projects, so changing one reaches past the scope. + pattern: "organizations/:org/releases/:version/**", + methods: ["POST", "PUT", "PATCH", "DELETE"], + subject: ({ version }) => `Release ${version}`, + enforce: { kind: "refused" }, }, +]; + +/** The rules of a project scope, first match wins. */ +export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [ { - pattern: "organizations/:org/monitors/:monitor/**", + pattern: "projects/:org/:project/**", 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, - }, + subject: ({ org, project }) => `Project ${org}/${project}`, + enforce: { kind: "project-path" }, }, { - pattern: "organizations/:org/detectors/:detector/**", + pattern: "organizations/:org/projects/:project/**", 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) }], - }, + subject: ({ org, project }) => `Project ${org}/${project}`, + enforce: { kind: "project-path" }, }, - ...PROJECT_FILTERED, + ...OVERRIDES, + ...CATALOG.rules, ]; type Match = { rule: T; params: Record }; diff --git a/packages/cli/test/fixtures/project-scope-operations.json b/packages/cli/test/fixtures/project-scope-operations.json new file mode 100644 index 0000000000..7c25893c5d --- /dev/null +++ b/packages/cli/test/fixtures/project-scope-operations.json @@ -0,0 +1,257 @@ +[ + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/agents/conversations/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/available-actions/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/chunk-upload/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/code-mappings/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/config/integrations/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/revisions/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/detectors/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/detectors/{detector_id}/", + "scope": "response:/projectId" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/discover/saved/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/discover/saved/{query_id}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/dsn-lookup/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/environments/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/events-dropped/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/events-timeseries/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/events/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/group-search-views/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/integrations/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/channel-validate/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/channels/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/repos/", + "scope": "org-metadata" + }, + { + "method": "DELETE", + "path": "/api/0/organizations/{organization_id_or_slug}/issues/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/issues/", + "scope": "filter" + }, + { + "method": "PUT", + "path": "/api/0/organizations/{organization_id_or_slug}/issues/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/", + "scope": "response:/project/id" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/members/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/members/{member_id}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/monitors/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/monitors/{monitor_id_or_slug}/", + "scope": "response:/project/id" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/projects/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/releases/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/releases/{version}/", + "scope": "response:/projects/*/id" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/replay-count/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/replays/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/replays/{replay_id}/", + "scope": "response:/data/project_id" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/repos/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/repos/{repo_id}/commits/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/sentry-app-components/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/sentry-app-installations/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/sentry-apps/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/teams/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/trace-items/attributes/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/user-teams/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/workflows/", + "scope": "filter" + }, + { + "method": "GET", + "path": "/api/0/organizations/{organization_id_or_slug}/workflows/{workflow_id}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/members/", + "scope": "org-metadata" + }, + { + "method": "GET", + "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/projects/", + "scope": "org-metadata" + } +] 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 cc6b3f4f7a..37736b1274 100644 --- a/packages/cli/test/lib/sdk-limit-to-target.test.ts +++ b/packages/cli/test/lib/sdk-limit-to-target.test.ts @@ -4,12 +4,20 @@ * The checks themselves are covered in `target-scope.test.ts`. */ -import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { afterEach, beforeEach, describe, expect, test, vi } 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"; +// The scope rules Sentry declares (`x-sentry-project-scope`), until the +// installed `@sentry/api` carries them. `target-scope-catalog.test.ts` +// checks the fixture against the generated catalog once it does. +vi.mock("../../src/generated/project-scope-operations.json", async () => ({ + default: (await import("../../test/fixtures/project-scope-operations.json")) + .default, +})); + /** Issue 200 is in `api`, outside the SDK's `acme/web`. */ const API_ISSUE = { ...issueFixture, @@ -24,6 +32,9 @@ function sentryApi(): typeof fetch { if (path === "/api/0/organizations/acme/") { return Response.json({ id: "9", slug: "acme", name: "Acme" }); } + if (path === "/api/0/projects/acme/web/") { + return Response.json({ id: "1", slug: "web" }); + } if (path === "/api/0/organizations/acme/issues/200/") { return Response.json(API_ISSUE); } diff --git a/packages/cli/test/lib/target-scope-catalog.test.ts b/packages/cli/test/lib/target-scope-catalog.test.ts new file mode 100644 index 0000000000..32129de1c8 --- /dev/null +++ b/packages/cli/test/lib/target-scope-catalog.test.ts @@ -0,0 +1,27 @@ +/** + * The scope tests run on `test/fixtures/project-scope-operations.json`, the + * `x-sentry-project-scope` declarations they expect from Sentry. Once the + * installed `@sentry/api` carries them, every one must be in the catalog, + * or the tests prove rules the CLI doesn't have. + */ + +import { existsSync, readFileSync } from "node:fs"; +import { describe, expect, test } from "vitest"; +import fixture from "../fixtures/project-scope-operations.json"; + +const GENERATED = new URL( + "../../src/generated/project-scope-operations.json", + import.meta.url, +); +const generated: unknown[] = existsSync(GENERATED) + ? JSON.parse(readFileSync(GENERATED, "utf8")) + : []; + +describe("the scope rules the tests expect", () => { + test.skipIf(generated.length === 0)( + "are all in the @sentry/api catalog", + () => { + expect(generated).toEqual(expect.arrayContaining(fixture)); + }, + ); +}); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 96d6731b26..b51a9db3ac 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -4,7 +4,7 @@ * checks by their response, or refuses. */ -import { beforeEach, describe, expect, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; import { SCOPE_ORG_ENV_VAR, SCOPE_PROJECT_ENV_VAR, @@ -16,6 +16,14 @@ import { withTargetScope, } from "../../src/lib/target-scope.js"; +// The scope rules Sentry declares (`x-sentry-project-scope`), until the +// installed `@sentry/api` carries them. `target-scope-catalog.test.ts` +// checks the fixture against the generated catalog once it does. +vi.mock("../../src/generated/project-scope-operations.json", async () => ({ + default: (await import("../../test/fixtures/project-scope-operations.json")) + .default, +})); + const BASE = "https://sentry.io/api/0/"; const WEB = { id: "1", slug: "web" }; const API = { id: "2", slug: "api" }; @@ -246,6 +254,7 @@ describe("a project scope", () => { ["GET", "organizations/acme/preprodartifacts/1/size-analysis/", "preprod"], ["GET", "organizations/acme/agents/conversations/9/", "a conversation"], ["POST", "organizations/acme/dashboards/", "an organization write"], + ["PUT", "organizations/acme/releases/1.0/", "a change to a release"], ["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) => { diff --git a/packages/cli/test/script/generate-api-schema.test.ts b/packages/cli/test/script/generate-api-schema.test.ts index db2078f8fd..4963657a97 100644 --- a/packages/cli/test/script/generate-api-schema.test.ts +++ b/packages/cli/test/script/generate-api-schema.test.ts @@ -1,6 +1,9 @@ import { operations, type ApiOperation } from "@sentry/api/operations"; import { describe, expect, test } from "vitest"; -import { projectApiOperations } from "../../script/lib/api-schema.js"; +import { + projectApiOperations, + selectProjectScopeOperations, +} from "../../script/lib/api-schema.js"; import { searchEndpoints } from "../../src/lib/api-schema.js"; const events = { @@ -105,3 +108,35 @@ describe("SDK catalog projection", () => { } }); }); + +describe("project scope extraction", () => { + test("keeps declared scopes other than path, sorted", () => { + expect( + selectProjectScopeOperations([ + { + ...events, + path: "/api/0/organizations/{org}/z/", + projectScope: "filter", + }, + { + ...events, + path: "/api/0/projects/{org}/{project}/", + projectScope: "path", + }, + { + ...events, + path: "/api/0/organizations/{org}/a/{id}/", + projectScope: "response:/project/id", + }, + events, + ]), + ).toEqual([ + { + method: "GET", + path: "/api/0/organizations/{org}/a/{id}/", + scope: "response:/project/id", + }, + { method: "GET", path: "/api/0/organizations/{org}/z/", scope: "filter" }, + ]); + }); +}); From bb02f8c9388feb5f55aed2294bd5170cf55ab07b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:46:04 +0000 Subject: [PATCH 2/7] fix(mcp): Use an interim copy of the scope declarations until the bump The installed `@sentry/api` (1.74) has no `projectScope`, so the generated catalog list is empty and a project scope refused every endpoint the catalog covers, `chunk-upload/` included. A scoped `sourcemap upload` was refused before its token check. Until the `@sentry/api` 3.x bump, the rules come from `interim-project-scope-operations.json`, a copy of what getsentry/sentry#132722 declares. It was the tests' fixture, so the tests now run on the same rules the CLI enforces. Once the catalog has any declarations it wins, and a guard test checks that every interim entry is in it. The copy and `projectScopeDeclarations` are marked for deletion with the bump. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../interim-project-scope-operations.json} | 0 packages/cli/src/lib/target-scope-rules.ts | 20 +++++- .../cli/test/lib/sdk-limit-to-target.test.ts | 10 +-- .../cli/test/lib/target-scope-catalog.test.ts | 63 ++++++++++++++++--- packages/cli/test/lib/target-scope.test.ts | 10 +-- 5 files changed, 75 insertions(+), 28 deletions(-) rename packages/cli/{test/fixtures/project-scope-operations.json => src/lib/interim-project-scope-operations.json} (100%) diff --git a/packages/cli/test/fixtures/project-scope-operations.json b/packages/cli/src/lib/interim-project-scope-operations.json similarity index 100% rename from packages/cli/test/fixtures/project-scope-operations.json rename to packages/cli/src/lib/interim-project-scope-operations.json diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index dbbdcd5f29..3d46665611 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -15,6 +15,9 @@ */ import generatedProjectScopes from "../generated/project-scope-operations.json" with { type: "json" }; +// INTERIM: delete with the `@sentry/api` 3.x bump, along with +// `projectScopeDeclarations` and the JSON file. +import interimProjectScopes from "./interim-project-scope-operations.json" with { type: "json" }; /** How a matched request stays in the scope's project. */ type ScopeEnforcement = @@ -223,7 +226,22 @@ export function catalogRules(entries: unknown): { return { orgReads, rules: [...checked, ...lookedUpFirst] }; } -const CATALOG = catalogRules(generatedProjectScopes); +/** + * The `x-sentry-project-scope` declarations to build rules from: the + * installed `@sentry/api` catalog's, or, while it has none, an interim copy + * of what getsentry/sentry#132722 declares. The copy keeps project scopes + * working until the `@sentry/api` 3.x bump, which deletes it. + */ +export function projectScopeDeclarations( + generated: readonly unknown[], + interim: readonly unknown[], +): readonly unknown[] { + return generated.length > 0 ? generated : interim; +} + +const CATALOG = catalogRules( + projectScopeDeclarations(generatedProjectScopes, interimProjectScopes), +); /** * Read-only organization metadata a project scope may read: what Sentry 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 37736b1274..fa74a2a072 100644 --- a/packages/cli/test/lib/sdk-limit-to-target.test.ts +++ b/packages/cli/test/lib/sdk-limit-to-target.test.ts @@ -4,20 +4,12 @@ * The checks themselves are covered in `target-scope.test.ts`. */ -import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +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"; -// The scope rules Sentry declares (`x-sentry-project-scope`), until the -// installed `@sentry/api` carries them. `target-scope-catalog.test.ts` -// checks the fixture against the generated catalog once it does. -vi.mock("../../src/generated/project-scope-operations.json", async () => ({ - default: (await import("../../test/fixtures/project-scope-operations.json")) - .default, -})); - /** Issue 200 is in `api`, outside the SDK's `acme/web`. */ const API_ISSUE = { ...issueFixture, diff --git a/packages/cli/test/lib/target-scope-catalog.test.ts b/packages/cli/test/lib/target-scope-catalog.test.ts index 32129de1c8..9c330a0d05 100644 --- a/packages/cli/test/lib/target-scope-catalog.test.ts +++ b/packages/cli/test/lib/target-scope-catalog.test.ts @@ -1,13 +1,32 @@ /** - * The scope tests run on `test/fixtures/project-scope-operations.json`, the - * `x-sentry-project-scope` declarations they expect from Sentry. Once the - * installed `@sentry/api` carries them, every one must be in the catalog, - * or the tests prove rules the CLI doesn't have. + * Where the scope rules come from. Until the installed `@sentry/api` + * carries `x-sentry-project-scope`, they come from an interim copy of what + * Sentry declares (`src/lib/interim-project-scope-operations.json`). Once + * the catalog has declarations, the catalog wins, and every interim entry + * must be in it, or deleting the copy with the bump would drop a rule. */ import { existsSync, readFileSync } from "node:fs"; -import { describe, expect, test } from "vitest"; -import fixture from "../fixtures/project-scope-operations.json"; +import { describe, expect, test, vi } from "vitest"; +import { + SCOPE_ORG_ENV_VAR, + SCOPE_PROJECT_ENV_VAR, + withEnv, +} from "../../src/lib/env.js"; +import interim from "../../src/lib/interim-project-scope-operations.json"; +import { scopeRequest } from "../../src/lib/target-scope.js"; +import { projectScopeDeclarations } from "../../src/lib/target-scope-rules.js"; + +// A catalog that declares only the DSN lookup. +vi.mock("../../src/generated/project-scope-operations.json", () => ({ + default: [ + { + method: "GET", + path: "/api/0/organizations/{organization_id_or_slug}/dsn-lookup/", + scope: "org-metadata", + }, + ], +})); const GENERATED = new URL( "../../src/generated/project-scope-operations.json", @@ -17,11 +36,37 @@ const generated: unknown[] = existsSync(GENERATED) ? JSON.parse(readFileSync(GENERATED, "utf8")) : []; -describe("the scope rules the tests expect", () => { +const send = async () => Response.json({ id: "1", slug: "web" }); + +function scoped(path: string) { + return withEnv( + { [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" }, + () => scopeRequest(`https://sentry.io/api/0/${path}`, undefined, send), + ); +} + +describe("the scope rules' declarations", () => { + test("are the interim copy while the catalog has none", () => { + expect(projectScopeDeclarations([], interim)).toBe(interim); + }); + + test("are the catalog's once it has any", async () => { + const catalog = [interim[0]]; + expect(projectScopeDeclarations(catalog, interim)).toBe(catalog); + // The mocked catalog declares the DSN lookup but not the upload + // options, which only the interim copy has. + await expect( + scoped("organizations/acme/dsn-lookup/"), + ).resolves.toBeDefined(); + await expect(scoped("organizations/acme/chunk-upload/")).rejects.toThrow( + /outside this session's scope/, + ); + }); + test.skipIf(generated.length === 0)( - "are all in the @sentry/api catalog", + "in the interim copy are all in the @sentry/api catalog", () => { - expect(generated).toEqual(expect.arrayContaining(fixture)); + expect(generated).toEqual(expect.arrayContaining(interim)); }, ); }); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index b51a9db3ac..37ebd03ec8 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -4,7 +4,7 @@ * checks by their response, or refuses. */ -import { beforeEach, describe, expect, test, vi } from "vitest"; +import { beforeEach, describe, expect, test } from "vitest"; import { SCOPE_ORG_ENV_VAR, SCOPE_PROJECT_ENV_VAR, @@ -16,14 +16,6 @@ import { withTargetScope, } from "../../src/lib/target-scope.js"; -// The scope rules Sentry declares (`x-sentry-project-scope`), until the -// installed `@sentry/api` carries them. `target-scope-catalog.test.ts` -// checks the fixture against the generated catalog once it does. -vi.mock("../../src/generated/project-scope-operations.json", async () => ({ - default: (await import("../../test/fixtures/project-scope-operations.json")) - .default, -})); - const BASE = "https://sentry.io/api/0/"; const WEB = { id: "1", slug: "web" }; const API = { id: "2", slug: "api" }; From 5709ba86c4a354f4a76f17f959f2e0cf6af4759d 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:49:17 +0000 Subject: [PATCH 3/7] fix(mcp): Adapt the catalog scope rules to main On `main`, `@sentry/api`'s operation catalog gives paths relative to `/api/0`, and the CLI prefixes `API_BASE_PATH` itself. The scope rules and the interim declarations match full request paths, so the extracted `projectScope` operations get the same prefix. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/script/lib/api-schema.ts | 5 +++-- packages/cli/src/lib/target-scope-rules.ts | 4 +++- packages/cli/test/script/generate-api-schema.test.ts | 6 +++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/cli/script/lib/api-schema.ts b/packages/cli/script/lib/api-schema.ts index d31d4f603d..93bf2eb847 100644 --- a/packages/cli/script/lib/api-schema.ts +++ b/packages/cli/script/lib/api-schema.ts @@ -50,7 +50,8 @@ function deriveResource(url: string): string { /** * The operations Sentry declares an `x-sentry-project-scope` for, other * than `path` (the scope rules match project paths themselves), for - * `target-scope-rules.ts`. `@sentry/api` carries it as `projectScope`. + * `target-scope-rules.ts`, with full request paths. `@sentry/api` carries + * it as `projectScope`. */ export function selectProjectScopeOperations( catalog: readonly { method: string; path: string; projectScope?: string }[], @@ -58,7 +59,7 @@ export function selectProjectScopeOperations( return catalog .flatMap(({ method, path, projectScope }) => projectScope && projectScope !== "path" - ? [{ method, path, scope: projectScope }] + ? [{ method, path: `${API_BASE_PATH}${path}`, scope: projectScope }] : [], ) .sort( diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index 3d46665611..82cb8c2264 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -276,7 +276,9 @@ function traceProjects(spans: unknown): (string | undefined)[] { const fields = record(span); return [ refOf(fields["project_slug"], fields["project_id"]), - ...(Array.isArray(fields["children"]) ? traceProjects(fields["children"]) : []), + ...(Array.isArray(fields["children"]) + ? traceProjects(fields["children"]) + : []), ]; }); } diff --git a/packages/cli/test/script/generate-api-schema.test.ts b/packages/cli/test/script/generate-api-schema.test.ts index 4963657a97..c9553b482d 100644 --- a/packages/cli/test/script/generate-api-schema.test.ts +++ b/packages/cli/test/script/generate-api-schema.test.ts @@ -115,17 +115,17 @@ describe("project scope extraction", () => { selectProjectScopeOperations([ { ...events, - path: "/api/0/organizations/{org}/z/", + path: "/organizations/{org}/z/", projectScope: "filter", }, { ...events, - path: "/api/0/projects/{org}/{project}/", + path: "/projects/{org}/{project}/", projectScope: "path", }, { ...events, - path: "/api/0/organizations/{org}/a/{id}/", + path: "/organizations/{org}/a/{id}/", projectScope: "response:/project/id", }, events, From 7f382fa3c7d9fb8d2e312da10a6f06773d670fe4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:27:25 +0000 Subject: [PATCH 4/7] fix(cli): Store project scope declarations as a method/path table The interim declarations as a list of objects put the @sentry/mcp-server bundle 906 bytes over its 3.75 MB budget. Keying them by method, then by path relative to /api/0, cuts 1.5 KB; the generated catalog file uses the same shape. --- packages/cli/script/generate-api-schema.ts | 8 +- packages/cli/script/lib/api-schema.ts | 23 +- .../lib/interim-project-scope-operations.json | 314 ++++-------------- packages/cli/src/lib/target-scope-rules.ts | 43 ++- .../cli/test/lib/target-scope-catalog.test.ts | 31 +- .../test/script/generate-api-schema.test.ts | 12 +- 6 files changed, 121 insertions(+), 310 deletions(-) diff --git a/packages/cli/script/generate-api-schema.ts b/packages/cli/script/generate-api-schema.ts index aafc2fdb52..3dea0ed7a4 100644 --- a/packages/cli/script/generate-api-schema.ts +++ b/packages/cli/script/generate-api-schema.ts @@ -46,13 +46,17 @@ export async function emit(): Promise { ); const projectScopeOperations = selectProjectScopeOperations(operations); + const projectScopeCount = Object.values(projectScopeOperations).reduce( + (count, paths) => count + Object.keys(paths).length, + 0, + ); await writeFile( PROJECT_SCOPE_OUTPUT_PATH, JSON.stringify(projectScopeOperations, null, 2), ); - if (projectScopeOperations.length === 0) { + if (projectScopeCount === 0) { // Scoped sessions still work, but refuse every endpoint the catalog // would have covered. logger.warn( @@ -60,7 +64,7 @@ export async function emit(): Promise { ); } else { logger.success( - `Generated ${PROJECT_SCOPE_OUTPUT_PATH} (${projectScopeOperations.length} operations)`, + `Generated ${PROJECT_SCOPE_OUTPUT_PATH} (${projectScopeCount} operations)`, ); } } diff --git a/packages/cli/script/lib/api-schema.ts b/packages/cli/script/lib/api-schema.ts index 93bf2eb847..d155bbb25e 100644 --- a/packages/cli/script/lib/api-schema.ts +++ b/packages/cli/script/lib/api-schema.ts @@ -3,7 +3,7 @@ import { API_BASE_PATH } from "@sentry/api/client"; import type { ApiOperation } from "@sentry/api/operations"; import type { ApiEndpoint } from "../../src/lib/api-schema.js"; -import type { ProjectScopeOperation } from "../../src/lib/target-scope-rules.js"; +import type { ProjectScopeTable } from "../../src/lib/target-scope-rules.js"; /** * Keep CLI grouping, output names and legacy deprecation detection local. @@ -50,20 +50,21 @@ function deriveResource(url: string): string { /** * The operations Sentry declares an `x-sentry-project-scope` for, other * than `path` (the scope rules match project paths themselves), for - * `target-scope-rules.ts`, with full request paths. `@sentry/api` carries - * it as `projectScope`. + * `target-scope-rules.ts`, sorted. `@sentry/api` carries it as + * `projectScope`. */ export function selectProjectScopeOperations( catalog: readonly { method: string; path: string; projectScope?: string }[], -): ProjectScopeOperation[] { - return catalog - .flatMap(({ method, path, projectScope }) => - projectScope && projectScope !== "path" - ? [{ method, path: `${API_BASE_PATH}${path}`, scope: projectScope }] - : [], - ) +): ProjectScopeTable { + const table: ProjectScopeTable = {}; + const declared = catalog + .filter(({ projectScope }) => projectScope && projectScope !== "path") .sort( (a, b) => - a.path.localeCompare(b.path) || a.method.localeCompare(b.method), + a.method.localeCompare(b.method) || a.path.localeCompare(b.path), ); + for (const { method, path, projectScope } of declared) { + (table[method] ??= {})[path] = projectScope ?? ""; + } + return table; } diff --git a/packages/cli/src/lib/interim-project-scope-operations.json b/packages/cli/src/lib/interim-project-scope-operations.json index 7c25893c5d..e4b93f3e87 100644 --- a/packages/cli/src/lib/interim-project-scope-operations.json +++ b/packages/cli/src/lib/interim-project-scope-operations.json @@ -1,257 +1,59 @@ -[ - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/agents/conversations/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/available-actions/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/chunk-upload/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/code-mappings/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/config/integrations/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/revisions/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/detectors/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/detectors/{detector_id}/", - "scope": "response:/projectId" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/discover/saved/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/discover/saved/{query_id}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/dsn-lookup/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/environments/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/events-dropped/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/events-timeseries/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/events/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/group-search-views/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/integrations/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/channel-validate/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/channels/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/integrations/{integration_id}/repos/", - "scope": "org-metadata" - }, - { - "method": "DELETE", - "path": "/api/0/organizations/{organization_id_or_slug}/issues/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/issues/", - "scope": "filter" - }, - { - "method": "PUT", - "path": "/api/0/organizations/{organization_id_or_slug}/issues/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/", - "scope": "response:/project/id" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/members/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/members/{member_id}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/monitors/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/monitors/{monitor_id_or_slug}/", - "scope": "response:/project/id" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/projects/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/releases/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/releases/{version}/", - "scope": "response:/projects/*/id" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/replay-count/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/replays/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/replays/{replay_id}/", - "scope": "response:/data/project_id" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/repos/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/repos/{repo_id}/commits/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/sentry-app-components/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/sentry-app-installations/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/sentry-apps/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/teams/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/trace-items/attributes/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/user-teams/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/workflows/", - "scope": "filter" - }, - { - "method": "GET", - "path": "/api/0/organizations/{organization_id_or_slug}/workflows/{workflow_id}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/members/", - "scope": "org-metadata" - }, - { - "method": "GET", - "path": "/api/0/teams/{organization_id_or_slug}/{team_id_or_slug}/projects/", - "scope": "org-metadata" +{ + "DELETE": { + "/organizations/{organization_id_or_slug}/issues/": "filter" + }, + "GET": { + "/organizations/{organization_id_or_slug}/": "org-metadata", + "/organizations/{organization_id_or_slug}/agents/conversations/": "filter", + "/organizations/{organization_id_or_slug}/available-actions/": "org-metadata", + "/organizations/{organization_id_or_slug}/chunk-upload/": "org-metadata", + "/organizations/{organization_id_or_slug}/code-mappings/": "org-metadata", + "/organizations/{organization_id_or_slug}/config/integrations/": "org-metadata", + "/organizations/{organization_id_or_slug}/dashboards/": "org-metadata", + "/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/": "org-metadata", + "/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/revisions/": "org-metadata", + "/organizations/{organization_id_or_slug}/detectors/": "filter", + "/organizations/{organization_id_or_slug}/detectors/{detector_id}/": "response:/projectId", + "/organizations/{organization_id_or_slug}/discover/saved/": "org-metadata", + "/organizations/{organization_id_or_slug}/discover/saved/{query_id}/": "org-metadata", + "/organizations/{organization_id_or_slug}/dsn-lookup/": "org-metadata", + "/organizations/{organization_id_or_slug}/environments/": "org-metadata", + "/organizations/{organization_id_or_slug}/events-dropped/": "filter", + "/organizations/{organization_id_or_slug}/events-timeseries/": "filter", + "/organizations/{organization_id_or_slug}/events/": "filter", + "/organizations/{organization_id_or_slug}/group-search-views/": "org-metadata", + "/organizations/{organization_id_or_slug}/integrations/": "org-metadata", + "/organizations/{organization_id_or_slug}/integrations/{integration_id}/": "org-metadata", + "/organizations/{organization_id_or_slug}/integrations/{integration_id}/channel-validate/": "org-metadata", + "/organizations/{organization_id_or_slug}/integrations/{integration_id}/channels/": "org-metadata", + "/organizations/{organization_id_or_slug}/integrations/{integration_id}/repos/": "org-metadata", + "/organizations/{organization_id_or_slug}/issues/": "filter", + "/organizations/{organization_id_or_slug}/issues/{issue_id}/": "response:/project/id", + "/organizations/{organization_id_or_slug}/members/": "org-metadata", + "/organizations/{organization_id_or_slug}/members/{member_id}/": "org-metadata", + "/organizations/{organization_id_or_slug}/monitors/": "filter", + "/organizations/{organization_id_or_slug}/monitors/{monitor_id_or_slug}/": "response:/project/id", + "/organizations/{organization_id_or_slug}/projects/": "org-metadata", + "/organizations/{organization_id_or_slug}/releases/": "filter", + "/organizations/{organization_id_or_slug}/releases/{version}/": "response:/projects/*/id", + "/organizations/{organization_id_or_slug}/replay-count/": "filter", + "/organizations/{organization_id_or_slug}/replays/": "filter", + "/organizations/{organization_id_or_slug}/replays/{replay_id}/": "response:/data/project_id", + "/organizations/{organization_id_or_slug}/repos/": "org-metadata", + "/organizations/{organization_id_or_slug}/repos/{repo_id}/commits/": "org-metadata", + "/organizations/{organization_id_or_slug}/sentry-app-components/": "org-metadata", + "/organizations/{organization_id_or_slug}/sentry-app-installations/": "org-metadata", + "/organizations/{organization_id_or_slug}/sentry-apps/": "org-metadata", + "/organizations/{organization_id_or_slug}/teams/": "org-metadata", + "/organizations/{organization_id_or_slug}/trace-items/attributes/": "filter", + "/organizations/{organization_id_or_slug}/user-teams/": "org-metadata", + "/organizations/{organization_id_or_slug}/workflows/": "filter", + "/organizations/{organization_id_or_slug}/workflows/{workflow_id}/": "org-metadata", + "/teams/{organization_id_or_slug}/{team_id_or_slug}/": "org-metadata", + "/teams/{organization_id_or_slug}/{team_id_or_slug}/members/": "org-metadata", + "/teams/{organization_id_or_slug}/{team_id_or_slug}/projects/": "org-metadata" + }, + "PUT": { + "/organizations/{organization_id_or_slug}/issues/": "filter" } -] +} diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index 82cb8c2264..ef61a8a790 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -92,17 +92,14 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [ ]; /** - * An operation of the `@sentry/api` catalog with an `x-sentry-project-scope` - * other than `path`, as `script/generate-api-schema.ts` extracts it. + * The operations of the `@sentry/api` catalog with an `x-sentry-project-scope` + * other than `path`, as `script/generate-api-schema.ts` extracts them: by + * uppercase method, then OpenAPI path template relative to `/api/0` + * (`/organizations/{organization_id_or_slug}/issues/`), the scope: + * `filter`, `org-metadata` or `response:`. A table rather than a + * list of objects keeps the `@sentry/mcp-server` bundle within its budget. */ -export type ProjectScopeOperation = { - /** Uppercase HTTP method */ - method: string; - /** OpenAPI path template, such as `/api/0/organizations/{org}/issues/` */ - path: string; - /** `filter`, `org-metadata` or `response:` */ - scope: string; -}; +export type ProjectScopeTable = Record>; /** `value` as an object, or `{}` when it is not one. */ export function record(value: unknown): Record { @@ -139,7 +136,7 @@ function valuesAt(body: unknown, pointer: string): unknown[] { /** The rule pattern of a catalog path: `{name}` becomes `:name`. */ function patternOf(path: string): string { - return path.replace(/^\/api\/0\//, "").replace(/\{([^}]+)\}/g, ":$1"); + return path.replace(/^\//, "").replace(/\{([^}]+)\}/g, ":$1"); } /** @@ -181,13 +178,15 @@ export function catalogRules(entries: unknown): { const orgReads: SimpleRule[] = []; const checked: ScopeRule[] = []; const lookedUpFirst: ScopeRule[] = []; - for (const entry of Array.isArray(entries) ? entries : []) { - const { method, path, scope } = record(entry); - if ( - typeof method !== "string" || - typeof path !== "string" || - typeof scope !== "string" - ) { + const declared = Object.entries(record(entries)).flatMap(([method, paths]) => + Object.entries(record(paths)).map(([path, scope]) => ({ + method, + path, + scope, + })), + ); + for (const { method, path, scope } of declared) { + if (typeof scope !== "string") { continue; } const pattern = patternOf(path); @@ -233,10 +232,10 @@ export function catalogRules(entries: unknown): { * working until the `@sentry/api` 3.x bump, which deletes it. */ export function projectScopeDeclarations( - generated: readonly unknown[], - interim: readonly unknown[], -): readonly unknown[] { - return generated.length > 0 ? generated : interim; + generated: unknown, + interim: unknown, +): unknown { + return Object.keys(record(generated)).length > 0 ? generated : interim; } const CATALOG = catalogRules( diff --git a/packages/cli/test/lib/target-scope-catalog.test.ts b/packages/cli/test/lib/target-scope-catalog.test.ts index 9c330a0d05..a4dc71e3fe 100644 --- a/packages/cli/test/lib/target-scope-catalog.test.ts +++ b/packages/cli/test/lib/target-scope-catalog.test.ts @@ -19,22 +19,27 @@ import { projectScopeDeclarations } from "../../src/lib/target-scope-rules.js"; // A catalog that declares only the DSN lookup. vi.mock("../../src/generated/project-scope-operations.json", () => ({ - default: [ - { - method: "GET", - path: "/api/0/organizations/{organization_id_or_slug}/dsn-lookup/", - scope: "org-metadata", + default: { + GET: { + "/organizations/{organization_id_or_slug}/dsn-lookup/": "org-metadata", }, - ], + }, })); const GENERATED = new URL( "../../src/generated/project-scope-operations.json", import.meta.url, ); -const generated: unknown[] = existsSync(GENERATED) +const generated: Record> = existsSync(GENERATED) ? JSON.parse(readFileSync(GENERATED, "utf8")) - : []; + : {}; + +/** Each declaration of a table, as `METHOD path scope`. */ +function declarations(table: Record>) { + return Object.entries(table).flatMap(([method, paths]) => + Object.entries(paths).map(([path, scope]) => `${method} ${path} ${scope}`), + ); +} const send = async () => Response.json({ id: "1", slug: "web" }); @@ -47,11 +52,11 @@ function scoped(path: string) { describe("the scope rules' declarations", () => { test("are the interim copy while the catalog has none", () => { - expect(projectScopeDeclarations([], interim)).toBe(interim); + expect(projectScopeDeclarations({}, interim)).toBe(interim); }); test("are the catalog's once it has any", async () => { - const catalog = [interim[0]]; + const catalog = { PUT: interim.PUT }; expect(projectScopeDeclarations(catalog, interim)).toBe(catalog); // The mocked catalog declares the DSN lookup but not the upload // options, which only the interim copy has. @@ -63,10 +68,12 @@ describe("the scope rules' declarations", () => { ); }); - test.skipIf(generated.length === 0)( + test.skipIf(Object.keys(generated).length === 0)( "in the interim copy are all in the @sentry/api catalog", () => { - expect(generated).toEqual(expect.arrayContaining(interim)); + expect(declarations(generated)).toEqual( + expect.arrayContaining(declarations(interim)), + ); }, ); }); diff --git a/packages/cli/test/script/generate-api-schema.test.ts b/packages/cli/test/script/generate-api-schema.test.ts index c9553b482d..1a9b15c91f 100644 --- a/packages/cli/test/script/generate-api-schema.test.ts +++ b/packages/cli/test/script/generate-api-schema.test.ts @@ -130,13 +130,11 @@ describe("project scope extraction", () => { }, events, ]), - ).toEqual([ - { - method: "GET", - path: "/api/0/organizations/{org}/a/{id}/", - scope: "response:/project/id", + ).toEqual({ + GET: { + "/organizations/{org}/a/{id}/": "response:/project/id", + "/organizations/{org}/z/": "filter", }, - { method: "GET", path: "/api/0/organizations/{org}/z/", scope: "filter" }, - ]); + }); }); }); From f6c310b6e52eec72124e15651363fe07f2418e54 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:49:24 +0000 Subject: [PATCH 5/7] fix(cli): Regenerate the schema when project-scope-operations.json is missing target-scope-rules.ts imports it, but ensure-generated and the schema step's outputs listed only the other two schema files, so a checkout missing just this one skipped generation and failed on the import. --- packages/cli/script/ensure-generated.mjs | 1 + packages/cli/script/generate.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/cli/script/ensure-generated.mjs b/packages/cli/script/ensure-generated.mjs index 7073403758..6e4193afe3 100644 --- a/packages/cli/script/ensure-generated.mjs +++ b/packages/cli/script/ensure-generated.mjs @@ -24,6 +24,7 @@ import { ROUTE_TREE_STUBS } from "./lib/route-tree-stub-files.mjs"; const SCHEMA_OUTPUTS = [ "src/generated/api-schema.json", "src/generated/idempotent-operations.json", + "src/generated/project-scope-operations.json", ]; /** Produced by `generate:grammar`; imported by `src/lib/arg-parsing.ts`. */ const GRAMMAR_OUTPUTS = [ diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index 74723249f8..89baf79900 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -105,6 +105,7 @@ function schemaFiles(): StepFiles { outputs: [ "src/generated/api-schema.json", "src/generated/idempotent-operations.json", + "src/generated/project-scope-operations.json", ], }; } From 20d14edc83044040d8f8ce89a72b3f4afe3d2e65 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:31:00 +0000 Subject: [PATCH 6/7] chore(deps): Bump @sentry/api to 3.5.0 3.5.0 carries Sentry's x-sentry-project-scope declarations (getsentry/sentry#132722) as each operation's projectScope. --- pnpm-lock.yaml | 16 ++++++++-------- pnpm-workspace.yaml | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ec442e5c8f..444c1de12e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -214,8 +214,8 @@ catalogs: specifier: ^1.2.3 version: 1.2.3 '@sentry/api': - specifier: 3.2.0 - version: 3.2.0 + specifier: 3.5.0 + version: 3.5.0 '@sentry/cloudflare': specifier: 11.12.0 version: 11.12.0 @@ -701,7 +701,7 @@ importers: version: 2.1.7(hono@4.13.18) '@sentry/api': specifier: 'catalog:' - version: 3.2.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.5.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/core': specifier: 'catalog:' version: 11.12.0 @@ -1066,7 +1066,7 @@ importers: version: 2.4.0 '@sentry/api': specifier: 'catalog:' - version: 3.2.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.5.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/core': specifier: 'catalog:' version: 11.12.0 @@ -1253,7 +1253,7 @@ importers: dependencies: '@sentry/api': specifier: 'catalog:' - version: 3.2.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) + version: 3.5.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7) '@sentry/http': specifier: workspace:* version: link:../http @@ -4453,8 +4453,8 @@ packages: cpu: [x64] os: [win32] - '@sentry/api@3.2.0': - resolution: {integrity: sha512-grOmtnfztzf/KDo1d+nq2NTjWznkudVTuOQk4Whbz+XYsNgl6p1pzho2DExXN+er9aQ0QO0/Cabb6KjHIPgZDA==} + '@sentry/api@3.5.0': + resolution: {integrity: sha512-1L7F7Pq97ChvfRIFLETPdGKZUVSSwfYw5wgHRoHZ5WTQiSP6s0t/rM8CMQY+DPEvHsl2GvVdOlRqkUf4pGKDlg==} engines: {node: '>=22'} peerDependencies: valibot: '*' @@ -11497,7 +11497,7 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.62.4': optional: true - '@sentry/api@3.2.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7)': + '@sentry/api@3.5.0(valibot@1.4.2(typescript@7.0.2))(zod@4.6.7)': dependencies: p-limit: 7.3.3 typescript: '@typescript/typescript6@6.0.2' diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 29ddfdf5b8..7152753c8c 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -63,7 +63,7 @@ catalog: "@modelcontextprotocol/server": 2.4.0 "@radix-ui/react-accordion": ^1.2.20 "@radix-ui/react-slot": ^1.2.3 - "@sentry/api": 3.2.0 + "@sentry/api": 3.5.0 "@sentry/cloudflare": 11.12.0 "@sentry/core": 11.12.0 "@sentry/node": 11.12.0 @@ -154,7 +154,7 @@ minimumReleaseAgeExclude: - "@sentry/search-syntax@1.0.0" - "@sentry/server-runtime-injection@11.12.0" - "@sentry/server-utils@11.12.0" - - "@sentry/api@3.2.0" + - "@sentry/api@3.5.0" - miniflare@5.20261101.0-beta - wrangler@4.156.1 - "@sentry/symbolic@14.0.0-alpha.5" From be03a600a09f76bfa3f5c9d2bfc847a7dbee518b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:55:13 +0000 Subject: [PATCH 7/7] refactor(cli): Read scope rules from the @sentry/api catalog @sentry/api 3.5.0 carries Sentry's x-sentry-project-scope declarations on each operation, and the CLI already bundles that catalog. Build the rules from it directly, and delete the interim copy of the declarations and the generated project-scope-operations.json. Sentry now derives `filter` for stats_v2, sessions and AI conversation details from their `project` parameter, so a project scope filters them instead of refusing them. --- packages/cli/script/ensure-generated.mjs | 1 - packages/cli/script/generate-api-schema.ts | 37 +-------- packages/cli/script/generate.ts | 1 - packages/cli/script/lib/api-schema.ts | 23 ------ packages/cli/src/global.d.ts | 5 -- .../lib/interim-project-scope-operations.json | 59 -------------- packages/cli/src/lib/target-scope-rules.ts | 50 ++---------- .../cli/test/lib/target-scope-catalog.test.ts | 79 ------------------- packages/cli/test/lib/target-scope.test.ts | 19 ++++- .../test/script/generate-api-schema.test.ts | 35 +------- 10 files changed, 28 insertions(+), 281 deletions(-) delete mode 100644 packages/cli/src/lib/interim-project-scope-operations.json delete mode 100644 packages/cli/test/lib/target-scope-catalog.test.ts diff --git a/packages/cli/script/ensure-generated.mjs b/packages/cli/script/ensure-generated.mjs index 6e4193afe3..7073403758 100644 --- a/packages/cli/script/ensure-generated.mjs +++ b/packages/cli/script/ensure-generated.mjs @@ -24,7 +24,6 @@ import { ROUTE_TREE_STUBS } from "./lib/route-tree-stub-files.mjs"; const SCHEMA_OUTPUTS = [ "src/generated/api-schema.json", "src/generated/idempotent-operations.json", - "src/generated/project-scope-operations.json", ]; /** Produced by `generate:grammar`; imported by `src/lib/arg-parsing.ts`. */ const GRAMMAR_OUTPUTS = [ diff --git a/packages/cli/script/generate-api-schema.ts b/packages/cli/script/generate-api-schema.ts index 3dea0ed7a4..65f0acab45 100644 --- a/packages/cli/script/generate-api-schema.ts +++ b/packages/cli/script/generate-api-schema.ts @@ -2,28 +2,20 @@ * Generate the CLI discovery index from the installed SDK's operation catalog. * * Usage: pnpm ts script/generate.ts schema - * Outputs: src/generated/api-schema.json, src/generated/idempotent-operations.json - * and src/generated/project-scope-operations.json + * Outputs: src/generated/api-schema.json and src/generated/idempotent-operations.json */ import { mkdir, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { operations } from "@sentry/api/operations"; import { selectIdempotentWrites } from "@sentry/api/client"; -import { - projectApiOperations, - selectProjectScopeOperations, -} from "./lib/api-schema.js"; +import { projectApiOperations } from "./lib/api-schema.js"; import { logger } from "../src/lib/logger.js"; const OUTPUT_PATH = "src/generated/api-schema.json"; const IDEMPOTENT_OUTPUT_PATH = "src/generated/idempotent-operations.json"; -const PROJECT_SCOPE_OUTPUT_PATH = "src/generated/project-scope-operations.json"; -/** - * Write the endpoint index, the idempotent write operations and the - * operations' project scopes. - */ +/** Write the endpoint index and the idempotent write operations. */ export async function emit(): Promise { const endpoints = projectApiOperations(operations); @@ -44,27 +36,4 @@ export async function emit(): Promise { logger.success( `Generated ${IDEMPOTENT_OUTPUT_PATH} (${idempotentOperations.length} operations)`, ); - - const projectScopeOperations = selectProjectScopeOperations(operations); - const projectScopeCount = Object.values(projectScopeOperations).reduce( - (count, paths) => count + Object.keys(paths).length, - 0, - ); - - await writeFile( - PROJECT_SCOPE_OUTPUT_PATH, - JSON.stringify(projectScopeOperations, null, 2), - ); - - if (projectScopeCount === 0) { - // Scoped sessions still work, but refuse every endpoint the catalog - // would have covered. - logger.warn( - `${PROJECT_SCOPE_OUTPUT_PATH} is empty: this @sentry/api has no projectScope`, - ); - } else { - logger.success( - `Generated ${PROJECT_SCOPE_OUTPUT_PATH} (${projectScopeCount} operations)`, - ); - } } diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index 89baf79900..74723249f8 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -105,7 +105,6 @@ function schemaFiles(): StepFiles { outputs: [ "src/generated/api-schema.json", "src/generated/idempotent-operations.json", - "src/generated/project-scope-operations.json", ], }; } diff --git a/packages/cli/script/lib/api-schema.ts b/packages/cli/script/lib/api-schema.ts index d155bbb25e..9d8f567ce9 100644 --- a/packages/cli/script/lib/api-schema.ts +++ b/packages/cli/script/lib/api-schema.ts @@ -3,7 +3,6 @@ import { API_BASE_PATH } from "@sentry/api/client"; import type { ApiOperation } from "@sentry/api/operations"; import type { ApiEndpoint } from "../../src/lib/api-schema.js"; -import type { ProjectScopeTable } from "../../src/lib/target-scope-rules.js"; /** * Keep CLI grouping, output names and legacy deprecation detection local. @@ -46,25 +45,3 @@ function deriveResource(url: string): string { .filter((s) => s.length > 0 && !s.startsWith("{")); return segments.at(-1) ?? "unknown"; } - -/** - * The operations Sentry declares an `x-sentry-project-scope` for, other - * than `path` (the scope rules match project paths themselves), for - * `target-scope-rules.ts`, sorted. `@sentry/api` carries it as - * `projectScope`. - */ -export function selectProjectScopeOperations( - catalog: readonly { method: string; path: string; projectScope?: string }[], -): ProjectScopeTable { - const table: ProjectScopeTable = {}; - const declared = catalog - .filter(({ projectScope }) => projectScope && projectScope !== "path") - .sort( - (a, b) => - a.method.localeCompare(b.method) || a.path.localeCompare(b.path), - ); - for (const { method, path, projectScope } of declared) { - (table[method] ??= {})[path] = projectScope ?? ""; - } - return table; -} diff --git a/packages/cli/src/global.d.ts b/packages/cli/src/global.d.ts index c584d8ac77..76f1ae59e3 100644 --- a/packages/cli/src/global.d.ts +++ b/packages/cli/src/global.d.ts @@ -52,8 +52,3 @@ declare module "*/generated/idempotent-operations.json" { const operations: unknown; export default operations; } - -declare module "*/generated/project-scope-operations.json" { - const operations: unknown; - export default operations; -} diff --git a/packages/cli/src/lib/interim-project-scope-operations.json b/packages/cli/src/lib/interim-project-scope-operations.json deleted file mode 100644 index e4b93f3e87..0000000000 --- a/packages/cli/src/lib/interim-project-scope-operations.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "DELETE": { - "/organizations/{organization_id_or_slug}/issues/": "filter" - }, - "GET": { - "/organizations/{organization_id_or_slug}/": "org-metadata", - "/organizations/{organization_id_or_slug}/agents/conversations/": "filter", - "/organizations/{organization_id_or_slug}/available-actions/": "org-metadata", - "/organizations/{organization_id_or_slug}/chunk-upload/": "org-metadata", - "/organizations/{organization_id_or_slug}/code-mappings/": "org-metadata", - "/organizations/{organization_id_or_slug}/config/integrations/": "org-metadata", - "/organizations/{organization_id_or_slug}/dashboards/": "org-metadata", - "/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/": "org-metadata", - "/organizations/{organization_id_or_slug}/dashboards/{dashboard_id}/revisions/": "org-metadata", - "/organizations/{organization_id_or_slug}/detectors/": "filter", - "/organizations/{organization_id_or_slug}/detectors/{detector_id}/": "response:/projectId", - "/organizations/{organization_id_or_slug}/discover/saved/": "org-metadata", - "/organizations/{organization_id_or_slug}/discover/saved/{query_id}/": "org-metadata", - "/organizations/{organization_id_or_slug}/dsn-lookup/": "org-metadata", - "/organizations/{organization_id_or_slug}/environments/": "org-metadata", - "/organizations/{organization_id_or_slug}/events-dropped/": "filter", - "/organizations/{organization_id_or_slug}/events-timeseries/": "filter", - "/organizations/{organization_id_or_slug}/events/": "filter", - "/organizations/{organization_id_or_slug}/group-search-views/": "org-metadata", - "/organizations/{organization_id_or_slug}/integrations/": "org-metadata", - "/organizations/{organization_id_or_slug}/integrations/{integration_id}/": "org-metadata", - "/organizations/{organization_id_or_slug}/integrations/{integration_id}/channel-validate/": "org-metadata", - "/organizations/{organization_id_or_slug}/integrations/{integration_id}/channels/": "org-metadata", - "/organizations/{organization_id_or_slug}/integrations/{integration_id}/repos/": "org-metadata", - "/organizations/{organization_id_or_slug}/issues/": "filter", - "/organizations/{organization_id_or_slug}/issues/{issue_id}/": "response:/project/id", - "/organizations/{organization_id_or_slug}/members/": "org-metadata", - "/organizations/{organization_id_or_slug}/members/{member_id}/": "org-metadata", - "/organizations/{organization_id_or_slug}/monitors/": "filter", - "/organizations/{organization_id_or_slug}/monitors/{monitor_id_or_slug}/": "response:/project/id", - "/organizations/{organization_id_or_slug}/projects/": "org-metadata", - "/organizations/{organization_id_or_slug}/releases/": "filter", - "/organizations/{organization_id_or_slug}/releases/{version}/": "response:/projects/*/id", - "/organizations/{organization_id_or_slug}/replay-count/": "filter", - "/organizations/{organization_id_or_slug}/replays/": "filter", - "/organizations/{organization_id_or_slug}/replays/{replay_id}/": "response:/data/project_id", - "/organizations/{organization_id_or_slug}/repos/": "org-metadata", - "/organizations/{organization_id_or_slug}/repos/{repo_id}/commits/": "org-metadata", - "/organizations/{organization_id_or_slug}/sentry-app-components/": "org-metadata", - "/organizations/{organization_id_or_slug}/sentry-app-installations/": "org-metadata", - "/organizations/{organization_id_or_slug}/sentry-apps/": "org-metadata", - "/organizations/{organization_id_or_slug}/teams/": "org-metadata", - "/organizations/{organization_id_or_slug}/trace-items/attributes/": "filter", - "/organizations/{organization_id_or_slug}/user-teams/": "org-metadata", - "/organizations/{organization_id_or_slug}/workflows/": "filter", - "/organizations/{organization_id_or_slug}/workflows/{workflow_id}/": "org-metadata", - "/teams/{organization_id_or_slug}/{team_id_or_slug}/": "org-metadata", - "/teams/{organization_id_or_slug}/{team_id_or_slug}/members/": "org-metadata", - "/teams/{organization_id_or_slug}/{team_id_or_slug}/projects/": "org-metadata" - }, - "PUT": { - "/organizations/{organization_id_or_slug}/issues/": "filter" - } -} diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index ef61a8a790..8a76703113 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -5,8 +5,7 @@ * * Most rules come from Sentry's schema: endpoints declare how they stay in * a project with the `x-sentry-project-scope` OpenAPI extension, which the - * `@sentry/api` catalog carries as `projectScope`, and - * `script/generate-api-schema.ts` extracts at build time (see + * `@sentry/api` catalog carries as `projectScope` (see * {@link catalogRules}). The rest are written here ({@link OVERRIDES}). * * In a project scope, a request no rule matches is refused. When a command @@ -14,10 +13,7 @@ * when the schema can't say it. */ -import generatedProjectScopes from "../generated/project-scope-operations.json" with { type: "json" }; -// INTERIM: delete with the `@sentry/api` 3.x bump, along with -// `projectScopeDeclarations` and the JSON file. -import interimProjectScopes from "./interim-project-scope-operations.json" with { type: "json" }; +import { type ApiOperation, operations } from "@sentry/api/operations"; /** How a matched request stays in the scope's project. */ type ScopeEnforcement = @@ -91,16 +87,6 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [ { pattern: "seer/models/" }, ]; -/** - * The operations of the `@sentry/api` catalog with an `x-sentry-project-scope` - * other than `path`, as `script/generate-api-schema.ts` extracts them: by - * uppercase method, then OpenAPI path template relative to `/api/0` - * (`/organizations/{organization_id_or_slug}/issues/`), the scope: - * `filter`, `org-metadata` or `response:`. A table rather than a - * list of objects keeps the `@sentry/mcp-server` bundle within its budget. - */ -export type ProjectScopeTable = Record>; - /** `value` as an object, or `{}` when it is not one. */ export function record(value: unknown): Record { return typeof value === "object" && value !== null @@ -171,22 +157,17 @@ const RESPONSE_PREFIX = "response:"; * IDs at the pointer of its response. A request under its path (`PUT` * of the same path, or any sub-resource) looks it up first. */ -export function catalogRules(entries: unknown): { +function catalogRules( + catalog: readonly Pick[], +): { orgReads: SimpleRule[]; rules: ScopeRule[]; } { const orgReads: SimpleRule[] = []; const checked: ScopeRule[] = []; const lookedUpFirst: ScopeRule[] = []; - const declared = Object.entries(record(entries)).flatMap(([method, paths]) => - Object.entries(record(paths)).map(([path, scope]) => ({ - method, - path, - scope, - })), - ); - for (const { method, path, scope } of declared) { - if (typeof scope !== "string") { + for (const { method, path, projectScope: scope } of catalog) { + if (!scope) { continue; } const pattern = patternOf(path); @@ -225,22 +206,7 @@ export function catalogRules(entries: unknown): { return { orgReads, rules: [...checked, ...lookedUpFirst] }; } -/** - * The `x-sentry-project-scope` declarations to build rules from: the - * installed `@sentry/api` catalog's, or, while it has none, an interim copy - * of what getsentry/sentry#132722 declares. The copy keeps project scopes - * working until the `@sentry/api` 3.x bump, which deletes it. - */ -export function projectScopeDeclarations( - generated: unknown, - interim: unknown, -): unknown { - return Object.keys(record(generated)).length > 0 ? generated : interim; -} - -const CATALOG = catalogRules( - projectScopeDeclarations(generatedProjectScopes, interimProjectScopes), -); +const CATALOG = catalogRules(operations); /** * Read-only organization metadata a project scope may read: what Sentry diff --git a/packages/cli/test/lib/target-scope-catalog.test.ts b/packages/cli/test/lib/target-scope-catalog.test.ts deleted file mode 100644 index a4dc71e3fe..0000000000 --- a/packages/cli/test/lib/target-scope-catalog.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Where the scope rules come from. Until the installed `@sentry/api` - * carries `x-sentry-project-scope`, they come from an interim copy of what - * Sentry declares (`src/lib/interim-project-scope-operations.json`). Once - * the catalog has declarations, the catalog wins, and every interim entry - * must be in it, or deleting the copy with the bump would drop a rule. - */ - -import { existsSync, readFileSync } from "node:fs"; -import { describe, expect, test, vi } from "vitest"; -import { - SCOPE_ORG_ENV_VAR, - SCOPE_PROJECT_ENV_VAR, - withEnv, -} from "../../src/lib/env.js"; -import interim from "../../src/lib/interim-project-scope-operations.json"; -import { scopeRequest } from "../../src/lib/target-scope.js"; -import { projectScopeDeclarations } from "../../src/lib/target-scope-rules.js"; - -// A catalog that declares only the DSN lookup. -vi.mock("../../src/generated/project-scope-operations.json", () => ({ - default: { - GET: { - "/organizations/{organization_id_or_slug}/dsn-lookup/": "org-metadata", - }, - }, -})); - -const GENERATED = new URL( - "../../src/generated/project-scope-operations.json", - import.meta.url, -); -const generated: Record> = existsSync(GENERATED) - ? JSON.parse(readFileSync(GENERATED, "utf8")) - : {}; - -/** Each declaration of a table, as `METHOD path scope`. */ -function declarations(table: Record>) { - return Object.entries(table).flatMap(([method, paths]) => - Object.entries(paths).map(([path, scope]) => `${method} ${path} ${scope}`), - ); -} - -const send = async () => Response.json({ id: "1", slug: "web" }); - -function scoped(path: string) { - return withEnv( - { [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" }, - () => scopeRequest(`https://sentry.io/api/0/${path}`, undefined, send), - ); -} - -describe("the scope rules' declarations", () => { - test("are the interim copy while the catalog has none", () => { - expect(projectScopeDeclarations({}, interim)).toBe(interim); - }); - - test("are the catalog's once it has any", async () => { - const catalog = { PUT: interim.PUT }; - expect(projectScopeDeclarations(catalog, interim)).toBe(catalog); - // The mocked catalog declares the DSN lookup but not the upload - // options, which only the interim copy has. - await expect( - scoped("organizations/acme/dsn-lookup/"), - ).resolves.toBeDefined(); - await expect(scoped("organizations/acme/chunk-upload/")).rejects.toThrow( - /outside this session's scope/, - ); - }); - - test.skipIf(Object.keys(generated).length === 0)( - "in the interim copy are all in the @sentry/api catalog", - () => { - expect(declarations(generated)).toEqual( - expect.arrayContaining(declarations(interim)), - ); - }, - ); -}); diff --git a/packages/cli/test/lib/target-scope.test.ts b/packages/cli/test/lib/target-scope.test.ts index 37ebd03ec8..013e85d85a 100644 --- a/packages/cli/test/lib/target-scope.test.ts +++ b/packages/cli/test/lib/target-scope.test.ts @@ -173,6 +173,22 @@ describe("a project scope", () => { "organizations/acme/issues/?projectSlug=web", "organizations/acme/issues/?projectSlug=web&project=1", ], + // Sentry derives `filter` for these from their `project` parameter. + [ + "GET", + "organizations/acme/stats_v2/", + "organizations/acme/stats_v2/?project=1", + ], + [ + "GET", + "organizations/acme/sessions/", + "organizations/acme/sessions/?project=1", + ], + [ + "GET", + "organizations/acme/agents/conversations/9/", + "organizations/acme/agents/conversations/9/?project=1", + ], ])("filters %s %s to its project", async (method, path, filtered) => { expect(await sentAs(WEB_SCOPE, method, path)).toBe(filtered); }); @@ -241,10 +257,7 @@ describe("a project scope", () => { ["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"], ["PUT", "organizations/acme/releases/1.0/", "a change to a release"], ["GET", "organizations/acme/brand-new-endpoint/", "an unknown endpoint"], diff --git a/packages/cli/test/script/generate-api-schema.test.ts b/packages/cli/test/script/generate-api-schema.test.ts index 1a9b15c91f..db2078f8fd 100644 --- a/packages/cli/test/script/generate-api-schema.test.ts +++ b/packages/cli/test/script/generate-api-schema.test.ts @@ -1,9 +1,6 @@ import { operations, type ApiOperation } from "@sentry/api/operations"; import { describe, expect, test } from "vitest"; -import { - projectApiOperations, - selectProjectScopeOperations, -} from "../../script/lib/api-schema.js"; +import { projectApiOperations } from "../../script/lib/api-schema.js"; import { searchEndpoints } from "../../src/lib/api-schema.js"; const events = { @@ -108,33 +105,3 @@ describe("SDK catalog projection", () => { } }); }); - -describe("project scope extraction", () => { - test("keeps declared scopes other than path, sorted", () => { - expect( - selectProjectScopeOperations([ - { - ...events, - path: "/organizations/{org}/z/", - projectScope: "filter", - }, - { - ...events, - path: "/projects/{org}/{project}/", - projectScope: "path", - }, - { - ...events, - path: "/organizations/{org}/a/{id}/", - projectScope: "response:/project/id", - }, - events, - ]), - ).toEqual({ - GET: { - "/organizations/{org}/a/{id}/": "response:/project/id", - "/organizations/{org}/z/": "filter", - }, - }); - }); -});