Plan: Internal Token Issuer — a Port of canopy-identity (epic &112, stage S2)

Contents

Status

In progress

Context

ADR-085 D1–D17 decide the design and cite the CRAIG code each unit changes; its annex lists each Canopy control as retained, changed or omitted. This plan places the design in files, orders the units and fixes their tests. It re-decides nothing.

  • Units. U0 is #2689. Each later unit becomes a child issue of epic &112 on approval, with the title, weight and priority given here. Each carries its canonical doc page and a CHANGELOG.adoc == Unreleased entry, === Added unless stated. The program continues in plan Internal Token Issuer, Cut-over and Production (U17–U21); the two pages split at the switch to keep each under the plan size cap.

  • Prerequisites. S0 has merged (#2684 RolesClaimPath, crates/craig-common/src/roles_claim.rs:39; #2686; #2687).

  • Order. The contracts the switch depends on (U2, U3) land first, on today’s path. The capacity experiment (U7) gates the federation work. Concurrency (U11, U13), compromise recovery (U4) and an issuer outage (U14) are exercised as soon as their code exists.

Design

A. Placement and database

  • craig-crypto: jwk::thumbprint(&Es256PublicKey) → Kid; no code computes an RFC 7638 thumbprint today. craig-common: owner_only (ADR-085 D12’s durable writer).

  • craig-auth: actor (D3); identity::{paths, policy, jws, token, key_cache, validator, sender, assertion}; upstream (the D5 validator and the relying party, shared by the issuer and the BFFs); device_client.

  • craig-security: src/identity/ (keys/ with registry, ring and schedule; jwks, key_source, clients, issuance_log, token, subjects, sessions, device, sweep, admin). The issuer is a process mode beside the migrate gate and --print-openapi (services/craig-security/src/lib.rs:149-160), serving /identity/, /livez and /readyz, run by the compose service craig-security-issuer. The ordinary process serves /v1/security/identity/.

  • craig-bff: session_store (D6’s engine and SQL) and federation. Each BFF’s migrations live under services/craig-web/migrations/ and services/craig-portal/migrations/, joining the ADR-063 migrate gate; devstack/postgres/init.sql gains each BFF’s owner and app logins.

  • Database. ADR-085 D2 fixes the owner, both runtime logins' matrix, provisioning and the primary-key carve-outs; D13 the log’s two write paths; D16 the purges. Times come from clock_timestamp().

B. Settings (CRAIG_<SVC>__<SETTING>, validated at boot; secrets as SecretString)

Setting Read by Meaning

IDENTITY_ISSUER, IDENTITY_INTERNAL_URL

every service, both BFFs, CLI profiles

the issuer identifier, compared byte for byte with iss; the fetch URL for the JWKS and token endpoint, defaulting to the identifier

CLIENT_JWK_FILE (production) / CLIENT_JWK (devstack)

each confidential client

its assertion key (keypair_env)

IDENTITY_DATABASE_URL, IDENTITY_DB_MAX_CONNECTIONS, IDENTITY_CLIENT_KEYS_FILE

the issuer process

the issuer login; its pool (12–64, default 22); the client-key registry, with each client’s rate_limit_rpm (D17)

IDENTITY_SESSION_MAX_SECONDS, IDENTITY_NATIVE_SESSION_SECONDS, IDENTITY_TOKEN_RATE_LIMIT_RPM, IDENTITY_ADOPT_UUID_SUBJECTS_FROM

the issuer process

28800 each (1800–43200); 30 000; the legacy issuer whose UUID subs are adopted (D7)

UPSTREAM_ISSUER, _INTERNAL_URL, _CLIENT_ID, _CA_BUNDLE_FILE; BFFs also _REDIRECT_URI, _CLIENT_SECRET

the issuer process, both BFFs

the one upstream and its client craig; a bundle replacing the built-in roots; the secret only when the profile authenticates by secret

DATABASE_URL

both BFFs

the session database (D6)

C. Receivers, senders and cut-over mechanics

  • Claims. Only the validator builds Claims (test fixtures aside), and every accessor keeps its meaning. A worker token opened by craig-web or craig-portal projects as the opener’s service principal with the worker lifted: channel() and service_id() are the opener (ADR-028 #1329’s first hop) and `is_relayed() holds. A craig-cli worker token is a direct worker. A service token is a bare service principal: actor() is Actor::Service, and service_id() is its client_id, the one service encoding U3 fixes before the switch. New accessors are caller() (client_id) and act_chain(); service identity no longer comes from a service: role.

  • The portal guard (ADR-076 D3) admits a portal-role subject only when the opener is craig-portal and the path is under PORTAL_PATHS.

  • Senders. TokenSource::service(target) caches until 60 s before exp, single-flight. TokenSource::delegate(subject, target) reuses a token only within its request: RelayAuth sites become delegate, and a site feeding a cross-request cache keeps a service token (ADR-028 #1329). The BFFs mint per request. Plugin data calls (services/craig-web/src/plugins.rs) mint for their host’s receiver; an unmapped host is refused at boot.

  • Staging. U2 and U3 change today’s path deliberately. U4–U16 wire no receiver and no sender (ADR-085 D15); their docs mark the surface "not yet trusted". U17 is one branch, one compiling signed commit per step, merged once the pre-push battery passes (Canopy R26 and SW1, adr-049:3175-3179). Only tests of deleted code are deleted, each named in the MR; an invariant replaces the ADR-028 characterization test (crates/craig-auth/src/middleware.rs:1096).

Scope

Units are numbered in build order; each heading’s after list is authoritative, and gives the weight, priority and branch. Dn is an ADR-085 decision; §A–§C are the sections above.

U1 — Spike: upstream claims, refresh and auth_time (weight 2, P3-low, chore/iti-u1-spike-upstream-claims, after U0)

  • Code: nothing merges. Against the devstack Keycloak (a craig client with id.token.claim on its realm-roles mapper, which today writes the access token, not the id_token, devstack/keycloak/craig-realm.json:1568-1579) and the craigidp ZITADEL and Kanidm (cargo xtask dev multibackend-up), record per profile: roles at a RolesClaimPath; auth_time unasked and when asked as an essential claim; azp and the audience shape; whether refresh re-issues the id_token (same sub, auth_time and nonce, newer iat) and rotates the refresh token; the sub format; RP-initiated logout.

  • Tests: none. Docs: an erratum here; a profile failing D1 files a trigger-4 issue first. CHANGELOG: === Changed.

Erratum (2026-11-06): U1 spike — Keycloak 26.5.7 and ZITADEL 4.15.0 meet D1; Kanidm 1.10.1 does not (no auth_time, asked or not; trigger 4 is #2965, raising the minimum to Kanidm 1.11). Keycloak emits auth_time only through the client’s basic scope and ignores the essential request (#2966); ZITADEL 4.15 ignores max_age and prompt=login on a reused session (#2967). The per-profile table is on #2738.

U2 — Record the legacy issuer (weight 2, P3-low, feat/iti-u2-legacy-issuer, after U0)

  • Code: on today’s path, owner-owned, INSERT-only identity_legacy_issuers and its retirement records; identity_record_legacy_issuer() (EXECUTE for the app login only) and the owner-only identity_retire_legacy_issuer(); craig-security records its OIDC_ISSUER at each boot, once per distinct value, a refusal being a WARN (D7). These first identity_ functions set D2’s function rules (REVOKE ALL … FROM PUBLIC, a fixed search_path).

  • Tests: two boots record one row; a changed setting adds a second; a retirement is logged; the app login holds no table privilege on either table and cannot retire (devstack); a refused record call boots with a WARN; an invariant compares the app login’s and PUBLIC’s EXECUTE rights with D2’s matrix, which later units extend.

  • Docs: data-model-security.adoc. CHANGELOG: Ops note: every existing deployment runs this release before the switch.

U3 — The machine-actor contract and typed worker subjects (weight 8, P3-low, refactor/iti-u3-actor-contract, after U0)

  • Code: Actor and Claims::actor() (D3). worker_subject() (403 worker_required for a service) replaces parse_actor_sub (crates/craig-api/src/request_claims.rs:573-577) and its ~150 call sites in ~100 files; ActingWorker::sub() goes, its raw uses moving to actor(), worker_subject() or log_id(). The three handlers a service token reaches (services/craig-cases/src/api/reports/crud.rs:96, report_attachments.rs:136, services/craig-exchange/src/api/screening.rs:112) use actor(); their digests (request_claims.rs:113-121) hash Actor’s encoding, a worker’s bytes unchanged, with D3’s comparison for digests stored before U3 until the switch; `upload_attempts.created_by and request_claims.created_by_sub become D3 column pairs; rule_evaluations.evaluated_by, report_attachments.uploaded_by and the audit actor (actor_service) take the service encoding; craig-auth’s test support gains Claims::test_service(name), building §C’s post-switch shape.

  • Tests: a digest from today’s intake shape (service:craig-intake, a UUID sub) equals that from §C’s post-switch shape (Claims::test_service("craig-intake"), which U14 pins), so a replay across the switch returns the stored row and a changed body is 409; a row stored with today’s service digest replays after U3, for each of the three digests; a worker’s digest is byte-identical to today’s; a service on a worker-only handler is 403, never 500; the column-pair CHECKs. Docs: shared-crates.adoc. CHANGELOG: === Changed; Ops note: only a request first made before U3 and retried after the switch answers 409.

U4 — The issuer process, key registry and staged rotation (weight 5, P3-low, feat/iti-u4-issuer-process, after U2)

  • Code: the issuer process mode (D2), non-dumpable first (rustix becomes a direct dependency, process feature), with its compose service and a healthcheck on /readyz; jwk::thumbprint; the D8 migration (a stamping trigger, CHECKs including kid = thumbprint, a guard-row 64-cap, UPDATE / DELETE refused, an owner-only identity_revoke_key) with D2’s grants (the schema-check tables included), TEMPORARY revoked from PUBLIC and the issuer (the annex), the init.sql issuer and provisioning roles, and the issuer probe; keys/registry.rs; a pure keys/schedule.rs (600 s first key, then 21600 s; next insert 120 s ahead; a 5 s close margin; 1–30 s backoff; read-back after an unknown outcome; clock divergence); keys/ring.rs, holding readiness until the first sign_from, with a counter and WARN when the cap refuses an insert.

  • Tests: a thumbprint proptest (canonical under member order); devstack invariants: UPDATE / DELETE refused, supplied times overwritten, a 65th row refused, a revoked row freeing its slot, a mismatched kid refused, an over-privileged login, a craig_security_app pool and an issuer able to create a temporary table refused by the probe; U2’s EXECUTE invariant extended to the issuer login; the schedule through lost answers, refusals, a clock step and a suspend, without sleeping; two rings at the cap; cold boot: ready and publishing with no RabbitMQ, craig-rules or object store reachable; recovery: D8 in its order, each step as the role it names: the owner revokes the INSERT grant and the keys, which leave the published rows; craig_security_provisioner sets NOLOGIN, ends the connections and restores LOGIN with a new password; the owner restores the grant, and a restarted replica publishes a fresh key (a serial test group). Docs: data-model-security.adoc, services.adoc, devstack.adoc § Services and Ports, configuration-reference.adoc. CHANGELOG: Ops note with the role’s provisioning SQL.

U5 — JWKS publication (weight 2, P3-low, feat/iti-u5-jwks, after U4)

  • Code: GET /identity/jwks (D9: memo, Age, 503); key_source over the memo for subject-token checks (D2).

  • Tests: a staged key is listed before it signs and a retiring one until publish_until; a revoked key is absent; Age tracks the memo; under fault injection a failed read is 503, never an older set; 64 keys fit in 64 KiB; with two rings over one registry, ring A’s kid resolves through replica B’s source. Docs: services.adoc, security.adoc §3.

U6 — Token endpoint, client auth, service tokens, call graph, issuance log (weight 5, P3-low, feat/iti-u6-token-endpoint, after U4, U5)

  • Code: policy with the *_URL census; jws and token; clients (D11, with D17’s rate_limit_rpm), the jti store and the client-status table (D13); craig-auth’s assertion signer; issuance_log (D13) with its ADR-058 archive spec pruning through identity_prune_issuance_log; POST /identity/token with the annex’s limits through craig-api’s rate limiter and craig-common’s client_ip, first grant client_credentials plus resource; the jti sweeper (D16); cargo xtask gen-client-keys and the devstack key fixture; cargo xtask identity verify gains the issuer’s JWKS and one client-credentials mint.

  • Tests: no-panic and round-trip proptests for both layouts and the parser; the evil corpus (crates/craig-test-lib/src/evil/); one test per assertion refusal (aud, typ, exp over 60 s, a reused jti, an unknown or disabled client, an extra header, oversize); purpose subsets; a client over its budget gets 429; an unaudited mint is a 503 that releases nothing (fault injection); the census refuses an unclassified URL; the sweeper keeps a jti until its assertion can no longer be accepted, in bounded batches, and the issuer login cannot DELETE; archive, then prune.

  • Docs: idp-integration.adoc § Internal issuer, configuration-reference.adoc. CHANGELOG: Ops note.

U7 — Capacity experiment (weight 3, P3-low, test/iti-u7-capacity-experiment, after U5, U6)

  • Code: an identity profile of cargo xtask perf (Canopy P6), driven from Rust because it signs assertions with the devstack client keys: client credentials at W1’s mint rate (the stand-in until U12), JWKS fan-in, the log and key rotation; a --kill option on cargo xtask dev restart-service; a pure registry model replaying restart patterns.

  • Tests: measure C and compute R (failing only when R > 10); G1 for client credentials and G2–G8, at R and R − 1 (--replicas craig-security-issuer=<R>); a rolling restart and a killed replica keep G3; a rolling restart at R = 10 counts published keys against the model, which also shows D8’s allowance. Docs: the figures in deployment-guide.adoc § Identity capacity, and an erratum here; a failed gate stops U8 onward until ADR-085 is revised. CHANGELOG: === Added (test).

  • Erratum (2026-11-06): the disruptive, R-dependent legs (C, the gates at R and R − 1, the killed replica, the rolling restarts) are cells of cargo xtask perf --profile identity, run by hand; the battery’s requires devstack legs only read or mint. docker-compose.scale.yml lifts the issuer’s per-IP limit, because the harness is one address.

  • Erratum (2026-11-08): the run fails D17. C = 50/s gives R = 25 > 10, and at 10 replicas G1, G2, G4 and G6 fail at design, as does the killed replica’s G3. U8 onward waits on ADR-085’s revision; figures and the knee’s evidence (WAL flush on the mint path’s two commits) are in deployment-guide.adoc § Identity capacity.

U8 — Upstream validator and subjects, #2685 (weight 5, P3-low, feat/iti-u8-subjects, after U1, U2, U7)

  • Code: upstream (D5): discovery with a byte-exact issuer, the CA bundle, 2 s connect and 2.5 s request bounds with redirects refused, keys through JwksProvider, the id_token validator, D6’s renewal-evidence check and the projection; subjects: link_or_mint with D7’s adoption rule and sub bounds; identity_adoption_state and identity_soak, created empty (U17’s migration inserts); D7’s refusals and the soak refusal.

  • Tests: D5’s negative fixtures (a second aud member; a wrong azp with one audience, refused; no azp with aud exactly craig, accepted; iat over 300 s old; no auth_time; an extra header member; 16 KiB + 1); renewal (a changed iss, sub or auth_time; no auth_time; a nonce that differs or appears where the original had none; an older iat; a replayed digest answered with the current state); Entra- and Okta-shaped subs mint a UUID v7; a canonical UUID is adopted only from the adopt issuer; 256-character, non-ASCII and empty subs are refused; 8 concurrent first federations of one pair yield one subject; with a history latch row (inserted as owner), boot refuses with no recorded issuer, an adopt issuer one byte off, or two unretired issuers, and boots once one is retired; with no latch row it boots on the setting alone; partial links still adopt the rest; during the soak a pair that cannot be adopted is refused; the issuer becomes ready with the upstream unreachable; no-panic proptests for sub validation and the projection.

  • Docs: idp-integration.adoc § Subjects, data-model-security.adoc. CHANGELOG: === Added (#2685).

U9 — Federation grant and issuer sessions (weight 5, P3-low, feat/iti-u9-federation, after U8)

  • Code: sessions (D6: versioned validations; owner functions to open, renew, grace and revoke, open_session() also writing a craig-web session’s worker_identities row); identity_suspensions, read at every mint (U10 adds the writes); the federation grant (D12) and POST /identity/revoke; the session sweeper (D16); the realm gains craig, in parity with xtask/src/cmd/identity/model.rs.

  • Tests: every answer field and refusal code; renewal per D6; grace only for not_processed, once and bounded; a stale session mints nothing and a revoked one is session_ended; of two renewals racing on one version, one wins; a craig-portal federation writes no worker_identities row; the sweeper purges 30 days after the end in batches of at most 100; devstack: a real Keycloak sign-in through the portal_subject.rs driver federates. Docs: services.adoc, data-model-security.adoc.

U10 — Issuer administration (weight 5, P3-low, feat/iti-u10-administration, after U11, U12, U14)

  • Code: the seven D13 writes as owner functions and handlers (the identity_admin ruleset resource, the IP limit, the logged actor; re-link revokes the pair’s sessions), tested behind U14’s validator and mounted at U17; the owner-only break-glass functions; the app probe (D2); craig-web’s /security/identity pages (a max_age=300 step-up).

  • Tests: each write is refused inside its transaction for a suspended actor (including one lifting their own suspension), a revoked or ended session, a disabled chain client, a craig-cli actor, an auth_time over 600 s old (401 with the challenge), and a suspension committed while the request is in flight; re-link during the soak is refused; subject creation refuses nil and is logged; each break-glass function is owner-only, logged, and re-enables a disabled craig-web; the evil corpus over the routes (crates/craig-test-lib/src/evil/mod.rs:386); the pages pass CSP and CSRF. Docs: security-operations.adoc § Identity administration.

U11 — BFF sessions and single-flight renewal (weight 8, P3-low, feat/iti-u11-bff-sessions, after U8)

  • Code: each BFF’s database, logins, probe and migration (D6); session_store (the decision table, the leader, the waiters, supersede links, and D6’s constants with their compile-time asserts); federation (open, renew, revoke); the relying party (D6: the essential auth_time, 32-byte values, a constant-time state compare, the fresh_retry retry); the BFF sweep (D16). Tested against a stub issuer and a stub upstream; nothing is wired to sign-in until U17.

  • Tests: two engines over one database racing on one session present the refresh token once and both serve; a late request after the commit re-reads; a lapsed claim ends the session refresh_lost; a claim whose upstream call never happened is released; a leader whose session was superseded revokes no successor; a session bound to another upstream ends; a stub provider sending auth_time only when asked yields it; a stale-SSO answer retries once under a fresh state and a second is refused; sign-out follows supersede links; the sweep purges in bounded batches and keeps the end log 30 days. Docs: security.adoc § Sessions, devstack.adoc, deployment-guide.adoc, configuration-reference.adoc. CHANGELOG: Ops note: each BFF needs its database, logins and DATABASE_URL.

U12 — Worker tokens: actor-token minting and onward delegation (weight 3, P3-low, feat/iti-u12-worker-tokens, after U5, U9)

  • Code: the D12 grant, verifying subject tokens through U5’s key_source: the edge, the act rules, a lifetime of min(300 s, session end, the subject token’s exp), the 5 s floor; D13’s three checks; a log row naming every hop.

  • Tests: an edge mints and a non-edge is refused; delegation appends the caller; a service token, a token for another audience and a repeated actor are each refused; a search pins MAX_ACT_DEPTH; the lifetime caps; a suspended subject, and a disabled client after the memo’s 5 s, mint nothing; a token from replica A is exchanged at replica B; the identity profile gains the worker-token mix, and G1–G3 hold for it at R, or U10 and U13 onward stop until ADR-085 is revised. Docs: services.adoc.

U13 — Device grant, native sessions and the device client (weight 5, P3-low, feat/iti-u13-device-grant, after U11, U12)

  • Code: device (D12: authorization, approval bound to the approver’s session, both grants, rotation, the session’s end, the rate limits); the device and native-credential purges (D16); craig-web’s /device page (askama, CSRF, prompt=login); device_client with D12’s store.

  • Tests: approval runs through the issuer with a session federated by U9’s driver (the craig-web page’s end-to-end test lands in U17); codes expire at 600 s; authorization_pending and slow_down; approval refused when auth_time is over 600 s old or the session differs; a reused refresh credential revokes the session; of two concurrent redemptions one wins; two OS processes (the test binary re-spawned) refreshing one store present each credential once; a cancelled refresh still stores its successor; a lock held past 15 s is Busy; the modes hold under umask 000; the evil corpus over the three routes and the user-code field; no-panic and canonical-form proptests for user-code normalization; the purges remove devices and credentials 30 days after expiry or revocation, in bounded batches; CSP and CSRF. Docs: services.adoc.

U14 — Receivers: the internal validation library (weight 5, P3-low, feat/iti-u14-receivers, after U3, U5, U6)

  • Code: key_cache (D9; single-flight fetches on an owned task) and validator::InternalTokenValidator over a key source: D5 and D9’s checks, the projection to Claims and Actor, the portal guard, X-Craig-Actor refused (400).

  • Tests: no panic on arbitrary bytes; one test per refusal (alg, an extra header, typ, iss, aud, an over-long lifetime, iat over 60 s ahead, an unknown member, the wrong layout, no edge, oversize); an injected clock: fail-closed at 720 s, a debounced unknown kid, Age honoured; an issuer outage under 720 s is invisible, and receivers recover when it returns (toxiproxy); the projection table, equal to U3’s Claims::test_service for a service token; the portal-guard matrix. Docs: shared-crates.adoc.

U15 — Senders, BFF minting and the CLI client (weight 5, P3-low, feat/iti-u15-senders, after U11, U13, U14)

  • Code: sender (§C; a 6.5 s budget, a zeroizing bearer, one retry after a 401); per-request worker tokens in both BFFs; craig login --device (the one device grant since #3127) gains the device_client path, which U17 switches on.

  • Tests: service-token reuse and a re-mint at the 60 s margin; a worker token never crosses requests; not_processed is claimed only for a failed connect, 408, 425 or 429 (fault injection); a devstack device sign-in end to end, approved through a session federated by U9’s driver. Docs: cli.adoc, shared-crates.adoc.

U16 — The test token broker (weight 3, P3-low, test/iti-u16-token-broker, after U15)

  • Code: identity_broker.rs (signs a cast person in through the portal_subject.rs driver, federates as either BFF, renews each session before its freshness ends through U11’s federation, mints worker, service and craig-cli tokens, shares sessions through an owner-only file cache); tools/craig-token-broker, the devstack-only HTTP face, answering per audience with exp (JSON, unknown fields refused, a 16 KiB cap).

  • Tests (crates/craig-test-lib/tests/identity_broker_test.rs): every cast person federates, pinned subs adopted; both token kinds validate through U14; sessions are shared across processes; a revoked one is replaced once; a mint 900 s after federation succeeds through renewal.

  • Docs: testing-reference.adoc § Token broker. CHANGELOG: === Added (test).

Out of scope

  • The switch and everything after it (U17–U21): plan Internal Token Issuer, Cut-over and Production.

  • The default IdP (its own issue under epic &112); an Alpine Keycloak image; any crate shared with Canopy; bearer authentication at craig-intake-keyring. DPoP, mTLS, native re-federation, BFF row field encryption, an HSM, KMS or FIPS module (ADR-085 triggers 2, 5); a userinfo claim source unless U1 needs one (trigger 4); a second upstream (trigger 3).

Risks

  • Upstream capability. No roles or auth_time in the id_token, or no re-issue on refresh, blocks federation; U1 checks before U8. Capacity. W1 is an assumption; U7 and U12 may send the ADR back before most of the work is spent.

  • Unwired code drifts. U4–U16 serve no production traffic until U17; each unit’s tests run against the devstack issuer, so drift shows in the battery, not at the switch.

Review log

Round Vendor Resolved model Verdict

1

Anthropic

Claude Opus 5.5 (fresh subagent)

no-ship (5 blockers, folded)

2

OpenAI (maintainer-run)

GPT Astra

no-ship (16 findings, 3 corrections; folded)

Edit this page · latest