Skip to content

feat(auth): Allow OAuth tokens to manage org auth tokens - #128051

Merged
BYK merged 9 commits into
masterfrom
feat/org-auth-tokens-oauth
Oct 23, 2026
Merged

BYK merged 9 commits into
masterfrom
feat/org-auth-tokens-oauth

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

The org auth token endpoints (/organizations/{org}/org-auth-tokens/ and the details route) only accepted session auth. That meant the CLI couldn't mint an org:ci token for source map upload after an OAuth login (getsentry/toolkit#1388).

These endpoints now also accept user tokens, and OrgAuthTokenPermission limits that to OAuth application tokens acting for a real user:

  • Personal tokens (no application), org auth tokens, API keys, and integration/Sentry App tokens are still rejected.
  • The OAuth grant has to include a new, dedicated org:tokens scope. Existing org:ci grants are not enough, so this doesn't widen what already-deployed org:ci credentials can do. A missing org:tokens returns a 403 with an RFC 6750 insufficient_scope challenge, so the CLI can ask the user to re-authorize.
  • org:tokens is token-only (in SENTRY_TOKEN_ONLY_SCOPES, like org:ci): it's a consent gate, not a role permission. Personal tokens have it stripped on save, and it isn't added to the Sentry App scope list.
  • The existing scope and role checks still apply on top: org:read for list/create/rename, org:write for delete, and the user must be a member of the org.

CLI follow-up: the CLI needs to request org:tokens and org:read in its OAuth scopes (plus org:write if it wants token delete).

Fixes #122462
Refs ENG-8458

via Junior system actor event.

--

View Junior Session in Sentry

The org auth token endpoints only accepted session auth, so the CLI could not mint an org:ci token for source map upload after an OAuth login. OAuth application tokens acting for a user are now accepted when the grant includes org:ci. Personal, org auth, and integration tokens are still rejected.

Fixes #122462

Refs ENG-8458

Co-Authored-By: byk <[email protected]>
@linear-code

linear-code Bot commented Oct 19, 2026

Copy link
Copy Markdown

ENG-8458

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Oct 19, 2026
@BYK
BYK marked this pull request as ready for review October 19, 2026 20:22
@BYK
BYK requested a review from a team as a code owner October 19, 2026 20:22

@michelletran-sentry michelletran-sentry 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.

Can we create a new scope instead? Currently org:ci tokens are deployed in many different places and opening up the capabilities of existing tokens.

…cope

Reusing org:ci as the consent scope would let every existing org:ci OAuth
grant start managing org auth tokens. Add a dedicated token-only
org:tokens scope instead, so only clients the user explicitly authorizes
for token management can use these endpoints.
The OAuth consent helper requires every scope in SENTRY_SCOPES to belong to
a permission group, so the new org:tokens scope needs its own resource row.
Comment thread src/sentry/api/bases/organization.py Resolved
@BYK

BYK commented Oct 20, 2026

Copy link
Copy Markdown
Member

Can we create a new scope instead? Currently org:ci tokens are deployed in many different places and opening up the capabilities of existing tokens.

I think there's a misunderstanding here: we want OAuth tokens issued for the CLI to be able to control (add, remove, rotate etc) org:ci tokens, not the other way around. This patch should not affect any org:ci token capabilities at all.

@michelletran-sentry michelletran-sentry 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.

A few comments about adding app_id to the audit logs. We want to be able to track the token lineage so that users (and us) can find CI tokens created by a compromised minting token. It would also be a nice future addition to add this to the token list or details page.

@michelletran-sentry
michelletran-sentry dismissed their stale review October 21, 2026 13:57

org:tokens was added. I am satisfied.

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

We should have a rule/test that ensures that tokens minted from existing tokens:

  1. Never has this new scope so they cannot mint new tokens themselves
  2. Should never have more scope than the issuing token

