diff --git a/static/packages/api/README.md b/static/packages/api/README.md index 061c4d61550c..9c7768a3e095 100644 --- a/static/packages/api/README.md +++ b/static/packages/api/README.md @@ -148,7 +148,7 @@ const logOperations = operations.filter(operation => console.log(logOperations.map(({ functionName, method, path }) => ({ functionName, method, path }))); ``` -Each `ApiOperation` records the actual exported `functionName`, original OpenAPI `operationId`, method, path (relative to `API_BASE_PATH`), summary, description, tags, path parameter names, query metadata, explicit deprecation flag, `experimental` flag, `idempotent` flag, and `routing` declaration. `ApiQueryParameter` includes the name, required flag, description, type, and declared enum values (item values for arrays). Operation parameters override inherited path parameters. +Each `ApiOperation` records the actual exported `functionName`, original OpenAPI `operationId`, method, path (relative to `API_BASE_PATH`), summary, description, tags, path parameter names, query metadata, explicit deprecation flag, `experimental` flag, `idempotent` flag, `routing` declaration, and `projectScope` declaration when Sentry has one. `ApiQueryParameter` includes the name, required flag, description, type, and declared enum values (item values for arrays). Operation parameters override inherited path parameters. `experimental` is `true` when Sentry marks the operation with the `x-sentry-experimental` OpenAPI extension, which it sets for endpoints under active development that may change. Their SDK docs also start with an **Experimental:** note. To find or reject experimental operations, for example in a lint rule or build check: @@ -185,6 +185,22 @@ The path may include `API_BASE_PATH`, an origin or a query string, and a missing `idempotent` tells retrying clients whether resending an identical request after a timeout or 5xx response is safe. It is always `true` for `GET`, `HEAD`, `OPTIONS`, and `TRACE`. Other methods are `true` only when Sentry marks the operation with the `x-sentry-idempotent` OpenAPI extension; `false` means not known to be idempotent, not known to be unsafe. +`projectScope` copies Sentry's `x-sentry-project-scope` declaration, which says how a request names the projects whose data it returns or changes. Clients that limit a caller to some projects read it instead of keeping their own endpoint list. `ApiProjectScope` is one of: + +- `path`: the path names the project. +- `filter`: an organization endpoint that takes the `project` query parameter (numeric project IDs) and returns or changes only those projects' data. +- `org-metadata`: a read-only organization endpoint whose response holds no project's telemetry, such as settings, members, or integrations. Only on `GET`. +- `response:`: a `GET` that looks something up by ID alone. The numeric ID of the project it belongs to is at `` in the response body. `` is an RFC 6901 JSON pointer in which a `*` segment matches every element of an array, such as `response:/projects/*/id`. + +An operation without a declaration has no `projectScope`, which means it is not known to respect a project limit. The build fails on any other value, and on `org-metadata` or `response:` for a method other than `GET`: + +```ts +import { matchOperation, type ApiProjectScope } from "@sentry/api/operations"; + +const scope: ApiProjectScope | undefined = matchOperation("GET", "/api/0/projects/acme/backend/")?.operation.projectScope; +scope; // "path" +``` + The catalog is generated from the same schema and SDK output as each release. Consumers own search, grouping, ranking, and command aliases; the catalog does not fetch a live schema or infer undocumented API behavior. ### API reference data diff --git a/static/packages/api/lib/operation-catalog.mjs b/static/packages/api/lib/operation-catalog.mjs index 750c95afa18e..466b58a5f103 100644 --- a/static/packages/api/lib/operation-catalog.mjs +++ b/static/packages/api/lib/operation-catalog.mjs @@ -23,6 +23,34 @@ function routing(key, operation, pathParameters) { return { silo, organizationParameter }; } +const PROJECT_SCOPES = new Set(["path", "filter", "org-metadata"]); +const RESPONSE_SCOPE = "response:"; +// RFC 6901: "/"-separated segments, with "~" only in the escapes "~0" and "~1". A "*" segment needs no special case. +const JSON_POINTER = /^(\/([^/~]|~[01])*)+$/; + +/** + * Copy Sentry's `x-sentry-project-scope` declaration, rejecting values that Sentry's + * schema build would also reject. An operation without one gets no `projectScope`. + */ +function projectScope(key, method, operation) { + const declared = operation["x-sentry-project-scope"]; + if (declared === undefined) return {}; + const invalid = reason => new Error(`${key} declares an unsupported x-sentry-project-scope ${JSON.stringify(declared)}: ${reason}`); + if (typeof declared !== "string") throw invalid("the value must be a string"); + if (declared.startsWith(RESPONSE_SCOPE)) { + if (method !== "get") throw invalid("response: is only for GET"); + if (!JSON_POINTER.test(declared.slice(RESPONSE_SCOPE.length))) { + throw invalid("response: must be followed by a JSON pointer such as /project/id"); + } + return { projectScope: declared }; + } + if (!PROJECT_SCOPES.has(declared)) { + throw invalid('the value must be "path", "filter", "org-metadata", or "response:"'); + } + if (declared === "org-metadata" && method !== "get") throw invalid("org-metadata is only for GET"); + return { projectScope: declared }; +} + /** Operation-level parameters replace path-level parameters with the same name/in. */ function queryParameters(pathItem, operation) { const parameters = new Map(); @@ -79,6 +107,7 @@ export function extractOperations(spec, sdkSource) { // Other methods count only when Sentry marks them; PUT/DELETE handlers are not all idempotent. idempotent: SAFE_METHODS.has(method) || operation["x-sentry-idempotent"] === true, routing: routing(key, operation, pathParameters), + ...projectScope(key, method, operation), }); } } diff --git a/static/packages/api/lib/operation-types.ts b/static/packages/api/lib/operation-types.ts index 0ba090192363..6bde7aa05e7e 100644 --- a/static/packages/api/lib/operation-types.ts +++ b/static/packages/api/lib/operation-types.ts @@ -24,6 +24,21 @@ export type ApiOperationRouting = { readonly organizationParameter?: string; }; +/** + * How an operation's request names the projects whose data it returns or changes, from + * Sentry's `x-sentry-project-scope` OpenAPI extension: + * - `path`: the path names the project. + * - `filter`: an organization endpoint that takes the `project` query parameter (numeric + * project IDs) and returns or changes only those projects' data. + * - `org-metadata`: a read-only organization endpoint whose response holds no project's + * telemetry, such as settings, members, or integrations. + * - `response:`: a GET that looks something up by ID alone. The numeric ID of + * the project it belongs to is at `` in the response body, such as + * `response:/project/id`. `` is an RFC 6901 JSON pointer in which a `*` + * segment matches every element of an array. + */ +export type ApiProjectScope = "path" | "filter" | "org-metadata" | `response:${string}`; + /** An operation shipped by this SDK version, without consumer-specific policy. */ export type ApiOperation = { /** Actual exported SDK function name, after name normalization. */ @@ -59,4 +74,9 @@ export type ApiOperation = { readonly idempotent: boolean; /** Where Sentry declares the operation available. */ readonly routing: ApiOperationRouting; + /** + * How the request names the projects it reads or changes. Absent when Sentry has no + * declaration, which means the operation is not known to respect a project limit. + */ + readonly projectScope?: ApiProjectScope; }; diff --git a/static/packages/api/scripts/generate-operations.mjs b/static/packages/api/scripts/generate-operations.mjs index cfe6f79b03c4..aed1a3e68dda 100644 --- a/static/packages/api/scripts/generate-operations.mjs +++ b/static/packages/api/scripts/generate-operations.mjs @@ -66,7 +66,7 @@ export function emit({ sourceSpec }) { ])), match, ), - f.createExportDeclaration(undefined, true, named(["ApiOperation", "ApiOperationRouting", "ApiQueryParameter"]), types), + f.createExportDeclaration(undefined, true, named(["ApiOperation", "ApiOperationRouting", "ApiProjectScope", "ApiQueryParameter"]), types), f.createExportDeclaration(undefined, false, named(["API_BASE_PATH"]), f.createStringLiteral("./api-base-path.gen.ts")), f.createExportDeclaration(undefined, false, named(["createOperationMatcher"]), match), f.createExportDeclaration(undefined, true, named(["ApiOperationMatch", "ApiOperationMatcher", "ApiOperationTemplate"]), match), diff --git a/static/packages/api/test/operation-types.ts b/static/packages/api/test/operation-types.ts index 5c65c62970a2..b2aeaa47c798 100644 --- a/static/packages/api/test/operation-types.ts +++ b/static/packages/api/test/operation-types.ts @@ -1,5 +1,5 @@ /** Public discovery types are readonly, including nested parameter metadata. */ -import { operations, type ApiOperation, type ApiQueryParameter } from "@sentry/api/operations"; +import { operations, type ApiOperation, type ApiProjectScope, type ApiQueryParameter } from "@sentry/api/operations"; const operation: ApiOperation | undefined = operations[0]; const parameter: ApiQueryParameter | undefined = operation?.queryParameters[0]; @@ -15,4 +15,9 @@ if (operation) { } // @ts-expect-error Enum values must not be changed by consumers. parameter?.enum?.push("added"); +const scope: ApiProjectScope | undefined = operation?.projectScope; +// @ts-expect-error Only Sentry's declared project scopes are values. +const unknownScope: ApiProjectScope = "project"; void value; +void scope; +void unknownScope; diff --git a/static/packages/api/test/operations.test.ts b/static/packages/api/test/operations.test.ts index 899b8ba315e2..7ed7635b9cd3 100644 --- a/static/packages/api/test/operations.test.ts +++ b/static/packages/api/test/operations.test.ts @@ -162,6 +162,49 @@ describe("operation discovery", () => { .toThrow("organizationParameter organization_slug, which is not in its path"); }); + test("copies Sentry's project scope declarations and rejects malformed ones", async () => { + const response = { responses: { "200": { description: "OK" } } }; + const scoped = (operationId: string, scope: unknown) => ({ operationId, ...response, "x-sentry-project-scope": scope }); + const spec = (scope: unknown, method = "get") => ({ + ...fixture(), + paths: { + ...fixture().paths, + "/project/": { get: scoped("retrieveProject", "path") }, + "/issues/": { put: scoped("updateIssues", "filter") }, + "/members/": { get: scoped("listMembers", "org-metadata") }, + "/short-ids/": { get: scoped("resolveShortId", "response:/projects/*/id") }, + "/escaped/": { get: scoped("readEscaped", "response:/a~0b/~1c") }, + "/thing/": { [method]: scoped("thing", scope) }, + }, + }); + const get = await generate(spec("response:/project/id")); + expect(Object.fromEntries(get.catalog.map(operation => [operation.functionName, operation.projectScope]))).toEqual({ + listMembers: "org-metadata", + listOrganizationEvents: undefined, + readEscaped: "response:/a~0b/~1c", + resolveShortId: "response:/projects/*/id", + retrieveProject: "path", + thing: "response:/project/id", + updateIssues: "filter", + }); + expect(get.catalog.find(operation => operation.path === eventsPath)).not.toHaveProperty("projectScope"); + for (const pointer of ["", "project/id", "/project/~2", "/project~"]) { + expect(() => extractOperations(spec(`response:${pointer}`), get.source)).toThrow( + `GET /thing/ declares an unsupported x-sentry-project-scope "response:${pointer}": response: must be followed by a JSON pointer such as /project/id`, + ); + } + + const put = await generate(spec("filter", "put")); + expect(put.catalog.find(operation => operation.path === "/thing/")?.projectScope).toBe("filter"); + const error = "PUT /thing/ declares an unsupported x-sentry-project-scope"; + expect(() => extractOperations(spec("org-metadata", "put"), put.source)).toThrow(`${error} "org-metadata": org-metadata is only for GET`); + expect(() => extractOperations(spec("response:/project/id", "put"), put.source)) + .toThrow(`${error} "response:/project/id": response: is only for GET`); + expect(() => extractOperations(spec("project", "put"), put.source)) + .toThrow(`${error} "project": the value must be "path", "filter", "org-metadata", or "response:"`); + expect(() => extractOperations(spec(["filter"], "put"), put.source)).toThrow(`${error} ["filter"]: the value must be a string`); + }); + test("ships the released routing declarations", () => { expect(operations.find(operation => operation.functionName === "listOrganizationProjects")?.routing) .toEqual({ silo: "cell", organizationParameter: "organization_id_or_slug" });