Skip to content

feat(service-accounts): Replicate service account tokens to the cell - #130108

Merged
skaasten merged 4 commits into
masterfrom
feat/service-account-token-replica
Nov 9, 2026
Merged

skaasten merged 4 commits into
masterfrom
feat/service-account-token-replica

Conversation

@sentry-junior

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

Copy link
Copy Markdown
Contributor

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 feat(service-accounts): Replicate service account tokens through their outbox #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.

via shaun.kaasten.

--

View Session [Sentry]

@sentry-junior
sentry-junior Bot requested review from a team as code owners November 5, 2026 19:08
@sentry-junior
sentry-junior Bot added this pull request to stack #130109 November 5, 2026 19:08
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 5, 2026
@skaasten
skaasten force-pushed the feat/service-account-token-replica branch from 1091703 to 30f3c65 Compare November 5, 2026 19:25
@sentry

sentry Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Sentry Snapshot Testing

Name Added Removed Changed Renamed Unchanged Skipped Status
sentry-frontend
sentry-frontend
0 0 0 0 798 0 ✅ Unchanged

⚙️ sentry-frontend Snapshot Settings

@sentry-junior
sentry-junior Bot force-pushed the feat/service-account-token-replica branch from 30f3c65 to c636d98 Compare November 5, 2026 21:21
@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/0007_add_service_account_token_replica.py

for 0007_add_service_account_token_replica in service_accounts

--
-- Create model ServiceAccountTokenReplica
--
CREATE TABLE "service_accounts_serviceaccounttokenreplica" ("id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, "token_id" bigint NOT NULL UNIQUE, "token_hashed" text NOT NULL, "scope_list" text[] NOT NULL, "date_expires" timestamp with time zone NULL, "date_deactivated" timestamp with time zone NULL, "organization_id" bigint NOT NULL, "service_account_id" bigint NOT NULL);
ALTER TABLE "service_accounts_serviceaccounttokenreplica" ADD CONSTRAINT "service_accounts_ser_organization_id_9a9d000e_fk_sentry_or" FOREIGN KEY ("organization_id") REFERENCES "sentry_organization" ("id") DEFERRABLE INITIALLY DEFERRED NOT VALID;
ALTER TABLE "service_accounts_serviceaccounttokenreplica" VALIDATE CONSTRAINT "service_accounts_ser_organization_id_9a9d000e_fk_sentry_or";
ALTER TABLE "service_accounts_serviceaccounttokenreplica" ADD CONSTRAINT "service_accounts_ser_service_account_id_bf6d44e8_fk_service_a" FOREIGN KEY ("service_account_id") REFERENCES "service_accounts_serviceaccountreplica" ("id") DEFERRABLE INITIALLY DEFERRED NOT VALID;
ALTER TABLE "service_accounts_serviceaccounttokenreplica" VALIDATE CONSTRAINT "service_accounts_ser_service_account_id_bf6d44e8_fk_service_a";
CREATE INDEX CONCURRENTLY "service_accounts_serviceac_organization_id_9a9d000e" ON "service_accounts_serviceaccounttokenreplica" ("organization_id");
CREATE INDEX CONCURRENTLY "service_accounts_serviceac_service_account_id_bf6d44e8" ON "service_accounts_serviceaccounttokenreplica" ("service_account_id");
CREATE INDEX CONCURRENTLY "sa_token_replica_hash_idx" ON "service_accounts_serviceaccounttokenreplica" ("token_hashed");

@sentry-junior
sentry-junior Bot force-pushed the feat/service-account-token-replica branch from c636d98 to d1ae2ac Compare November 6, 2026 16:17
Base automatically changed from feat/service-account-token-models to master November 6, 2026 16:30
skaasten pushed a commit that referenced this pull request Nov 6, 2026
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. #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
(#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.

<!-- junior-request-attribution:start -->
via [automation
`evt_96f99ce311a0097e57d5a80fb82b61c7`](https://junior-prod.sentry.dev/automations/evt_96f99ce311a0097e57d5a80fb82b61c7)
· Run ID `dispatch_f7e53e47800bce9272ae0b23084ecc16`, **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>
@skaasten
skaasten force-pushed the feat/service-account-token-replica branch from d1ae2ac to 7b01216 Compare November 6, 2026 16:31
Comment thread src/sentry/service_accounts/models.py Resolved
sentry-junior Bot and others added 4 commits November 9, 2026 09:48
Makes ServiceAccountToken a ReplicatedControlModel with a new
SERVICE_ACCOUNT_TOKEN_UPDATE outbox. The outbox writes
ServiceAccountTokenReplica through
cell_replica_service.upsert_replicated_service_account_token, which the
token authenticator will read in a later PR.
…a is missing

Drop the separate Organization lookup in upsert_replicated_service_account_token.
The account replica's org foreign key cascades, so finding it already proves the
org exists. When it's missing, log and skip instead of raising, so an out-of-order
outbox can't block the org's shard.

handle_replication now builds its update from attnames, so updating a replica
no longer loads each related row (like the org) just to copy its id.
upsert_replicated_service_account_token is a new cell RPC method. Calling it in
the same deploy that defines it is unsafe, because control can process a token
outbox before every cell serves the method. Drop the token's
handle_async_replication so nothing calls the method yet; the caller follows in
a separate PR once this one is deployed.

The model stays a ReplicatedControlModel, so token outboxes are still written
and deletes still write tombstones. Without a handler the outboxes drain as
no-ops. The tests now call the RPC method directly.
Revert the switch to copying foreign key ids in the shared
handle_replication. Token replica updates load the org row again,
which is one primary-key read on a rare path, and this keeps the
change out of every other replica type.

Co-Authored-By: Shaun Kaasten <[email protected]>
@skaasten
skaasten force-pushed the feat/service-account-token-replica branch from 6bf624c to 138860e Compare November 9, 2026 14:48
@skaasten
skaasten enabled stacked auto-merge (squash) November 9, 2026 14:50
@skaasten
skaasten merged commit d979ff3 into master Nov 9, 2026
88 of 89 checks passed
@skaasten
skaasten deleted the feat/service-account-token-replica branch November 9, 2026 14:55
skaasten added a commit that referenced this pull request Nov 9, 2026
…r outbox (#130265)

Turns on replication for service account tokens.
`ServiceAccountToken.handle_async_replication` now calls
`cell_replica_service.upsert_replicated_service_account_token`, so
creating, updating or revoking a token writes its
`ServiceAccountTokenReplica` in the org's cell.

This is split from #130108 because #130108 adds that RPC method. If
control calls a cell RPC method in the same deploy that adds it, control
can call a cell that doesn't serve the method yet. **Merge and deploy
this only after #130108 is deployed everywhere.**

Until this lands, token outboxes are still written but drain without
doing anything, so any token saved in that window has no cell replica.
After this deploys, raise
`outbox_replication.service_accounts_serviceaccounttoken.replication_version`
in the options automator. That backfills the replicas for those tokens.

**Tests:** new `ServiceAccountTokenOutboxReplicationTest`, which saves
tokens through the outbox:
- creating a token writes its replica
- revoking it updates the replica's `date_deactivated`
- a missing account replica is skipped without leaving the outbox stuck

The service account, hybridcloud, backup and silo test suites pass (760
tests), and prek and mypy pass.

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

2 participants