Repository navigation
fix(mcp): Enforce the session scope in the API transport - #2549
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
1 Skipped Deployment
|
BYK
left a comment
There was a problem hiding this comment.
Should fail-closed apply only when sentry mcp --commands sets the scope, with plain SDK callers keeping only the ID checks?
Yeah I think allowing SDK callers to do more stuff is fine. But in general I think we shouldn't restrict too much like DSN look ups etc. Some safe read-only org-level actions should be allowed for smooth operation. Again, DSN lookups is the first that comes to my mind.
a16f2e4 to
7659adb
Compare
7659adb to
a386c10
Compare
The org/project limit of `limitToTarget` was checked call by call: each lookup that an ID alone names (issues, short IDs, events, traces, replays, Feedback, `@latest`) had its own assert, and each list had to remember to pass the scope's project. Anything new, or anything missed (`trace logs <trace-id>`, `sentry api organizations/<other>/...`, the preprod downloads that send the token around the transport), was not checked at all. The limit is now enforced once, where every request the CLI sends with a credential goes: `scopeRequest` in `target-scope.ts`, called from the authenticated fetch in `sentry-client.ts` (before the response cache, so cached responses are checked too) and, through `withTargetScope`, from the two fetches that send around it (share links, preprod downloads). A scoped invocation fails closed: - Paths must name the scope's organization and, in a project scope, its project. - In a project scope, organization endpoints that return every project's data are filtered to the scope's project (a missing `project` or `-1` gets the scope's ID; another project is refused). - Lookups by an ID alone are checked by their response's project; a request that reads or changes what an ID names (`PUT issues/<id>/`, `issues/<id>/events/`, `trace-meta`, `trace-logs`) looks it up first. - Any other request, such as one to an endpoint added later, is refused before it is sent. The rules are in `target-scope-rules.ts`. The per-command asserts and project narrowing from the two previous commits are removed; only the `event view` fallback keeps rethrowing a `ResolutionError`, so a refusal isn't turned into an org-wide search. `target-scope-coverage.test.ts` fails when a source file fetches around the transport without the scope. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
A project scope refused organization reads that carry no project's data, so DSN detection (the org list, then `dsn-lookup/`) and similar lookups failed in scoped sessions. These GETs are now allowed in every scope: - `organizations/`, `users/:user/` and `seer/models/`; - under `organizations/:org/`: `dsn-lookup/`, `chunk-upload/`, `members/:member/`, `user-teams/`, `integrations/:id/**`, `config/integrations/`, `available-actions/`, `sentry-apps/`, `sentry-app-installations/`, `repos/:repo/commits/`, `code-mappings/`, `discover/saved/[:query/]` and `group-search-views/`; - `teams/:org/:team/**` and `customers/:org/`. Requests to other organizations are still refused, and so is any endpoint no rule covers. Project keys, org auth tokens, SCIM, stats and sessions, preprod and agent conversations stay refused. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
Adds an `x-sentry-project-scope` operation extension to the OpenAPI schema. It works like `x-sentry-idempotent`: the schema build stamps it on each operation before issue alias canonicalization. The Sentry CLI and MCP server limit a caller to an org or project at the HTTP transport, using a hand-written table of endpoint rules (getsentry/toolkit#2549). With this extension they can read the same facts from the schema through `@sentry/api/operations`. Refs getsentry/toolkit#2237. ## What the value means The value is a string on an operation (path + method). It says how the request names the projects whose data the operation returns or changes: | Value | Meaning | | --- | --- | | `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 has no project's issues, events, replays, or other telemetry, such as settings, members, integrations, and saved views. | | `response:<pointer>` | A `GET` lookup by ID alone. The numeric project ID of the object it found is at `<pointer>` in the response body. `<pointer>` is an RFC 6901 JSON pointer, plus a `*` segment that matches every element of an array, e.g. `response:/projects/*/id`. | An operation with no value isn't known to respect a project limit. ## Where values come from The build derives two values from the schema: - `path` on every operation whose path contains `{project_id_or_slug}`. - `filter` on every other operation that documents the `project` query parameter (`OrganizationParams.PROJECT` in `@extend_schema`). Endpoints declare the rest per method on the class, and a declared value wins over a derived `filter`: ```python project_scope = {"GET": "response:/projects/*/id"} ``` `Endpoint.project_scope: dict[HTTP_METHOD_NAME, str]` defaults to `{}`. The build fails when: - the value isn't `filter`, `org-metadata`, or `response:<pointer>` (`path` can't be declared), - `response:` or `org-metadata` is on a method other than `GET`, - the text after `response:` isn't a JSON pointer, - the pointer doesn't reach a string or integer field in the operation's 200 response schema (following `$ref`, `allOf`, `oneOf`, `anyOf`, and array items), - a method isn't in `publish_status`, - the declaration is on a path that already contains `{project_id_or_slug}`. Declarations are collected for unpublished endpoints too and reset on every build. Subclasses inherit them, like `idempotent_methods`. The SCIM team details endpoint sets `project_scope = {}`, so it doesn't inherit `org-metadata` from team details. The rules are documented in `src/sentry/apidocs/README.md`. ## Values in the schema Paths are relative to `/organizations/{organization_id_or_slug}/` unless shown otherwise. - `path` (derived): 91 operations. - `filter` (derived): 36 operations. These include `issues/` (GET, PUT, DELETE), GET on `events/`, `events-timeseries/`, `events-dropped/`, `trace-items/attributes/`, `replays/`, `replay-count/`, `monitors/`, `detectors/`, `workflows/`, `releases/`, `agents/conversations/`, `issues-stats/`, `sessions/`, `tags/`, `stats_v2/`, and `profiling/*`, plus PUT/DELETE on `detectors/` and `workflows/`. - `response:` (declared, GET): - `issues/{issue_id}/` → `response:/project/id` - `replays/{replay_id}/` → `response:/data/project_id` - `monitors/{monitor_id_or_slug}/` → `response:/project/id` - `detectors/{detector_id}/` → `response:/projectId` (`null` for the all-projects detector) - `releases/{version}/` → `response:/projects/*/id` - `org-metadata` (declared, GET): the organization itself, `projects/`, `teams/`, `user-teams/`, `members/`, `members/{member_id}/`, `environments/`, `dsn-lookup/`, `chunk-upload/`, `integrations/`, `integrations/{integration_id}/` (plus `channels/`, `repos/`, and `channel-validate/`), `config/integrations/`, `available-actions/`, `sentry-apps/`, `sentry-app-installations/`, `sentry-app-components/`, `repos/`, `repos/{repo_id}/commits/`, `code-mappings/`, `dashboards/`, `dashboards/{dashboard_id}/`, `dashboards/{dashboard_id}/revisions/`, `discover/saved/`, `discover/saved/{query_id}/`, `group-search-views/`, and `workflows/{workflow_id}/`. Also `/teams/{organization_id_or_slug}/{team_id_or_slug}/`, `.../members/`, and `.../projects/`. ## Follow-ups A getsentry/sentry-api-schema PR will carry the extension into the published schema and `@sentry/api/operations`. A getsentry/toolkit PR will then replace the hand-written scope table with these values. Both will link back here. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A32ccc4a8b8fcfb339491217797caf8ab --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A32ccc4a8b8fcfb339491217797caf8ab) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A32ccc4a8b8fcfb339491217797caf8ab/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <126780+BYK@users.noreply.github.com>
…verage test `sentry wizard`, merged from main, fetches Sentry's public release registry and writes example code with fetch() calls into the user's project. Neither sends the CLI's credential to the Sentry API.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 93bf8f3. Configure here.
getSharedIssue sends the share request without the bearer token, and the target scope's project lookup went out the same way. When the session names its project by ID and the share payload by slug (or the reverse), that lookup got 401 and an in-scope share was refused. withTargetScope now takes an optional lookup sender, and getSharedIssue passes the authenticated transport, which still refuses an untrusted host.
trace-meta and trace-logs look the trace up first, over the request's period (14d by default). A trace with in-scope spans only past that window came back empty and was refused, while trace view, which retries 90d, showed it. A relative period now retries the lookup at 90d before refusing.
…getsentry#2552) Refs getsentry#2237. Stacked on getsentry#2549. This replaces most of the hand-written endpoint table behind `limitToTarget` with rules Sentry declares in its own schema. It bumps `@sentry/api` to 3.5.0, the first release that carries Sentry's `x-sentry-project-scope` extension (getsentry/sentry#132722) as `ApiOperation.projectScope`. **What changes** `target-scope-rules.ts` reads `projectScope` from `@sentry/api` 3.5.0's `operations` catalog, which the CLI already bundles, so no generated copy of the declarations is needed. It builds a rule for each operation whose scope isn't `path`: - `org-metadata`: an org read that the project scope may send. - `filter`: an org endpoint that gets filtered to the scope's project. - `response:<pointer>`: a lookup by an ID alone. The response is checked against the numeric project IDs at that JSON pointer, where `*` matches each array element. A write to the same path, or any request below it, looks the resource up first. **What stays hand-written**, because the schema can't say it: - project paths and account reads; - getsentry's `customers/:org/`; - endpoints the schema doesn't publish: short IDs, event IDs, share links, `trace/` and `trace-meta/`; - `trace-logs`, which ignores `project`, so it looks the trace up first; - release writes, which stay refused because a release spans projects. **Behavior changes** - Issue, replay, monitor, detector and release lookups now compare numeric project IDs instead of slugs, since slugs are only unique within an org. The scope project's ID is looked up once per process. - Sentry now derives `filter` from an endpoint's `project` parameter, so a project scope sends these with `?project=<id>` instead of refusing them: - `organizations/:org/stats_v2/` - `organizations/:org/sessions/` - `organizations/:org/agents/conversations/{conversation_id}/` <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A30387dbb15a73c1ea95ce25e5f09b56a --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A30387dbb15a73c1ea95ce25e5f09b56a) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A30387dbb15a73c1ea95ce25e5f09b56a/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <126780+BYK@users.noreply.github.com>

Refs #2237. Stacked on #2541 (→ #2527 →
main).#2527 and #2541 checked the
limitToTargetscope call by call, one assert per lookup and one project filter per list caller. Anything they missed wasn't checked at all, for example:trace logs <trace-id>: Sentry'strace-logsandtrace-metaignore theprojectfilter.sentry api organizations/<other>/....This PR moves the check into the transport, so a new code path can't skip it.
What already existed. Nothing enforced the scope centrally.
assertCredentialScopeinprepareHeaderschecks only the host, and it runs after the transport's cache lookup.sdk-invoke.tsonly turnslimitToTargetinto theSENTRY_CLI_SCOPE_*env vars.The new check reads those env vars (
getTargetScope()) and runs in the same authenticated fetch, before the cache.How it works
scopeRequest(lib/target-scope.ts) runs increateAuthenticatedFetchbeforetransport.request. That covers SDK calls,apiRequestToRegion, rawsentry apiand cached responses.withTargetScope()applies the same check to the share-link fetch and the preprod downloads. With no scope, nothing changes.A scoped invocation fails closed: a request that matches no rule in
lib/target-scope-rules.tsis refused before it is sent.organizations|projects|teams|customers/<org>/…must name the scope's org. In a project scope,projects/<org>/<project>/…must also name its project, by slug or ID.issues/(including bulk PUT/DELETE),events/,events-timeseries/,events-dropped/,trace-items/attributes/,replays/,replay-count/,monitors/,detectors/,workflows/,releases/andagents/conversations/get filtered to the scope's project. A missingprojector-1is replaced with the scope project's ID, looked up once per process. Any other project is refused.issues/<id>/,shortids/<id>/,shared/issues/<id>/,eventids/<id>/,replays/<id>/,monitors/<id>/,detectors/<id>/,releases/<version>/andtrace/<id>/. A trace with one span in the project counts as in scope, as in fix(mcp): Check events, traces and replays an ID alone names against the session's project #2541.PUT issues/<id>/,issues/<id>/events/…, monitor and detector writes, release sub-resource reads,trace-meta/<id>/andtrace-logs/?traceId=.GET /api/0/,auth/andusers/me/.projects/,teams/,members/,environments/,integrations/,repos/,sentry-app-components/, and reads ofdashboards/…andworkflows/<id>/.The asserts and project filters from #2527 and #2541 are removed. One piece stays:
event view's fallback still rethrowsResolutionError. That catch-all would otherwise turn a refusal into a search across other orgs.The repo has no
design/directory, so the rule is written indocs/architecture/overview.mdand in thelimitToTargetrow oflibrary-usage.md.Open questions
limitToTargetdefaults totruesince fix(mcp): Check an issue an ID alone names against the session's project #2527, so everycreateSentrySDK({ org, project })caller now fails closed too, not just--commandssessions. Refused in a project scope today:sentry-app-installations/…, used for issue links;customers/…, used for trials;dsn-lookup/,project-keys/, preprod endpoints andagents/conversations/<id>/;Should fail-closed apply only when
sentry mcp --commandssets the scope, with plain SDK callers keeping only the ID checks?Spans from other projects in an in-scope trace are still returned. Their details (
projects/<other>/trace-items/…) are now refused, sotrace viewlists them without details.via @BYK.
--
View Session [Sentry]