Skip to content

fix(mcp): Enforce the session scope in the API transport - #2549

Open
sentry-junior[bot] wants to merge 11 commits into
fix/mcp-commands-opaque-id-scopefrom
fix/mcp-commands-central-scope
Open

sentry-junior[bot] wants to merge 11 commits into
fix/mcp-commands-opaque-id-scopefrom
fix/mcp-commands-central-scope

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Refs #2237. Stacked on #2541 (→ #2527 → main).

#2527 and #2541 checked the limitToTarget scope 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's trace-logs and trace-meta ignore the project filter.
  • sentry api organizations/<other>/....
  • The two preprod downloads that send the token around the transport.

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.

  • assertCredentialScope in prepareHeaders checks only the host, and it runs after the transport's cache lookup.
  • sdk-invoke.ts only turns limitToTarget into the SENTRY_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 in createAuthenticatedFetch before transport.request. That covers SDK calls, apiRequestToRegion, raw sentry api and 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.ts is refused before it is sent.

  • Paths. 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.
  • Project filter (project scope). issues/ (including bulk PUT/DELETE), events/, events-timeseries/, events-dropped/, trace-items/attributes/, replays/, replay-count/, monitors/, detectors/, workflows/, releases/ and agents/conversations/ get filtered to the scope's project. A missing project or -1 is replaced with the scope project's ID, looked up once per process. Any other project is refused.
  • Checked by the response (project scope). issues/<id>/, shortids/<id>/, shared/issues/<id>/, eventids/<id>/, replays/<id>/, monitors/<id>/, detectors/<id>/, releases/<version>/ and trace/<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.
  • Looked up first (project scope). A request on what an ID names first runs the matching response check, once per process. This covers PUT issues/<id>/, issues/<id>/events/…, monitor and detector writes, release sub-resource reads, trace-meta/<id>/ and trace-logs/?traceId=.
  • Allowlist.
    • Any scope: GET /api/0/, auth/ and users/me/.
    • Project scope, org settings with no project data: org details, projects/, teams/, members/, environments/, integrations/, repos/, sentry-app-components/, and reads of dashboards/… and workflows/<id>/.

The asserts and project filters from #2527 and #2541 are removed. One piece stays: event view's fallback still rethrows ResolutionError. 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 in docs/architecture/overview.md and in the limitToTarget row of library-usage.md.

Open questions

  • limitToTarget defaults to true since fix(mcp): Check an issue an ID alone names against the session's project #2527, so every createSentrySDK({ org, project }) caller now fails closed too, not just --commands sessions. Refused in a project scope today:

    • org-level writes other than issues, monitors and detectors: dashboard writes, release writes (a release spans projects), workflow writes, team and project creation, org auth tokens, code mappings, artifact bundles and chunk uploads;
    • sentry-app-installations/…, used for issue links;
    • customers/…, used for trials;
    • dsn-lookup/, project-keys/, preprod endpoints and agents/conversations/<id>/;
    • the org list.

    Should fail-closed apply only when sentry mcp --commands sets 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, so trace view lists them without details.

via @BYK.

--

View Session [Sentry]

@vercel

vercel Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
cli Ready Ready Preview Nov 28, 2026 2:19am UTC
1 Skipped Deployment
Project Deployment Actions Updated
sentry-local Skipped Skipped Nov 28, 2026 2:19am UTC

Request Review

@sentry-junior
sentry-junior Bot added this pull request to stack #1926 November 26, 2026 23:42
@sentry-junior
sentry-junior Bot requested a review from BYK November 26, 2026 23:43

@BYK BYK left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread packages/cli/src/lib/target-scope.ts Resolved
Comment thread packages/cli/src/lib/target-scope.ts Resolved
Comment thread packages/cli/src/lib/target-scope.ts Resolved
Comment thread packages/cli/src/lib/target-scope.ts Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread packages/cli/src/lib/target-scope.ts Resolved
sentry-junior Bot and others added 2 commits November 27, 2026 12:13
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>
sentry-junior Bot and others added 4 commits November 27, 2026 12:13
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>
BYK added a commit to getsentry/sentry that referenced this pull request Nov 27, 2026
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>
@BYK
BYK enabled stacked auto-merge November 27, 2026 23:28
…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.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread packages/cli/src/lib/api/issues.ts Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Fix All in Cursor

❌ 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/" },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_READS includes organizations/:org/workflows/:workflow/ with default GET/HEAD and no enforce hook.
  • scopeRequest returns early on ORG_READS matches with NOTHING_TO_VERIFY, so the workflow body is never checked against the session project.
  • The same file's PROJECT_FILTERED only covers the list path organizations/:org/workflows/, and detector detail correctly uses kind: "response" project checks.
  • getIssueAlertRule filters workflows by project + id at 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

Comment on lines +366 to +372
pattern: "organizations/:org/releases/:version/**",
subject: ({ version }) => `Release ${version}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: releasePath(params) }],
},
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
  • LookUpFirst is documented for requests that "read or change" an ID-named resource, and sibling rules (issues/:issue/**, monitors/:monitor/**, detectors/:detector/**) set methods: ANY_METHOD so non-GET hits the look-up-first path.
  • organizations/:org/releases/:version/** has no methods, so it defaults to READS (GET, HEAD) only.
  • updateRelease / deleteRelease / createReleaseDeploy call updateOrganizationRelease, deleteOrganizationRelease, and createOrganizationReleaseDeploy (PUT/DELETE/POST on organizations/:org/releases/:version/ or a subpath).
  • With a project scope, those methods match neither the GET-only detail rule nor this /** rule, so matchScopeRule returns no match and scopeRequest throws outside-scope before the request is sent.

Identified by Warden · code-review · 9ZJ-YF7

Comment on lines +14 to +16
* - Its path names the scope's organization (`organizations/<org>/...`,
* `projects/<org>/...`) and, in a project scope, its project
* (`projects/<org>/<project>/...`).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
  • scopeRequest only extracts a rule path when url.pathname.startsWith("/api/0/"); otherwise it throws outsideScope before sending the request.
  • Self-hosted subpath URLs are supported: infrastructure.test.ts expects a raw API request to https://sentry.example.com/sentry/api/0/organizations/acme/.
  • buildIsolatedEnv enables the target scope by default when options.org is set, and downloadBuildArtifact wraps same-region downloads such as /dl/?response_format=ipa with withTargetScope, 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

Comment on lines +418 to +424
return { input, verify: NOTHING_TO_VERIFY };
}
const match = matchScopeRule(PROJECT_SCOPE_RULES, method, segments);
if (!match) {
throw outsideScope(subject, scope);
}
return await applyRule(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 outsideScope in scopeRequest.
  • ORG_READS lists organizations/:org/chunk-upload/ with default GET/HEAD only; PROJECT_SCOPE_RULES has no chunk-upload or artifactbundle/assemble rule.
  • uploadMissingChunks POSTs to the server chunk-upload URL via authenticated fetch; assembleArtifactBundle POSTs organizations/{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

This branch was successfully deployed

1 active and 1 inactive deployments
Preview – cli — bf67348b Deployed Nov 28, 2026 by vercel[bot]
Preview – sentry-local — bf67348b Deployed Nov 28, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant