Skip to content

feat(api): Advertise required scopes on token-scope 403s (RFC 6750) - #118612

Merged
gricha merged 1 commit into
masterfrom
greg/insufficient-scope-errors
Jun 29, 2026
Merged

gricha merged 1 commit into
masterfrom
greg/insufficient-scope-errors

Conversation

@gricha

@gricha gricha commented Jun 26, 2026

Copy link
Copy Markdown
Member

Summary

When a token-authorized request is denied for lacking the required scope, Sentry returns a
bare 403 {"detail": "You do not have permission to perform this action."} — it never says
which scope was needed. This adopts the OAuth 2.0 standard answer (RFC 6750
insufficient_scope) so callers know what they're missing:

WWW-Authenticate: Bearer error="insufficient_scope", scope="org:admin org:write"

The required scopes come from the endpoint's own scope_map, surfaced from the single
shared token-scope gate (ScopedPermission.has_permission), so every token-scoped
endpoint gets it with no per-class edits.

Why it's safe / non-breaking

  • The 403 body is unchanged — the scope info rides only in the WWW-Authenticate
    header, so clients parsing {"detail": ...} are unaffected.
  • No-op for non-token auth (session/superuser/staff) and for 401 authentication failures.
  • The transport already existed: custom_exception_handler copies an exception's
    auth_header onto WWW-Authenticate (it even cited RFC 6750).
  • Discloses only the endpoint's required scopes (already public in open-source scope_map
    and the API docs). The denial fires at the view level before the org/object is loaded,
    so it leaks no resource existence; it never enumerates the caller's held scopes.

Non-goals

  • Object-level scope denials (has_object_permission) are not enriched yet — deliberate,
    to keep the blast radius small. The view-level gate covers the motivating cases.

Tests

tests/sentry/api/test_permissions.py: unit (the raise + exact header at the permission
boundary) and end-to-end (header reaches the HTTP response; body unchanged; no header
on 401, on session denial, or on success).

Spec: openspec/changes/add-insufficient-scope-errors/.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Jun 26, 2026
@gricha
gricha force-pushed the greg/insufficient-scope-errors branch 3 times, most recently from 27a0106 to 0599669 Compare June 29, 2026 15:14
@gricha
gricha marked this pull request as ready for review June 29, 2026 15:15
@gricha
gricha requested review from a team as code owners June 29, 2026 15:15
Comment thread src/sentry/api/permissions.py Resolved
default_detail = "The requested resource does not exist"


class InsufficientScope(PermissionDenied):

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.

not blocking, i'm curious if we will want this for any getsentry endpoints and if this will work out of the box for those

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

i do think it works out of the box if i am to trust the agent here

@gricha
gricha force-pushed the greg/insufficient-scope-errors branch from 0599669 to 3f7ce77 Compare June 29, 2026 18:05
Comment thread tests/sentry/api/bases/test_project.py Outdated
Comment on lines +38 to +40
return perm.has_permission(drf_request, APIView()) and perm.has_object_permission(
drf_request, APIView(), obj
)

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.

Having a has_* method raise when you're denied feels a bit clunky. Usually has* methods will capture any exceptions from the checks they do and return a bool.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

corrected, thanks for the call out!

When a token-authorized request is denied because its scopes do not cover the
endpoint's required scopes, return an RFC 6750 insufficient_scope challenge in the
WWW-Authenticate header instead of a bare 403, so callers learn which scope they lack.

has_permission stays a plain bool: the shared token-scope gate records the required
scopes on the request, and Endpoint.permission_denied (which already raises for
superuser/staff) raises InsufficientScope from them. The required scopes come from the
endpoint's own scope_map, so every token-scoped endpoint benefits with no per-class edits.

