Repository navigation
feat(auth): Allow OAuth tokens to manage org auth tokens - #128051
Conversation
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]>
Co-Authored-By: byk <[email protected]>
michelletran-sentry
left a comment
There was a problem hiding this comment.
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.
I think there's a misunderstanding here: we want OAuth tokens issued for the CLI to be able to control (add, remove, rotate etc) |
michelletran-sentry
left a comment
There was a problem hiding this comment.
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.
org:tokens was added. I am satisfied.
BYK
left a comment
There was a problem hiding this comment.
We should have a rule/test that ensures that tokens minted from existing tokens:
- Never has this new scope so they cannot mint new tokens themselves
- Should never have more scope than the issuing token
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@michelletran-sentry wdyt, shall we look into enabling this?
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]>
|
Addressed @BYK's review in 9d95cb6:
|
BYK
left a comment
There was a problem hiding this comment.
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
|
@BYK got it. I'll switch to "minted scopes ⊆ issuer scopes − Proposal
Open question: do we cap which scopes an org auth token can hold at all? Org auth tokens aren't bound to a member.
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
left a comment
There was a problem hiding this comment.
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.
I moved the CLI scope requirements to getsentry/toolkit#1388. |
|
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.
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]>
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>
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 anorg:citoken for source map upload after an OAuth login (getsentry/toolkit#1388).These endpoints now also accept user tokens, and
OrgAuthTokenPermissionlimits that to OAuth application tokens acting for a real user:org:tokensscope. Existingorg:cigrants are not enough, so this doesn't widen what already-deployedorg:cicredentials can do. A missingorg:tokensreturns a 403 with an RFC 6750insufficient_scopechallenge, so the CLI can ask the user to re-authorize.org:tokensis token-only (inSENTRY_TOKEN_ONLY_SCOPES, likeorg: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.org:readfor list/create/rename,org:writefor delete, and the user must be a member of the org.CLI follow-up: the CLI needs to request
org:tokensandorg:readin its OAuth scopes (plusorg:writeif it wantstoken delete).Fixes #122462
Refs ENG-8458
via Junior system actor
event.--
View Junior Session in Sentry