diff --git a/packages/cli/src/lib/target-scope-rules.ts b/packages/cli/src/lib/target-scope-rules.ts index e3cc1b029..8a7670311 100644 --- a/packages/cli/src/lib/target-scope-rules.ts +++ b/packages/cli/src/lib/target-scope-rules.ts @@ -3,10 +3,18 @@ * 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` (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 { type ApiOperation, operations } from "@sentry/api/operations"; + /** How a matched request stays in the scope's project. */ type ScopeEnforcement = /** The path names the scope's project, as `:project`. */ @@ -28,7 +36,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 @@ -77,43 +87,6 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [ { pattern: "seer/models/" }, ]; -/** - * Read-only organization metadata a project scope may read: settings, - * members, integrations and saved views, with no project's issues, events - * or other data in them. - */ -export const ORG_READS: readonly SimpleRule[] = [ - { pattern: "organizations/:org/" }, - { pattern: "organizations/:org/projects/" }, - { pattern: "organizations/:org/teams/" }, - { pattern: "organizations/:org/user-teams/" }, - { pattern: "organizations/:org/members/" }, - { pattern: "organizations/:org/members/:member/" }, - { pattern: "organizations/:org/environments/" }, - // The project a DSN belongs to: its ID, slug and name. - { pattern: "organizations/:org/dsn-lookup/" }, - { pattern: "organizations/:org/chunk-upload/" }, - { pattern: "organizations/:org/integrations/" }, - { pattern: "organizations/:org/integrations/:integration/**" }, - { pattern: "organizations/:org/config/integrations/" }, - { pattern: "organizations/:org/available-actions/" }, - { pattern: "organizations/:org/sentry-apps/" }, - { pattern: "organizations/:org/sentry-app-installations/" }, - { pattern: "organizations/:org/sentry-app-components/" }, - { pattern: "organizations/:org/repos/" }, - { pattern: "organizations/:org/repos/:repo/commits/" }, - { pattern: "organizations/:org/code-mappings/" }, - { pattern: "organizations/:org/dashboards/" }, - { pattern: "organizations/:org/dashboards/:dashboard/" }, - { pattern: "organizations/:org/dashboards/:dashboard/revisions/" }, - { pattern: "organizations/:org/discover/saved/" }, - { pattern: "organizations/:org/discover/saved/:query/" }, - { pattern: "organizations/:org/group-search-views/" }, - { pattern: "organizations/:org/workflows/:workflow/" }, - { pattern: "teams/:org/:team/**" }, - { pattern: "customers/:org/" }, -]; - /** `value` as an object, or `{}` when it is not one. */ export function record(value: unknown): Record { return typeof value === "object" && value !== null @@ -127,6 +100,124 @@ 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(/^\//, "").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. + */ +function catalogRules( + catalog: readonly Pick[], +): { + orgReads: SimpleRule[]; + rules: ScopeRule[]; +} { + const orgReads: SimpleRule[] = []; + const checked: ScopeRule[] = []; + const lookedUpFirst: ScopeRule[] = []; + for (const { method, path, projectScope: scope } of catalog) { + if (!scope) { + 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(operations); + +/** + * 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 +226,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"])]; @@ -157,17 +248,7 @@ function traceProjects(spans: unknown): (string | undefined)[] { }); } -/** `organizations////`, from a rule's params. */ -function orgPath(kind: string, param: string) { - return (params: Record): string => - `organizations/${encodeURIComponent(params["org"] ?? "")}/${kind}/${encodeURIComponent(params[param] ?? "")}/`; -} - -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 +268,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 +331,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/lib/sdk-limit-to-target.test.ts b/packages/cli/test/lib/sdk-limit-to-target.test.ts index cc6b3f4f7..fa74a2a07 100644 --- a/packages/cli/test/lib/sdk-limit-to-target.test.ts +++ b/packages/cli/test/lib/sdk-limit-to-target.test.ts @@ -24,6 +24,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.test.ts b/packages/cli/test/lib/target-scope.test.ts index 96d6731b2..013e85d85 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,11 +257,9 @@ 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"], ["GET", "sentry-app-installations/x/external-requests/", "an app install"], ])("refuses %s %s (%s)", async (method, path) => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ec442e5c8..444c1de12 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 29ddfdf5b..7152753c8 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"