Repository navigation
feat(auth): Issue service account actors from the viewer-context endpoint - #128779
Conversation
…oint The viewer-context endpoint now signs a SERVICE_ACCOUNT actor for the account instead of Seer's org-only context. Requests carrying that context authenticate as a userless credential bound to the account's org, with scopes read from the cell replica on every request, and get a new ServiceAccountAccess: every active project with open membership, otherwise only the account's linked active projects. A service-account context can't mint another account's context, and service accounts skip the release permission cache so their IDs don't share keys with API keys. Refs ENG-8829 Co-Authored-By: Shaun Kaasten <[email protected]>
…t-actor Co-Authored-By: Shaun Kaasten <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit b7b3c9e. Configure here.
OrganizationReleasesBaseEndpoint.get_projects only admitted API keys, org tokens, agents and users, so a service account got no projects and has_release_permission never passed. Admit service accounts bound to the organization. Endpoints that default to "my projects" filter by membership, which a service account never has. Treat its linked projects as its membership. Refs ENG-8829
SeerRpcViewerContextAuthentication accepted a service-account ViewerContext like Seer's own org-only one. seer-rpc methods trust their org_id argument and skip access checks, so the account's scopes, project links and active status were not enforced there. Reject service-account actors; HMAC callers are unaffected. This also covers the viewer-context endpoint, so its separate service-account check is no longer needed. Refs ENG-8829 Co-Authored-By: Shaun Kaasten <[email protected]>
| if vc is not None and vc.actor.type == ActorType.SERVICE_ACCOUNT: | ||
| service_account_auth = authenticate_service_account(vc) | ||
| if service_account_auth is None: | ||
| return None | ||
| sentry_sdk.get_isolation_scope().set_tag("viewer_context_auth", True) | ||
| sentry_sdk.get_isolation_scope().set_attribute("viewer_context_auth", True) | ||
| return (AnonymousUser(), service_account_auth) | ||
|
|
There was a problem hiding this comment.
is this needed? why do we need bound token instead of using just the viewer context?
There was a problem hiding this comment.
Made a doc outlining alternatives to use here.
Show that the release endpoints' project lookup stays limited to a service account's linked projects, including for $all, and clarify why service accounts skip the release permission cache. Refs ENG-8829
There was a problem hiding this comment.
Thanks @gricha. Answers to the three inline questions are below. I pushed cf2770f with a clarified docstring and new tests; nothing else changed.
get_projects on the releases endpoint: does this make every project visible to service accounts?
No. That check only stops the early return [] for a service account whose token is for this org. Unlike the API-key path, it doesn't set force_global_perms. The projects are still filtered by filter_projects_by_permissions through request.access, which is ServiceAccountAccess. In a closed-membership org that means the account's linked active projects only, including for $all. In an open-membership org it means every active project, which is the agreed contract and matches integration tokens. New tests: test_service_account_release_projects_are_limited_to_linked_projects, test_service_account_release_all_projects_are_limited_to_linked_projects and test_service_account_release_projects_with_open_membership. The existing test_service_account_release_permission_follows_linked_projects also asserts that an unlinked release is denied.
has_release_permission: do service accounts actually get apikey: keys?
Not today, because they skip the cache. Without the skip they would: request.user is anonymous and request.auth is set, so they'd fall into actor_id = "apikey:%s" % request.auth.entity_id. That entity_id is a service-account ID, which can match an API key ID. The old wording was unclear, so I rewrote the docstring. A service_account:<id> key would also work. I kept the skip so a change to an account's project links shows up on the next request instead of up to 60s later.
ViewerContextAuthentication: why return a bound credential instead of just using the viewer context?
I didn't change this. The identity has to reach request.auth, because Sentry builds Access from there. access.from_request sends anonymous-user requests with request.auth set to from_auth. That function (and from_rpc_auth, for silo RPC) dispatches on AuthenticatedToken.kind to build ServiceAccountAccess. If the authenticator returned nothing, the request would be unauthenticated (401). If it returned (AnonymousUser(), None), Access would be the default with no scopes. "Bound" here just means the credential is tied to the account's org, and its scopes come from the replica row read at auth time, not from the JWT. The alternative is to have from_request read the ViewerContext contextvar directly and build Access from it. That would put a second, ambient path into Access, so I'd rather keep request.auth as the single source. Happy to change it if you'd prefer that approach.
| or vc.organization_id is None | ||
| ): | ||
| return None | ||
| # The replica is a cell table. Seer only calls cell endpoints with these contexts. |
There was a problem hiding this comment.
Is service account strictly for Seer?
There was a problem hiding this comment.
No it's generic, with Seer as the first use-case.
| service_account_id: int, | ||
| organization_id: int, | ||
| scopes: Iterable[str], | ||
| has_open_membership: bool, |
There was a problem hiding this comment.
Is this inherited from organization.flags.allow_joinleave, which means that orgs with open team membership will always have this be true for all their service accounts? If this is the case, I would prefer if we make the service account configurable for whether it's open to all projects, defaulting to linked projects only.
There was a problem hiding this comment.
Yep - it's set from organization.flags.allow_joinleave) . So far we are re-using this concept instead of creating a new "all projects" switch.
There was a problem hiding this comment.
@michelletran-sentry - planning to merge this behaviour as-is and then follow-up PRs to switch over to a new "all projects" setting on the service account.
There was a problem hiding this comment.
Thanks @michelletran-sentry. Answers to your three inline comments are below. I pushed aa9f72e, which only rewords the comment in service_accounts/auth.py.
Is the service account strictly for Seer?
The account itself isn't. ServiceAccount, its scopes, its project links and ServiceAccountAccess don't depend on Seer. What is Seer-only today is getting a token: only Seer can call the viewer-context endpoint (SeerSystemViewerContextPermission), and it's the only service holding the signing key. The old comment mixed the two, so I rewrote it to give the real reason for the check, which is the silo.
Will we ever want to expand service accounts to control?
Possibly, but not in this PR. In control, authenticate_service_account() returns None because it reads the cell replica. The source ServiceAccount and ServiceAccountProject tables live in control, so a control-side path could read those directly and build Access from them. Every endpoint Seer plans to use is a cell endpoint, so I left it out. The new comment points at that route.
Open membership grants access to all projects (allow_joinleave)
Yes, it's inherited from the org. In an open-membership org, every service account reaches every active project and team, and its project links are ignored. This follows the contract already on master. The management API's projectIds help text says the links are "ignored while open membership is on, like team membership for people", and ServiceAccountProject is documented the same way.
Making this a per-account setting that defaults to linked projects changes that contract. It needs a new field on ServiceAccount and on its cell replica, migrations for both, and changes to the outbox payload, the RPC model and the API serializer and docs. I haven't made it here, because it's a design decision and not a fix to this diff. I've asked the PR requester. There are two options:
- In this PR, drop the inheritance so every account is limited to its linked projects. That needs no migration. Then add a per-account "all projects" setting in a follow-up.
- Keep the current contract here, and add the per-account setting (defaulting to linked projects) as a follow-up before Seer starts calling the endpoint.
I'm leaving this thread open until that's decided.
Adds service account ViewerContext rows to the agent-token auth matrix, so we can iterate on service account authorization endpoint by endpoint. Oracle: an owner token holding the account's scopes. The account is linked to the project in an open-membership org, so it should reach everything the owner does. User-global routes must deny it. Until service account auth lands (#128779), every row is a non-strict `xfail`. After that, rows that still don't match are listed in `SERVICE_ACCOUNT_KNOWN_GAPS` as strict `xfail`s, with the cause as the reason. A fixed row XPASSes and fails until its entry is removed. Against #128779, 36 of 261 rows are gaps: | Cause | Rows | |---|---| | Endpoint requires or stores state for `request.user` | 19 | | Control silo (SA auth is cell-only) | 12 | | 500 using an anonymous `request.user` as an actor | 3 | | Checks the caller's org role | 2 |
Behind auth.service-account-principal (default off), a service account's request.user is a ServiceAccountPrincipal instead of AnonymousUser. Off, it is anonymous, as #128779 has it. set_request_principal applies the option, so there is one place to turn it off. The principal's user_id is None and its actor is SERVICE_ACCOUNT. Its id is a ServiceAccountId that never equals an int and raises UserRequired (403, user-required) when converted to one, so no existing request.user.id call site can reach the user with the same number. The Django-level request.user stays anonymous, so session auth and web views never see the account. SentryIsAuthenticated rejects callers with no user_id; service accounts count as sudo, like org auth tokens, and get their own rate-limit bucket. The stack's shared defaults cover serializers. What's left here is per-site: team and org lookups, update_groups, ScheduledDeletion, Activity and creator attribution, saved queries, dashboards, replay has_viewed and onboarding. Creating a project calls require_user. 14 of the 36 known service-account gaps in the auth matrix now match the oracle, and 5 human-only routes assert user-required instead.
Behind auth.service-account-principal (default off), a service account's request.user is a ServiceAccountPrincipal instead of AnonymousUser. Off, it is anonymous, as #128779 has it. set_request_principal applies the option, so there is one place to turn it off. The principal's user_id is None and its actor is SERVICE_ACCOUNT. Its id is a ServiceAccountId that never equals an int and raises UserRequired (403, user-required) when converted to one, so no request.user.id call site can reach the user with the same number. The Django-level request.user stays anonymous, so session auth and web views never see the account. SentryIsAuthenticated rejects callers with no user_id, sudo checks don't treat service accounts as sudo, they get their own rate-limit bucket, and UserRequired passes through RPC as an API error. The auth matrix runs with the option on. Rows that don't match the oracle yet are strict xfails, so the PRs that fix them have to remove them.
Behind auth.service-account-principal (default off), a service account's request.user is a ServiceAccountPrincipal instead of AnonymousUser. Off, it is anonymous, as #128779 has it. set_request_principal applies the option, so there is one place to turn it off. The principal's user_id is None and its actor is SERVICE_ACCOUNT. Its id is a ServiceAccountId that never equals an int and raises UserRequired (403, user-required) when converted to one, so no request.user.id call site can reach the user with the same number. The Django-level request.user stays anonymous, so session auth and web views never see the account. Sudo checks don't treat service accounts as sudo, they get their own rate-limit bucket, and UserRequired passes through RPC as an API error. The auth matrix runs with the option on. Rows that don't match the oracle yet are strict xfails, so the PRs that fix them have to remove them.
Behind auth.service-account-principal (default off), a service account's request.user is a ServiceAccountPrincipal instead of AnonymousUser. Off, it is anonymous, as #128779 has it. set_request_principal applies the option, so there is one place to turn it off. The principal's user_id is None and its actor is SERVICE_ACCOUNT. Its id is a ServiceAccountId that never equals an int and raises UserRequired (403, user-required) when converted to one, so no request.user.id call site can reach the user with the same number. The Django-level request.user stays anonymous, so session auth and web views never see the account. Sudo checks don't treat service accounts as sudo, they get their own rate-limit bucket, and UserRequired passes through RPC as an API error. The auth matrix runs with the option on. Rows that don't match the oracle yet are strict xfails, so the PRs that fix them have to remove them.
Behind auth.service-account-principal (default off), a service account's request.user is a ServiceAccountPrincipal instead of AnonymousUser. Off, it is anonymous, as #128779 has it. set_request_principal applies the option, so there is one place to turn it off. The principal's user_id is None and its actor is SERVICE_ACCOUNT. Its id is a ServiceAccountId that never equals an int and raises UserRequired (403, user-required) when converted to one, so no request.user.id call site can reach the user with the same number. The Django-level request.user stays anonymous, so session auth and web views never see the account. Sudo checks don't treat service accounts as sudo, they get their own rate-limit bucket, and UserRequired passes through RPC as an API error. The auth matrix runs with the option on. Rows that don't match the oracle yet are strict xfails, so the PRs that fix them have to remove them.
) On a DRF request, a service account's `request.user` is a `ServiceAccountPrincipal` instead of `AnonymousUser`. Service accounts are gated by `organizations:service-accounts`, which is now checked at authentication too (`authenticate_service_account`), so that flag is the one switch. Before, only service-account creation and the token endpoint checked it, and anything holding the shared secret could sign a service-account viewer context. The principal has no user, so `has_user()` is False and `acting_user_id()` is None, and its actor is `SERVICE_ACCOUNT`. Its `id` is a `ServiceAccountId` that never equals an int and raises `UserRequired` (403 `user-required`) when converted to one, so no `request.user.id` call site can reach the user with the same number. **Temporary:** `ServiceAccountId` is a runtime guard, because about 490 `request.user.id` reads still assume a user. It's deleted, along with the RPC pass-through for `UserRequired`, once mypy types `request.user` to include `ServiceAccountPrincipal` (plugin, shrinking per-module allowlist) and those reads are migrated. This PR sits right above the chokepoint on purpose: every PR after it is written and tested against the real principal. Endpoints aren't blocked up front. What breaks for a service account shows up in the auth matrix, and the PRs above fix it or mark the endpoint `requires_user`. What else this changes: - **Web views:** `set_request_principal` sets a service account only on a DRF `Request` (its setter also copies it to Django's `request.user`). Until DRF authenticates it, Django's `request.user` is anonymous, and session auth never sees it, since `ViewerContextAuthentication` runs before `SessionAuthentication`. The check reads the credential (`is_service_account_auth(auth)`), not `isinstance(user, ...)`: the middleware passes Django's lazy user, and loading it reads the session, which adds `Vary: Cookie` to every response. `test_leaves_lazy_user_unloaded` guards it. - **Access:** `SentryPermission.determine_access` asks `has_user()` and `acting_user_id()`, so a service account keeps the credential-based access (`from_rpc_auth`) it had as `AnonymousUser`, instead of its `ServiceAccountId` reaching the org lookup. - **Sudo:** neither the decorator nor the sudo middleware treats a service account as sudo; both ask `has_user()` before `has_usable_password()`. Sudo re-authenticates a person, so `require_sudo()` answers a caller with no user with a 403 `user-required` instead of a sudo prompt, from `@sudo_required` and from project delete. Org, team and project delete and project transfer stay user-only. - **Rate limits:** service accounts get their own bucket. - **RPC:** `UserRequired` passes through as an API error. The auth matrix enables the flag for its service-account rows and records what still fails at this point in the stack. Rows that don't match the oracle are strict xfails, so the PR that fixes a row has to remove it. At this point 89 service-account rows are known gaps: 28 audit actors, 21 per-user serializer lookups, 20 `request.user.id` reads, 2 `serialize_generic_user`, 1 project creation that needs `require_user`, 12 control-silo endpoints and 5 that check the caller's own membership or org role. The PRs above remove them. At the top of the stack, 17 remain: the control-silo and membership ones. This replaces #128983, split per review. It builds on #128779, now landed. **Stack** (each PR is based on the one above it): 1. #128982 Shared `request.user` interface 2. #129133 Set `request.user` / `request.auth` through one helper 3. #129146 Service accounts on `request.user` 4. #129136 `has_user()` in access, org lookups and `users/me` 5. #129143 `requires_user` / `require_user()` 6. #129144 Lints for patterns that break for a service account 7. #129154 Orgs, teams, projects 8. #129155 Issues 9. #129149 Discover, Explore 10. #129156 Dashboards 11. #129150 Workflow engine 12. #129151 Replays 13. #129152 Preprod 14. #129153 Remaining endpoints 15. #129253 Audit entries 16. #129254 Per-user serializer lookups 17. #129255 `serialize_generic_user` 18. #129256 Flagpole user context