The response body is unchanged and the behavior is a no-op for non-token auth and for
401s, so this is non-breaking. Sentry's custom_exception_handler already forwards an
exception's auth_header onto WWW-Authenticate, so the transport is reused as-is.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@gricha
gricha force-pushed the greg/insufficient-scope-errors branch from 3f7ce77 to b354c93 Compare June 29, 2026 19:50
Comment thread src/sentry/api/base.py Resolved
@gricha
gricha merged commit 68c8a61 into master Jun 29, 2026
87 checks passed
@gricha
gricha deleted the greg/insufficient-scope-errors branch June 29, 2026 21:32
shayna-ch pushed a commit that referenced this pull request Jun 30, 2026
…118612)

## Summary

When a token-authorized request is denied for lacking the required
scope, Sentry returns a
bare `403 {"detail": "You do not have permission to perform this
action."}` — it never says
*which* scope was needed. This adopts the OAuth 2.0 standard answer (RFC
6750
`insufficient_scope`) so callers know what they're missing:

```
WWW-Authenticate: Bearer error="insufficient_scope", scope="org:admin org:write"
```

The required scopes come from the endpoint's own `scope_map`, surfaced
from the single
shared token-scope gate (`ScopedPermission.has_permission`), so
**every** token-scoped
endpoint gets it with no per-class edits.

## Why it's safe / non-breaking

- The `403` **body is unchanged** — the scope info rides only in the
`WWW-Authenticate`
  header, so clients parsing `{"detail": ...}` are unaffected.
- No-op for non-token auth (session/superuser/staff) and for `401`
authentication failures.
- The transport already existed: `custom_exception_handler` copies an
exception's
  `auth_header` onto `WWW-Authenticate` (it even cited RFC 6750).
- Discloses only the endpoint's required scopes (already public in
open-source `scope_map`
and the API docs). The denial fires at the view level *before* the
org/object is loaded,
so it leaks no resource existence; it never enumerates the caller's held
scopes.

## Non-goals

- Object-level scope denials (`has_object_permission`) are not enriched
yet — deliberate,
to keep the blast radius small. The view-level gate covers the
motivating cases.

## Tests

`tests/sentry/api/test_permissions.py`: unit (the raise + exact header
at the permission
boundary) and end-to-end (header reaches the HTTP response; body
unchanged; **no** header
on `401`, on session denial, or on success).

