Repository navigation
fix(mcp): Enforce the session scope in the API transport - #2549
sentry-junior[bot] wants to merge 11 commits into
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>
Fixes from review of the transport scope guard: - A project-filtered list with only `projectSlug`, or a slug in `project`, was sent as is. Not every endpoint reads those, so it could run unfiltered. It now always gets the scope project's ID. - A response naming the scope project by ID next to other projects' slugs (a trace across projects) was refused: the IDs were ignored as soon as one slug was present. Each ref is now compared with the scope project in its own kind, looking that up once when needed. A project with both a slug and an ID counts once, by slug. - A scope named by numeric project ID waited on its own lookup. Its ID is now used as given, and the scope project's own path passes without a lookup. - `withTargetScope` sent the scope's lookups without the request's headers, so an authenticated download's lookups had no token. They now carry the request's headers. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
A scoped request with a slug in `project` kept the slug next to the scope project's ID. Sentry reads slugs there now, but older versions integer-cast every `project` value and refuse the request. Once checked, slugs and `-1` are dropped from `project`, so the filter carries only numeric IDs, the scope project's when there are none. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
On `main`, the CLI compiles with `noPropertyAccessFromIndexSignature` and `exactOptionalPropertyTypes`, so the scope rules read response fields by key and a scope project's slug may be `undefined`. Objectstore uploads (`snapshots upload`) also landed on `main`. They send the pre-signed token Sentry issues for them, not the CLI's credential, so the coverage test lists `lib/objectstore.ts` with the other senders the scope does not need to guard. Refs #2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
a386c10 to
7a9798c
Compare
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.
| { pattern: "organizations/:org/discover/saved/" }, | ||
| { pattern: "organizations/:org/discover/saved/:query/" }, | ||
| { pattern: "organizations/:org/group-search-views/" }, | ||
| { pattern: "organizations/:org/workflows/:workflow/" }, |
There was a problem hiding this comment.
Workflow detail GET bypasses project scope checks
ORG_READS allows GET organizations/:org/workflows/:workflow/ with no project verification, so a project-scoped session can read any org workflow (alert conditions, actions, Slack/email targets) by ID. List uses project-filter and detectors use response project checks; this detail path should too.
Evidence
ORG_READSincludesorganizations/:org/workflows/:workflow/with default GET/HEAD and noenforcehook.scopeRequestreturns early onORG_READSmatches withNOTHING_TO_VERIFY, so the workflow body is never checked against the session project.- The same file's
PROJECT_FILTEREDonly covers the list pathorganizations/:org/workflows/, and detector detail correctly useskind: "response"project checks. getIssueAlertRulefilters workflows byproject+idat the API layer, but transport-level callers (e.g.sentry api) can hit the detail URL directly and skip that guard.
Identified by Warden · security-review · YLQ-ZDB
| pattern: "organizations/:org/releases/:version/**", | ||
| subject: ({ version }) => `Release ${version}`, | ||
| enforce: { | ||
| kind: "look-up-first", | ||
| lookups: (params) => [{ path: releasePath(params) }], | ||
| }, | ||
| }, |
There was a problem hiding this comment.
Release version writes refused under project scope
The releases/:version/** rule omits methods: ANY_METHOD, so PUT/POST/DELETE on a release (finalize, archive, delete, deploy, set-commits) never match and are refused even when the release is in scope. Add methods: ANY_METHOD like the issue/monitor/detector /** rules.
Evidence
LookUpFirstis documented for requests that "read or change" an ID-named resource, and sibling rules (issues/:issue/**,monitors/:monitor/**,detectors/:detector/**) setmethods: ANY_METHODso non-GET hits the look-up-first path.organizations/:org/releases/:version/**has nomethods, so it defaults toREADS(GET,HEAD) only.updateRelease/deleteRelease/createReleaseDeploycallupdateOrganizationRelease,deleteOrganizationRelease, andcreateOrganizationReleaseDeploy(PUT/DELETE/POST onorganizations/:org/releases/:version/or a subpath).- With a project scope, those methods match neither the GET-only detail rule nor this
/**rule, somatchScopeRulereturns no match andscopeRequestthrows outside-scope before the request is sent.
Identified by Warden · code-review · 9ZJ-YF7
| * - Its path names the scope's organization (`organizations/<org>/...`, | ||
| * `projects/<org>/...`) and, in a project scope, its project | ||
| * (`projects/<org>/<project>/...`). |
There was a problem hiding this comment.
Scoped transport rejects self-hosted API URLs mounted under a path
When an org-scoped SDK targets a supported subpath install such as /sentry, scopeRequest rejects its /sentry/api/0/... requests before sending them because it only recognizes /api/0/...; API commands against that install fail. The same gate also blocks the wrapped same-region /dl/ artifact request in build download.
Evidence
scopeRequestonly extracts a rule path whenurl.pathname.startsWith("/api/0/"); otherwise it throwsoutsideScopebefore sending the request.- Self-hosted subpath URLs are supported:
infrastructure.test.tsexpects a raw API request tohttps://sentry.example.com/sentry/api/0/organizations/acme/. buildIsolatedEnvenables the target scope by default whenoptions.orgis set, anddownloadBuildArtifactwraps same-region downloads such as/dl/?response_format=ipawithwithTargetScope, so those requests also hit the rejection.
Also found at 1 additional location
packages/cli/src/lib/target-scope.ts:394-399
Identified by Warden · code-review · K4F-VCX
| return { input, verify: NOTHING_TO_VERIFY }; | ||
| } | ||
| const match = matchScopeRule(PROJECT_SCOPE_RULES, method, segments); | ||
| if (!match) { | ||
| throw outsideScope(subject, scope); | ||
| } | ||
| return await applyRule( |
There was a problem hiding this comment.
Project scope refuses POST chunk-upload and artifactbundle assemble
Under a project limitToTarget scope, sourcemap/debug-file/proguard uploads fail: GET chunk-upload is allowed as ORG_READS, but POST chunk upload and artifactbundle/assemble match no project rule and are refused by scopeRequest.
Evidence
- After ORG_READS, unmatched project-scope paths hit
throw outsideScopeinscopeRequest. - ORG_READS lists
organizations/:org/chunk-upload/with default GET/HEAD only; PROJECT_SCOPE_RULES has no chunk-upload orartifactbundle/assemblerule. uploadMissingChunksPOSTs to the server chunk-upload URL via authenticated fetch;assembleArtifactBundlePOSTsorganizations/{org}/artifactbundle/assemble/.- Tests allow GET chunk-upload as "upload options" but never POST; project-path assemble under
projects/:org/:project/**still depends on the preceding chunk POST.
Identified by Warden · code-review · HZG-EZS

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]