Comment thread src/sentry/api/bases/organization.py Outdated
def has_permission(self, request: Request, view: APIView) -> bool:
if request.auth is not None:
# OAuth application tokens acting for a user are the only tokens allowed here.
# Personal, org auth, and integration tokens must not be able to mint new tokens.

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.

Why not personal access tokens?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Personal tokens can't carry org:tokens today. org:tokens is in SENTRY_TOKEN_ONLY_SCOPES, and enforce_scope_hierarchy (receivers/tokens.py) strips token-only scopes from USER tokens on save. So a PAT could only get here with org:read/org:write, which would let any existing PAT mint CI tokens without explicit consent. It also has no application_id for the lineage Michelle asked for. That's why this stays OAuth-only. If we want PAT minting, it needs its own opt-in, e.g. letting org:tokens be selected for PATs. I'd do that as a separate change. Leaving this open in case you want it here.

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.

@michelletran-sentry wdyt, shall we look into enabling this?

Comment thread src/sentry/api/bases/organization.py Resolved
Comment thread src/sentry/api/bases/organization.py Resolved
Comment thread src/sentry/api/helpers/oauth_consent.py Resolved
Address review feedback on OAuth-managed org auth tokens:

- Require the issuing OAuth token to hold every scope it mints (org:ci),
  so a minted token never has more access than its issuer.
- Reject org:tokens on org auth tokens at the model validator so minted
  tokens can never mint further tokens.
- Only accept tokens authenticated via UserAuthTokenAuthentication and
  document what OrgAuthTokenPermission allows.
- Record application_id and api_token_id in ORGAUTHTOKEN_ADD/REMOVE audit
  entries so tokens minted by a compromised grant can be traced.
- Clarify org:tokens consent copy: it manages org:ci org auth tokens and
  cannot create personal tokens.

Co-Authored-By: BYK <[email protected]>
@sentry-junior

sentry-junior Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed @BYK's review in 9d95cb6:

  1. Minted tokens never get org:tokens. validate_scope_list on OrgAuthToken now rejects it. A test also mints a token via OAuth and checks that the new token itself gets a 403 on the mint endpoint.
  2. Minted tokens never exceed the issuer's scopes. On POST, the issuing OAuth token must hold every scope in ORG_AUTH_TOKEN_SCOPES (org:ci) in addition to org:tokens. If it doesn't, the request gets a 403 with a WWW-Authenticate: insufficient_scope challenge that lists the missing scopes.

⚠️ This changes what the CLI must request. To mint tokens it needs org:tokens org:ci org:read (plus org:write for delete). Listing or renaming tokens only needs org:tokens + org:read.

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

On POST, the issuing OAuth token must hold every scope in ORG_AUTH_TOKEN_SCOPES (org:ci) in addition to org:tokens. If it doesn't, the request gets a 403 with a WWW-Authenticate: insufficient_scope challenge that lists the missing scopes.

See, this is not what I wanted to enforce. What we want to enforce is the new tokens have at most the same scopes minus org:tokens but they can actually have less.

⚠️ This changes what the CLI must request. To mint tokens it needs org:tokens org:ci org:read (plus org:write for delete). Listing or renaming tokens only needs org:tokens + org:read.

You should put this as a comment on the CLI side issue or PR

@sentry-junior

sentry-junior Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@BYK got it. I'll switch to "minted scopes ⊆ issuer scopes − org:tokens" and drop the forced org:ci requirement on the issuer. One thing to settle before I code it:

Proposal

  • POST accepts an optional scopes list. It defaults to ["org:ci"], so the UI and session flow don't change.
  • For OAuth callers, every requested scope must be held by the issuing token, and org:tokens is always rejected (plus the model validator from 9d95cb6). Anything else gets a 400 naming the offending scopes.
  • Session callers stay org:ci-only, the same as today.