Spec: `openspec/changes/add-insufficient-scope-errors/`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.8 <[email protected]>
betegon added a commit to getsentry/toolkit that referenced this pull request Nov 11, 2026
…ssing (#2165)

Stacked on #2163.

Split out of #2160.

About 1% of `release set-commits` runs hit a 403 on the repos list: over
14 days, about 41k on 0.45 and 126 on 0.49. The repos list accepts
`org:ci` but not `project:releases`, so a personal token made for
releases fails there with no hint why. Since getsentry/sentry#118612,
Sentry lists the accepted scopes in `WWW-Authenticate: Bearer
error="insufficient_scope", scope="..."`. The CLI now shows them.

### Before

`release set-commits`, with a personal token in `SENTRY_AUTH_TOKEN` that
lacks `org:ci`:

```
Error: Failed to list repositories: 403 Forbidden
  You do not have permission to perform this action.

  Your SENTRY_AUTH_TOKEN token may lack the required scope for this operation.
  Check token scopes at: <sentry-url>/settings/account/api/auth-tokens/
```

### After

```
Error: Failed to list repositories: 403 Forbidden
  You do not have permission to perform this action.

  Your SENTRY_AUTH_TOKEN token lacks the scope this request needs. Any one of these works: org:admin, org:ci, org:integrations, org:read, org:write.
  An org auth token has org:ci. Create one in your organization's Settings > Auth Tokens.
  Check token scopes at: <sentry-url>/settings/account/api/auth-tokens/
```

The second line depends on the credential that sent the request:
- **Org auth token, on an endpoint `org:ci` can't satisfy:** `Org auth
tokens only have org:ci. Use a personal token with one of these scopes
instead.`
- **`sentry auth login` session:** `Your login lacks the scope this
request needs. Any one of these works: …`, followed by `auth login
--force`, or `auth refresh --scope <default scopes>,<needed scope>` when
none of the default scopes is accepted.

Self-hosted servers older than getsentry/sentry#118612 don't send the
header, so they keep the "may lack the required scope" message.

<!-- junior-request-attribution:start -->
via @betegon.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A28e783cd48c13b214d69caf6d8977a0c -->

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/agent%3A28e783cd48c13b214d69caf6d8977a0c/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: bete <[email protected]>
BYK added a commit to getsentry/sentry-api-schema that referenced this pull request Nov 12, 2026
… accepts (#146)

When a token lacks every scope an endpoint accepts, Sentry returns a 403
with DRF's generic `{"detail":"You do not have permission to perform
this action."}` and names the accepted scopes only in `WWW-Authenticate:
Bearer error="insufficient_scope", scope="..."`
(getsentry/sentry#118612). The request core dropped that header, so the
MCP told agents to "address the concern and try again", which can't work
with the same token (getsentry/toolkit#2208). The CLI parsed the header
itself, but only on its own request path.

- `readErrorResponse` reads the challenge into `acceptedScopes` (403s
only).
- The core passes it through `createApiError` (new optional last
argument) to `ApiPermissionError.acceptedScopes`, with
`isInsufficientScopeError()`.
- `ApiPermissionError.toUserMessage()` names the scopes and says
retrying with the same token will not help. Other 403s keep the old
message.
- `parseInsufficientScopeChallenge` moves here from the Sentry CLI, so
the CLI and MCP share one parser. It keeps only well-formed
`namespace:action` scope names, so no other header text reaches users or
agents.

Everything is additive; existing callers don't change. The toolkit
change that uses this is on toolkit branch `fix/insufficient-scope-403`.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:local%3Aweb%3A0e1dc56124311021b965584c -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/local%3Aweb%3A0e1dc56124311021b965584c)
[[Sentry]](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A0e1dc56124311021b965584c/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK pushed a commit to getsentry/toolkit that referenced this pull request Nov 13, 2026
…t_scope (#2222)

Fixes #2208.

When a token lacks the scope an endpoint needs, Sentry returns a 403
with DRF's generic detail and lists the accepted scopes only in
`WWW-Authenticate: Bearer error="insufficient_scope", scope="..."`. The
MCP dropped that header and showed the generic **Input Error** template
("…address the concern and try again"), which can't work with the same
token. For example, starting autofix in `analyze_issue_with_seer` needs
`event:write`, `event:admin`, or `seer:write`. Sentry already sends the
challenge for that endpoint (getsentry/sentry#118612), so no backend
change is needed.

`@sentry/api` 1.83.0 (getsentry/sentry-api-schema#146) reads the header
in the shared request core: `ApiPermissionError.acceptedScopes` holds
the scopes, and its `toUserMessage()` names them. This PR bumps to
1.83.0 and uses that:

- **MCP**: `formatErrorForUser` returns a **Missing Permission** message
that names the accepted scopes and says retrying with the same token
won't help. It also finds the error when a tool rewrapped it as `cause`
(e.g. `withApiErrorHandling`'s `UserInputError`). Embedded agent tools
get the same message, without the "try again" advice.
- **CLI**: the CLI already turned this challenge into scope guidance on
its own request path. It now uses the shared
`parseInsufficientScopeChallenge` instead of a local copy, so behavior
is the same. `sentry mcp` gets the MCP fix through mcp-core.

The message only names the scopes the endpoint accepts, which are the
same for every caller. Nothing about the user, role, org, or token is
added. A role-based 403 has no challenge and keeps the old message.

Out of scope: `analyze_issue_with_seer` still declares `requiredScopes:
[]`. Gating the tool on `event:write` would hide it from grants that can
read Seer results, so that's a product call for a separate change.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:local%3Aweb%3A0e1dc56124311021b965584c -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/local%3Aweb%3A0e1dc56124311021b965584c)
[[Sentry]](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A0e1dc56124311021b965584c/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants