Skip to content

feat(service-accounts): Add the ServiceAccountToken model - #130103

Merged
skaasten merged 2 commits into
masterfrom
feat/service-account-token-models
Nov 6, 2026
Merged

skaasten merged 2 commits into
masterfrom
feat/service-account-token-models

Conversation

@sentry-junior

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

Copy link
Copy Markdown
Contributor

This is part 1 of the service account access tokens plan. It's the first PR in a stack:

  1. This PR: the control ServiceAccountToken model and its table.
  2. feat(service-accounts): Replicate service account tokens to the cell #130108: replicating tokens to the cell (ServiceAccountTokenReplica, the outbox and the RPC method).

Nothing creates, reads or authenticates tokens yet.

What changes

ServiceAccountToken is a plain control silo model in this PR. The next PR makes it a ReplicatedControlModel, which needs no schema change.

  • Only token_hashed (unique) and token_last_characters are stored. The plaintext is never stored.
  • Each token has its own scope_list, validated with validate_grantable_scopes. The authenticator will intersect it with the account's current scopes on every request, so narrowing the account narrows the token, but widening the account doesn't widen it.
  • date_deactivated is the token's status: NULL means active. Revoking keeps the row, like org auth tokens. There's no separate is_active boolean that could disagree with it.
  • service_account is a normal CASCADE FK. Accounts are soft-deleted (feat(service-accounts): Soft-delete service accounts #129950), so it only fires when the org is deleted.
  • organization_id is copied from the account, so the outbox and the cell replica in the next PR don't need a join.
  • created_by is always a human user. Per the plan, token management is human-only.
  • RelocationScope.Excluded: a relocated token would need a new secret anyway.
  • __repr__ leaves out the hash.

Migration service_accounts/0005 creates the table. It's new and empty, so the migration is safe to run during deploy.

Tests

  • ServiceAccountTokenTest: scope_list rejects non-grantable scopes, and the repr omits the hash.
  • tests/sentry/service_accounts, hybridcloud/tasks/test_backfill_outboxes.py, the backup coverage, invariants and snapshots tests, and db/test_silo_models.py pass locally.
  • The migration applies, reverses and reapplies cleanly, and makemigrations --check finds no changes. prek and mypy pass.

Known failures from master

  • migration drift fails on the sentry_grouprelease.new_release_id indexes.
  • 3 tests in seer/endpoints/test_organization_seer_workflow_configs.py fail.

Both fail the same way on master today.

via automation evt_96f99ce311a0097e57d5a80fb82b61c7 · Run ID dispatch_f7e53e47800bce9272ae0b23084ecc16, shaun.kaasten.

--

View Session [Sentry]

@sentry-junior
sentry-junior Bot requested review from a team as code owners November 5, 2026 18:44
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

This PR has a migration; here is the generated SQL for src/sentry/service_accounts/migrations/0006_add_service_account_tokens.py

for 0006_add_service_account_tokens in service_accounts

--
-- Create model ServiceAccountToken
--
CREATE TABLE "service_accounts_serviceaccounttoken" ("id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, "organization_id" bigint NOT NULL, "name" varchar(64) NOT NULL, "token_hashed" text NOT NULL UNIQUE, "token_last_characters" varchar(4) NOT NULL, "scope_list" text[] NOT NULL, "date_added" timestamp with time zone NOT NULL, "date_expires" timestamp with time zone NULL, "date_last_used" timestamp with time zone NULL, "date_deactivated" timestamp with time zone NULL, "created_by_id" bigint NULL, "service_account_id" bigint NOT NULL);
ALTER TABLE "service_accounts_serviceaccounttoken" ADD CONSTRAINT "service_accounts_ser_created_by_id_6180060a_fk_auth_user" FOREIGN KEY ("created_by_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED NOT VALID;
ALTER TABLE "service_accounts_serviceaccounttoken" VALIDATE CONSTRAINT "service_accounts_ser_created_by_id_6180060a_fk_auth_user";
ALTER TABLE "service_accounts_serviceaccounttoken" ADD CONSTRAINT "service_accounts_ser_service_account_id_938a4ba3_fk_service_a" FOREIGN KEY ("service_account_id") REFERENCES "service_accounts_serviceaccount" ("id") DEFERRABLE INITIALLY DEFERRED NOT VALID;
ALTER TABLE "service_accounts_serviceaccounttoken" VALIDATE CONSTRAINT "service_accounts_ser_service_account_id_938a4ba3_fk_service_a";
CREATE INDEX CONCURRENTLY "service_accounts_serviceaccounttoken_organization_id_57ab3f30" ON "service_accounts_serviceaccounttoken" ("organization_id");
CREATE INDEX CONCURRENTLY "service_accounts_serviceaccounttoken_token_hashed_36c69e9d_like" ON "service_accounts_serviceaccounttoken" ("token_hashed" text_pattern_ops);
CREATE INDEX CONCURRENTLY "service_accounts_serviceaccounttoken_created_by_id_6180060a" ON "service_accounts_serviceaccounttoken" ("created_by_id");
CREATE INDEX CONCURRENTLY "service_accounts_serviceac_service_account_id_938a4ba3" ON "service_accounts_serviceaccounttoken" ("service_account_id");

@sentry-junior
sentry-junior Bot force-pushed the feat/service-account-token-models branch from eae0d9d to 5a41f64 Compare November 5, 2026 19:08
@sentry-junior
sentry-junior Bot added this pull request to stack #130109 November 5, 2026 19:08
@sentry-junior sentry-junior Bot changed the title feat(service-accounts): Add service account token models feat(service-accounts): Add the ServiceAccountToken model Nov 5, 2026
@skaasten
skaasten force-pushed the feat/service-account-token-models branch from 5a41f64 to 9d78492 Compare November 5, 2026 19:25
Adds the control silo table for service account access tokens. Only the
hash and the last 4 characters of a token are stored. Each token has its
own scope_list, validated like the account's.

First PR of the service account access tokens plan. Nothing creates or
reads tokens yet, and replication to the cell comes in the next PR.
@sentry-junior
sentry-junior Bot force-pushed the feat/service-account-token-models branch from 9d78492 to 86cd10a Compare November 5, 2026 21:21
Comment thread src/sentry/service_accounts/models.py Resolved
Every token has last characters to show, so the column doesn't need to be
nullable. The migration hasn't shipped, so this edits it in place.
@skaasten
skaasten merged commit 988446e into master Nov 6, 2026
98 of 99 checks passed
@skaasten
skaasten deleted the feat/service-account-token-models branch November 6, 2026 16:30
skaasten added a commit that referenced this pull request Nov 9, 2026
…130108)

Part of the service account access tokens plan. This PR adds the
cell-side copy of `ServiceAccountToken` (#130103, merged) and the RPC
method that writes it. **Nothing calls the RPC method yet.**

The caller, `ServiceAccountToken.handle_async_replication`, is in
#130265, which is stacked on this PR. Per the hybrid cloud deploy rule,
the RPC method has to be deployed in every cell before anything calls
it, so **#130265 must merge only after this PR is deployed everywhere.**

Nothing creates or reads tokens yet. The authenticator comes in a later
PR and will read the replica this PR adds.

**What changes**

- `ServiceAccountToken` becomes a `ReplicatedControlModel` with a new
`SERVICE_ACCOUNT_TOKEN_UPDATE` outbox category (53), registered in
`ORGANIZATION_SCOPE` and sharded on the org like the account's outbox.
This needs no schema change. Because the model has no
`handle_async_replication` yet, its outboxes drain without doing
anything in the cell. Deletes still write tombstones.
-
`outbox_replication.service_accounts_serviceaccounttoken.replication_version`
is registered (default 0) for the backfill.
- `ServiceAccountTokenReplica` (cell) is created by migration
`service_accounts/0007`. It has:
  - an FK to `ServiceAccountReplica` and an FK to the org
  - a unique `token_id` hybrid cloud FK
  - `token_hashed`, indexed but not unique, as on `OrgAuthTokenReplica`
  - `scope_list`, `date_expires` and `date_deactivated`

The table is new and empty, so the migration is safe to run during
deploy.
- `cell_replica_service.upsert_replicated_service_account_token` is
declared on `CellReplicaService`
(`@cell_rpc_method(resolve=ByCellName())`) and fully implemented in
`DatabaseBackedCellReplicaService`:
- It looks up the account's replica and takes `organization_id` from the
token. There's no separate org lookup: the account replica's org FK
cascades, so finding it proves the org exists.
- If the account replica is missing, it logs
`service_account_token_replica.missing_service_account`, records a
`skipped` replica write and returns. It doesn't raise, so an
out-of-order message can't block the org's outbox shard.
- Otherwise it upserts the replica through the shared
`handle_replication`, unchanged. On the update path (a revoke or scope
change), that still loads the org row once to build the update.
- `RpcServiceAccountToken` and `serialize_service_account_token` are
added. `token_hashed` is `repr=False`, and the replica's `__repr__`
leaves the hash out.
- Deleting a token row in control (on org deletion) removes the replica
through the tombstone cascade on `token_id`.

**Rollout**

1. Deploy this PR. Token outboxes are written and drained as no-ops.
2. Merge and deploy #130265, which starts calling the RPC method.
3. Raise
`outbox_replication.service_accounts_serviceaccounttoken.replication_version`
in the options automator to backfill replicas for any tokens saved
between steps 1 and 2.

**Expected check warnings**

- The optional prod/dev RPC schema diff will list
`region_replica/upsert_replicated_service_account_token` as a new
method.

**Tests**

`ServiceAccountTokenReplicaServiceTest` (all silos) calls the RPC method
directly and covers:
- the outbox's scope, shard and cell
- an upsert creating the replica with every field and the account
replica link
- a revoke keeping the replica with `date_deactivated` set
- a token of a deleted (inactive) account still replicating
- a missing account replica being skipped without raising
- delete removing the replica through the tombstone cascade

Outbox-driven replication tests are in #130265.

These also pass locally (754 tests on a fresh test DB):
- `tests/sentry/service_accounts` and `tests/sentry/hybridcloud`
- `tests/sentry/backup/test_exhaustive.py`
- `tests/sentry/db/test_silo_models.py`

`makemigrations --check` finds no changes. prek and mypy pass.

**Known failure from master**

- `migration drift` fails on the `sentry_grouprelease.new_release_id`
indexes. None of the reported drift touches `service_accounts`.

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

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

--

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

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

---------

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

3 participants