Open question: do we cap which scopes an org auth token can hold at all? Org auth tokens aren't bound to a member. ScopedPermission checks their scope_list directly, and they keep working after created_by leaves the org. So with only the subset rule, an owner's CLI grant could mint a long-lived org:admin / member:admin org token. Today every org token is org:ci, and that's what the UI, docs and Michelle's lineage concern assume. Options:

  1. Subset rule only (what you described).
  2. Subset rule plus an allowlist of CI-appropriate scopes, e.g. org:ci, project:releases, project:read, org:read.

I'd lean toward 2. Which do you want? I'll implement it and post the CLI scope requirements on getsentry/toolkit#1388 once it's settled (getsentry/cli#1112 is closed).

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

Junior, you actually raise a good point. I want the tests to check for the subset condition but for now, out of caution, we should only allow minting new tokens with the org:ci scope. The code should support allowing more scopes easily as in your option 2 but should NOT expand the scope to more than org:ci for now in this PR.

Token creation now accepts an optional `scopes` list (default org:ci).
Requested scopes must be in ORG_AUTH_TOKEN_ALLOWED_SCOPES, which is
org:ci only for now, and never include org:tokens. A token-authenticated
caller may only mint a subset of its own scopes. The issuer is no longer
required to hold org:ci up front. Tests cover the subset rule against a
widened allowlist so broadening it later is a one-line change.
@sentry-junior

sentry-junior Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@BYK done in 1ceb3a9:

  • POST accepts an optional scopes list, defaulting to ["org:ci"]. Requested scopes must be in ORG_AUTH_TOKEN_ALLOWED_SCOPES (models/orgauthtoken.py), which is org:ci only for now. org:tokens is always rejected, and anything else gets a 400.
  • Subset rule: a token-authenticated caller can only mint scopes it holds itself. Fewer is fine, more gets a 403 insufficient_scope naming the missing scopes. I dropped the upfront "issuer must hold org:ci" check from the permission class. The permission now only requires org:tokens.
  • Tests: test_minted_scopes_are_subset_of_issuer_scopes widens the allowlist with a patch and checks the three cases: a request beyond the issuer's scopes gets a 403, a narrower or equal request succeeds, and org:tokens is still rejected. Widening the allowlist later is a one-line change.

I moved the CLI scope requirements to getsentry/toolkit#1388.

@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

No findings on the latest commit.

Read name and scopes from a serializer's validated_data instead of
request.data. The endpoint keeps its existing name error messages.
@BYK
BYK merged commit 708cc75 into master Oct 23, 2026
89 checks passed
@BYK
BYK deleted the feat/org-auth-tokens-oauth branch October 23, 2026 22:10
BYK added a commit to getsentry/toolkit that referenced this pull request Nov 4, 2026
Adds `sentry token list`, `sentry token create`, and `sentry token
delete` for org auth tokens (the `org:ci` tokens used for source map,
debug file, and release uploads). `sentry tokens` is an alias for `token
list`. This is the CLI side of getsentry/sentry#128051, and replaces the
archived getsentry/cli#1112.

```
sentry token list [<org>]
sentry token create [<org>/]<name>        # prints the token value once
sentry token delete [<org>/]<token-id>    # buildDeleteCommand: --yes/--force/--dry-run, type-to-confirm
```

### Scopes

Sentry only lets OAuth application tokens that hold `org:tokens` manage
org auth tokens. Personal tokens, org tokens, and `SENTRY_AUTH_TOKEN`
get a 403. Here's what each endpoint requires, checked against the
merged backend:

| Command | Needs |
|---|---|
| list | `org:tokens` + `org:read` |
| create | `org:tokens` + `org:read` + `org:ci` (an OAuth caller can
only mint scopes it holds) |
| delete | `org:tokens` + `org:read` + `org:write` (the delete is
`org:write`, the confirm lookup is `org:read`) |

`org:tokens` is now in `SENTRY_SCOPES`, so `auth login --scope
org:tokens` validates. I kept it out of the default `OAUTH_SCOPES` on
purpose. The device flow rejects the whole request when it sees a scope
it doesn't know, so adding `org:tokens` to the defaults would break
`sentry auth login` on older self-hosted servers.

Instead, each token command calls `ensureScopesForAction`, and it can
now ask for scopes outside the defaults:

- If `required` only names default scopes, nothing changes: the device
flow requests the defaults.
- Otherwise it requests three things: the defaults, the known opt-in
scopes the grant already has (so elevating for one command doesn't
remove what an earlier elevation added), and `required`.

When elevation is needed but this run can't do it (no TTY, `--yes`, or
`--json`), a 403 gets a specific explanation: what to run once
interactively, or that the command needs a CLI login plus an org role
that allows it.

### Notes for review

- The endpoints are control-silo, so they're called through
`getControlSiloUrl()`. They aren't in `@sentry/api` (checked 0.399.0),
so `OrgAuthTokenSchema` is a Valibot schema that mirrors the backend
serializer.
- The full token value only appears in `create` output, including
`--json`, because Sentry can't return it again. `list` shows only
`tokenLastCharacters`.
- `delete` reads the list to show the token name in the confirmation,
since there's no single-token GET. The list is unpaginated server-side.
- `create` splits `org/name` on the first `/`, but only when the prefix
looks like an org slug. Names containing `/` work as long as the org is
given explicitly.

### Tests

- New tests for the API module, the shared helpers, all three commands,
and the opt-in scope elevation in `scope-recovery`.
- `typecheck`, `lint`, `check:docs-sections`, `check:destructive`,
`check:fragments`, and `check:errors` pass.
- The full unit suite passes except 6 permission-based tests
(chmod/EACCES) in completions, upgrade, telemetry, code-scanner, and
file-changes. Those fail the same way on `main` in my sandbox, so
they're environment issues unrelated to this change.
- Not exercised against a live Sentry instance.

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

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

--

[View Junior Session in
Sentry](https://sentry.sentry.io/explore/conversations/local%3Aweb%3Aea151394798e521acab43719/?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]>
Co-authored-by: betegon <[email protected]>
BYK pushed a commit that referenced this pull request Nov 7, 2026
Publishes the org auth token operations the Sentry CLI uses to manage CI
tokens, so they reach the public OpenAPI schema and the generated
`@sentry/api` client. Refs #130351, where these endpoints were proposed
for publishing. In the Slack discussion that led to it, the request was
that org auth tokens "should be public too unless you have strong
opposition".

| Operation | Endpoint | operationId |
| --- | --- | --- |
| `GET /organizations/{org}/org-auth-tokens/` |
`OrganizationAuthTokensEndpoint` | `listOrganizationAuthTokens` |
| `POST /organizations/{org}/org-auth-tokens/` |
`OrganizationAuthTokensEndpoint` | `createOrganizationAuthToken` |
| `DELETE /organizations/{org}/org-auth-tokens/{token_id}/` |
`OrganizationAuthTokenDetailsEndpoint` | `deleteOrganizationAuthToken` |

`GET` and `PUT` on a single token stay `PRIVATE`. The CLI doesn't use
them, and the issue didn't ask for them.

**Why now:** the endpoints have existed since 2023-06-20, and their
request and response shapes haven't changed since. #128051 (2026-10-23)
let OAuth application tokens holding `org:tokens` call them. That is the
path the CLI needs, so publishing them now gives the CLI a typed,
documented client.

### Security-relevant behavior, now in the operation descriptions
These come from `OrgAuthTokenPermission`
(`src/sentry/api/bases/organization.py`) and the endpoint code:
- **Who can call it:** a signed-in session, or an OAuth application
token that holds `org:tokens` plus a `scope_map` scope
(`org:read`/`org:write`/`org:admin`; `DELETE` needs `org:write` or
`org:admin`).
- Personal auth tokens, org auth tokens and integration tokens are
always rejected with 403.
- The schema's `security` block is derived from `scope_map` and can't
express `org:tokens` or these rejections, so the descriptions state
them.
- **List** never returns a token's value, only `tokenLastCharacters`. It
is not paginated.
- **Create:**
  - Returns the full `token` exactly once.
  - Only `org:ci` can be granted, and `org:tokens` can never be granted.
- An OAuth caller can only grant scopes its own token holds. Otherwise
it gets 403 `insufficient_scope`.
- Every new token is written to the audit log and emailed to all org
owners.
- Impersonated sessions are blocked by
`DisallowImpersonatedTokenCreation`.
- **Delete** deactivates the token (soft delete) and writes an audit log
entry. A second call returns 404.
- Both mutations set `idempotent_methods = frozenset()`.

### POST/DELETE: PUBLIC rather than PUBLIC_EXPERIMENTAL?
My view is that there's no strong reason against `PUBLIC`.
- Publishing doesn't change who can call these endpoints. That's still
enforced by the permission class, the `org:tokens` consent, the scope
cap, owner emails and audit logs.
- The request and response contract has been stable for more than two
years.
- The newest piece is the OAuth path from #128051, which is about two
weeks old. If its rules change, the likely changes are allowing more
scopes or tightening the permission check. Neither changes the
documented shape.
- `PUBLIC_EXPERIMENTAL` would only make sense if Foundations expects to
change the request body or the response, and I found nothing pointing
that way.

### Other changes
- **Response type:** `OrgAuthTokenSerializerResponse` fields now have
descriptions.
- **`name` stays optional in the request schema** but its description
says it's required. The serializer keeps `required=False` on purpose, so
the endpoint can return its existing `{"detail": "The name cannot be
blank."}` error, which tests assert. Making it required in the schema
would change that error body.
- **Typed returns:** return annotations use `Response[T]` arms, as
flake8 S022 requires. The serializer errors path goes through
`as_validation_errors`, with no runtime change.
- **Schema extension fix:** `apidocs/extensions.py` now skips permission
classes that have no `scope_map`. Without that, `make build-api-docs`
crashed on `DisallowImpersonatedTokenCreation`. These are the first
published endpoints to use that permission class.
- **Agent token permission matrix**
(`test_organization_agent_token.py`):
  - Adds an org auth token fixture for `token_id` and a POST payload.
- These endpoints now assert that every token credential (personal,
agent, scoped-down agent, approved agent and service account) is denied
with 401/403.

### Flag for Security: viewer context can call these endpoints
The matrix showed that a Seer-signed `X-Viewer-Context` request can
list, create and revoke org auth tokens for the user.
`ViewerContextAuthentication` (and the auth middleware) sets
`request.user` without `request.auth`, so `OrgAuthTokenPermission`
treats it like a session. This is how master behaves today and this PR
doesn't change it; the matrix just records it. Please confirm it's
intended, or say if it should be denied in a follow-up.

### Schema check
I ran `make build-api-docs` and diffed `openapi-derefed.json` against
master. The only changes are the three added operations above, plus the
new `OrgAuthToken`, `OrgAuthTokenCreate` and `OrgAuthTokenListResponse`
components. The "(Optional) Shows the difference between the prod and
dev schema" check is expected to fail on a schema-changing PR.

### Tests run locally
- `make build-api-docs` and `pnpm run validate-api-examples`: pass
- `pytest tests/apidocs`, `test_organization_auth_tokens.py`,
`test_organization_auth_token_details.py` and
`tests/sentry/seer/endpoints/test_organization_agent_token.py`: 545
passed, 23 xfailed
- `pytest tests/sentry/apidocs`: 167 passed
- `prek run` and mypy (`--stage pre-push`) on the changed files: pass

CODEOWNERS routes these files to app-backend, so I'm also requesting
review from Foundations and Security.

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

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

--

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

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

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
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.

Allow org:ci token creation via OAuth access tokens

3 participants