The viewer-context endpoint now signs a typed
(service_account, id)ViewerContext instead of Seer's org-only one, and Sentry can authenticate requests that carry it (service accounts design, step 6).ViewerContextAuthenticationsends service-account contexts toauthenticate_service_account()before the user path, which resolves the active account from its cell replica on every request.request.userstays anonymous;request.authis anAuthenticatedTokenwithkind="service_account"and the account's current scopes, so narrowing, disabling or deleting an account applies to already-issued tokens once it replicates.ServiceAccountAccesslimits the account to its org and scopes. Open-membership orgs grant every active project and team; otherwise only linked active projects and no teams. Those projects also count as its "member" projects, so default project lookups and release endpoints return them.SeerRpcViewerContextAuthenticationrejects service-account contexts. seer-rpc methods trust theirorg_idargument and skip access checks, so accepting them would bypass the account's scopes, project links and disabled state. This also stops one account from getting a context for another through the viewer-context endpoint.apikey:keys with API keys.Nothing calls the endpoint yet. No seed or backfill is needed, but an account must exist and replicate before Seer can request its context. Builds on #128718 (merged), which keeps the actor intact when Sentry calls Seer.
Follow-ups: rate limits are still per IP rather than per account, and holders of the shared signing key can still sign these contexts directly (ENG-8830).
Refs ENG-8829
via shaun.kaasten.
--
View Junior Session [Sentry]