IdP Integration
Overview
CRAIG is IdP-neutral over the set of OIDC backends that implement the client_credentials grant. Any conforming issuer can authenticate CRAIG users and (since Plan E) issue per-service client_credentials tokens for service-to-service auth. The codebase contains no IdP-vendor-specific logic: endpoints are resolved at boot via the OIDC discovery doc (<issuer>/.well-known/openid-configuration), and inbound bearer-token validation runs via one of two strategies (ADR-029):
-
Local JWS validation:
craig-auth::JwksProviderdecodes the bearer (a JWS, JSON Web Signature, token) locally against the issuer’s JWKS (JSON Web Key Set). Fast (~10µs) and resilient to short IdP outages; the default path for JWS-issuing backends. -
RFC 7662 introspection:
craig-auth::IntrospectionClientPOSTs the bearer to the issuer’s introspection endpoint and caches the claims (DashMap, SHA-256-hashed keys, configurable TTL). This is the required path for backends that issue JWE-encrypted (JSON Web Encryption) or opaque access tokens: Kanidm by default, ZITADEL’s opaque default, Keycloak lightweight tokens, and authentik’s encrypted mode.
Per-service env var CRAIG_<SVC>__TOKEN_VALIDATION_MODE selects the strategy: jws / introspect / auto (default). Auto dispatches on token shape: 3 segments → JWS, 5 segments → JWE-via-introspection, no dots → opaque-via-introspection. Plan F (docs/modules/ROOT/pages/plans/introspection-validation-mode.adoc) shipped the introspection path across 6 step MRs (!269–!274).
|
Plan E (service identity) made the |
Tested backends (JWS or introspection-validating):
| Backend | Mode | IaC adapter | Notes |
|---|---|---|---|
Keycloak |
JWS |
|
Devstack reference; production-tested with the full E2E suite green. Supports "lightweight access tokens" (opaque) per Plan F’s introspection path. |
authentik |
JWS |
|
Verified end-to-end against Authentik 2026.2.2 (!266). Rendered blueprint imports cleanly; full |
ZITADEL |
JWS (with |
|
Verified structurally against ZITADEL 4.15.0 (!268). Renderer pins JWT type on machine users. ZITADEL’s default opaque-token mode works under Plan F’s |
Kanidm |
Introspection only |
|
Kanidm 1.11 or later. Kanidm 1.10 never puts |
To run the multi-backend integration tests:
cargo xtask dev multibackend-up
cargo xtask dev zitadel-bootstrap # the two full-mint legs fail loud without these
cargo xtask dev kanidm-bootstrap
cargo nextest run -p craig-test-lib --profile identity-multibackend --run-ignored only
cargo xtask dev multibackend-down
Or in one command, which CI runs (#2641): cargo xtask identity matrix. It removes any earlier craigidp
project with its volumes, brings it up and waits for every healthcheck, runs both bootstraps, then the profile with
--no-tests=fail. On a failure it keeps the IdP containers' logs in test-results/container-logs/, and on every
outcome it removes the project again, volumes included, so it also wipes local IdP state. The identity-multibackend CI
job runs it on every schedule (the weekly one, #2651). On a merge train it runs, and blocks, when identity code changes: craig-auth,
craig-security’s identity module, craig-bff’s oidc.rs, the Keycloak, ZITADEL, Kanidm and authentik devstack inputs,
docker-compose.idp.yml or this page. On a plain MR it is then a manual job
(testing-reference § CI stages). The devstack’s Kanidm
1.10 pin, current when #2641 added this job, failed ADR-085 D1; #2965
resolved that by moving it to 1.11.2. The plane’s Kanidm legs are client_credentials tests, so neither version changes
what they assert.
Untested but expected to work given OIDC conformance:
-
Okta, Azure AD / Entra ID, ForgeRock, PingFederate, Auth0, custom OIDC providers.
For backends without a render adapter, the operator configures the backend in whatever tooling they already use (Terraform, Helm, Pulumi, the console); the contract below is the spec to satisfy.
Required IdP Configuration
Realm / Tenant
A single realm or tenant containing the CRAIG worker identities. CRAIG does not provision users — operators integrate with whatever directory the agency already uses (Active Directory, LDAP, SAML federation, social login).
Clients
CRAIG needs three user-facing OIDC clients in the realm (plus one client_credentials client per service — see
Reference IaC below; the portal BFF craig-portal is one of those, with audience mappers for craig-placement and
craig-financial only and no self-audience, since nothing calls the portal):
| Client | Flow | Use |
|---|---|---|
|
Authorization Code + PKCE (Proof Key for Code Exchange) |
Web UI (craig-web BFF). Public client; no client secret. Redirect URI: |
|
Authorization Code + PKCE |
The self-service portals (the |
|
Resource Owner Password Credentials (transitional) |
CLI clients, integration tests, and (pre-Plan-E) service-to-service auth. Public client with direct access grants (per the realm JSON). Plan E retires this in favor of per-service |
On Keycloak, every sign-in (authorization-code) client keeps the built-in basic scope among its default client
scopes: today craig-ui and craig-portal-ui, and the craig client that the internal token issuer adds
(ADR-085). Without basic, the id_token carries no auth_time; see
Keycloak: keep the basic scope for auth_time.
Claims & Scopes
CRAIG expects the access token to carry:
| Claim | Notes |
|---|---|
|
Stable user UUID. Used as the worker identity for all data writes. An IdP whose |
|
Human-readable username; rendered in the web UI. |
|
Optional; populated into |
|
Optional full name (the |
the roles claim, at |
RBAC roles, read at one configured path; see The roles claim per IdP. |
|
Multi-valued array of service names. CRAIG validates that the token’s audience contains the target service ( |
|
When present, must be |
The roles claim per IdP
CRAIG_IDENTITY_ROLES_CLAIM_PATH names where a token carries its roles (#2684). It is one fleet-wide setting: set the
same value on every service, craig-web and craig-portal. The JWS path (the verified payload) and the RFC 7662 path (the
introspection body) read it through the same reader, so a token yields the same roles whichever way it is validated.
The value is dot-separated claim names, one claim name per segment: realm_access.roles, groups,
urn:zitadel:iam:org:project:roles. A claim name that itself contains a ., such as an Auth0 namespaced claim
https://example.com/roles, cannot be addressed; map the roles to a claim name without a dot. A malformed value
refuses boot: an empty path, an empty segment (a..b), RFC 6901 pointer syntax (/realm_access/roles), a segment with
surrounding whitespace or a control character, and a segment starting with $ (JSONPath).
What CRAIG reads at the path:
| At the path | Result |
|---|---|
An array of strings |
Those roles. |
An object |
Its keys (ZITADEL’s |
Absent, or |
Zero roles. The token is accepted with no roles. |
Any other type, a non-string array element, or a segment name that appears twice in one object |
The token is refused (401). |
Actor tokens (X-Craig-Actor) always use realm_access.roles, never this setting: CRAIG mints them itself, in its own
wire format.
| IdP | CRAIG_IDENTITY_ROLES_CLAIM_PATH |
Source |
|---|---|---|
Keycloak |
|
The realm-roles mapper. |
authentik |
|
The |
Okta |
|
A groups claim on the authorization server, filtered to the CRAIG groups. |
Entra ID |
|
App roles. Entra also puts them on client-credentials tokens for service principals. |
Auth0 |
a claim name without a |
An Action that sets the roles on that claim. A namespaced URL claim cannot be addressed. |
Kanidm |
none today |
Not carried in Kanidm access tokens or introspection today (#2690, #2688). |
ZITADEL |
|
Project roles. CRAIG reads the object’s keys. |
Only the Keycloak row runs in the devstack. The others follow each IdP’s documentation: their claim carriage, and the
service:* roles on their client-credentials tokens, are unverified until the live per-IdP suite (#2688) runs.
A path that names the wrong claim yields zero roles, by the rules above. A worker then meets craig-web’s
bff-admit-worker-only refusal and every role-gated backend call is refused; check CRAIG_IDENTITY_ROLES_CLAIM_PATH
first.
|
Roles outside CRAIG’s vocabularies (#2518). A stock realm grants every account its default-roles-<realm> composite
(offline_access, uma_authorization), and other IdPs add defaults of their own. CRAIG ignores any realm role that is in
neither craig_auth::REALM_ROLES nor craig_auth::PORTAL_REALM_ROLES wherever it counts roles: both BFFs' audience
gates, the fleet guard’s portal-principal rule, and craig-web’s sole-readonly write guard. Such a role can neither admit
nor refuse an account, and a readonly worker carrying it is still write-guarded. The one exception is a service: role
on a relayed portal subject, which the fleet guard still refuses.
CRAIG’s 9 RBAC roles: 6 operational roles — admin, supervisor, caseworker, eligibility_worker, icpc_coordinator, readonly — plus 3 office-authority roles — county_director, regional_director, state_office (the ADR-054 subsidy approval matrix axis; office principals also hold a base operational role). The operational roles are inputs to JDM decision tables (each jurisdiction layer’s <jurisdiction>-authz-<resource>.json), so an operator can extend or reshape the role model via ruleset edits without touching CRAIG source; the approval matrix authorizes on the office axis.
CRAIG-specific OAuth2 scopes
Per RFC 6749, scopes are space-separated identifiers in the scope claim. CRAIG enforces them via Claims::require_scope as an additive gate on top of role checks — RBAC decides what a principal can do, scope narrows which clients may do it. The catalogue is intentionally tight: most authorization is role-driven, and a new scope is added only when a single client should be the sole legitimate caller of an endpoint.
| Scope | Assigned to | Enforced at |
|---|---|---|
|
|
|
Operators replacing the devstack Keycloak realm with another IdP must mint partners.replay-check on the equivalent of craig-intake’s `client_credentials flow. Devstack provisions it via devstack/keycloak/craig-realm.json (clientScopes array + defaultClientScopes on the craig-intake client); see ADR-028 for the underlying identity model.
CRAIG’s standard scopes inherited from Keycloak (profile, email, roles, acr, basic, web-origins) are mirrored from the master realm via defaultDefaultClientScopes so the existing claim shape is preserved alongside the new catalogue.
Keycloak: keep the basic scope for auth_time
From Keycloak 25, the id_token’s auth_time comes only from the session-note mapper (AUTH_TIME to auth_time) in
the built-in basic client scope. Remove basic from a client’s default scopes and auth_time disappears from its
id_token. It stays absent even when the sign-in requests it as an essential claim
(claims={"id_token":{"auth_time":{"essential":true}}}), although discovery advertises
claims_parameter_supported: true. This was observed on Keycloak 26.5.7 in the #2738 spike. ADR-085 D1 refuses an
upstream id_token without auth_time, so on Keycloak:
-
basicMUST be a default client scope on every sign-in client:craig-ui,craig-portal-uiand ADR-085’scraigclient. An optional client scope is not enough, because CRAIG does not requestbasic; -
the
basicscope MUST keep itsauth_timemapper with Add to ID token on.
The devstack realm grants basic through defaultDefaultClientScopes, which its sign-in clients inherit. The Keycloak
render (Reference IaC) names the same six scopes on each sign-in client’s defaultClientScopes. A render merged into
a realm whose defaults were trimmed therefore still keeps basic. Unit tests in
xtask/src/cmd/identity/render/keycloak.rs fail when either side loses basic on a sign-in client, or when the
realm’s basic scope loses its auth_time mapper. These tests are static: they read the files and need no running
Keycloak. The live check, that a real sign-in’s id_token carries auth_time, belongs to the identity-multibackend
conformance job (#2641). cargo xtask identity verify does not check it.
Audience Mappers
Configure each client to emit a multi-valued aud claim naming every backend its tokens are presented to (the
identity model’s worker_audiences / service_audiences / PORTAL_AUDIENCES):
-
worker clients (
craig-ui,craig-api):craig-rules,craig-cases,craig-placement,craig-exchange,craig-financial,craig-reporting,craig-security,craig-intake,craig-composition; -
service clients: the same nine plus
craig-web; -
the portal clients (
craig-portal-uiand thecraig-portalBFF):craig-placementandcraig-financialonly. No token namescraig-portal.
This prevents cross-realm token reuse without burdening operators with per-service tokens (RBAC remains the authorization boundary; audience is defense-in-depth).
Portal principals
The portal roles (foster_parent, family, provider — craig_auth::PORTAL_REALM_ROLES) and the worker roles
(craig_auth::REALM_ROLES) are disjoint per account, not only as vocabularies (the vocabulary split is
ADR-076 D1; the per-account rule is #1858). One IdP account holds roles from one
set or the other, never both. A person who is both a worker and a caregiver, such as a caseworker who is also a licensed
foster parent, has two accounts.
What an account holding both sets meets:
-
The portal refuses it and tells it to use a separate portal account (
portal-admit-dual-role, #2371). craig-portal mints a session only for a principal with a portal role and no worker role. The fleet guard accepts a relayed subject only when it holds a portal role and no worker orservice:role (ADR-076 D3 rule iii). -
craig-web refuses it. craig-web mints a session only for a principal with a worker role and no portal role (#1842, #2371), answering
bff-admit-dual-role, and drops a session whose refreshed roles gain one. So a mixed account works under neither outbound identity. Do not provision one.
cargo xtask identity render refuses to seed a dev user declared with roles from both sets, and names each one. A unit
test holds the committed devstack realm to the same rule.
A worker who becomes a caregiver:
-
Leave the worker account unchanged. Never add a portal role to it.
-
Give the person a second account in the same realm, under their personal email, never the agency address that the worker account carries (Keycloak refuses two accounts on one email by default). The account holds the one portal role the caregiving relationship needs (
foster_parentfor a foster home or a kinship household) and no worker role. It is created by staff or self-registered, whichever provisioning the deployment uses (ADR-076 open question R6). -
Bind it like any caregiver. Staff open a caregiver binding for the person on the foster home or kinship household and issue a portal invitation on that binding. The person redeems it signed in as the new account, which enrols that account as the person’s caregiver identity (ADR-076 D5). Authority comes only from that binding; the role only routes.
-
The two accounts have separate lifecycles. Ending the binding or revoking the caregiver identity on craig-placement leaves the worker account untouched, and disabling the worker account leaves the caregiver account untouched.
CRAIG-Side Configuration
Every CRAIG service reads these env vars:
| Variable | Value |
|---|---|
|
Public issuer URL, e.g. |
|
Internal URL for split-DNS deployments (Docker / k8s). When set, CRAIG fetches the discovery doc + JWKS via this URL and rewrites the doc’s |
|
Where tokens carry their roles (The roles claim per IdP). The same value on every service and both BFFs (craig-web,
craig-portal); no service prefix. Optional — defaults to |
At boot, each service:
-
Builds an
OidcDiscoveryclient pointing at the issuer (and internal URL if split-DNS). -
Fetches
<issuer>/.well-known/openid-configurationand caches the four endpoints CRAIG consumes:jwks_uri,token_endpoint,authorization_endpoint,end_session_endpoint. -
Fetches the JWKS from
jwks_uriand starts a background refresh task (default TTL 1h). An RSA key under 2048 bits is refused as the set loads (#2687): it is never cached or used, a warn names itskid, and a token naming it is refused (401, bodyinvalid token) while the set’s other keys keep working. Rotate such a key to 2048 bits or more. A key of a type CRAIG’s JWT library does not model (an unknownktysuch as a post-quantumAKPkey, ECsecp256k1, OKPEd448orX25519, an RSA key with noe) is skipped the same way, with the warn reasonkey type is not supported for JWS verification: the set still loads and its RSA, EC P-256 / P-384 and Ed25519 keys verify, so an issuer may publish such a key beside its signing key (#2695). Sign CRAIG’s tokens with one of the supported key types. Additionally (#981), a bearer whosekidmisses the key cache triggers ONE on-demand refresh-and-revalidate, single-flight across concurrent requests and bounded by a 30s cooldown that also covers failed attempts. Normal IdP signing-key rotation is therefore picked up immediately instead of failing fresh tokens until the next periodic refresh. Every other rejection class (signature,exp,iss,aud,azp,typ, missingkid) never triggers IdP traffic, and a failed on-demand refresh still rejects the token (fail-closed). -
Spawns a per-instance authz cache invalidation subscriber that listens for
ruleset.changed.*events from craig-rules.
If the discovery doc fetch fails at boot, CRAIG retries with exponential backoff (250ms → 4s, ~7.75s budget). A post-boot warm-up task (spawn_post_boot_warmup) retries bulk_refresh 20× × 1s after axum starts serving so a slow IdP startup doesn’t permanently brick the service.
Logout and a discovery outage (#2582). Both BFFs clear the CRAIG session cookies first, then end the IdP session
through end_session_endpoint (RP-initiated logout, with id_token_hint). An IdP whose discovery document has no
end_session_endpoint gets a direct redirect to the post-logout URL, as before. When discovery itself fails (the IdP
unreachable, a 5xx), the BFF does not redirect: it logs a warning and answers a page, in the request locale, saying the
sign-in service could not be reached and asking the worker to close every browser window. A silent redirect would
leave the `IdP’s session alive, so the next "Sign in" in that browser would resume the same worker with no password.
Signing out after an audience refusal (#2519). A refused callback mints no session, but the IdP’s SSO session
survives it, so the next sign-in would be refused again with no password asked. The refusal page therefore keeps the
reason and links the host’s `/logout: the same RP-initiated logout as above, returning to the host’s landing page
(/welcome). The refused callback kept no id_token, so the end-session request carries client_id without
id_token_hint, and the IdP may show a logout confirmation (Keycloak 26 does) before it redirects back.
BFF login
The two BFFs, craig-web and craig-portal, verify both tokens the token endpoint returns before they mint a session (#813, #2686):
-
The id_token is always a JWS, verified against the JWKS: signature, issuer,
exp, audience andazp= the login client,typ: ID, the loginnonce, and theat_hashbinding when present. OIDC Core requires a signed id_token; a nested-JWE id_token is not supported. -
The access token goes through the services' validation strategy, the same
ClaimsExtractordispatch every service builds (craig_auth::extractor_for). A JWS is verified locally against the JWKS. An opaque or JWE token is sent to the IdP’s RFC 7662 introspection endpoint, authenticated as the BFF’s own confidential client (HTTP Basic). Both forms are held toazp= the login client, so another client’s token for the same user is refused, and neither checks an audience, since a BFF is never in an access token’saud. The roles come from the configured roles claim (The roles claim per IdP) on both paths. -
The mode is
CRAIG_WEBTOKEN_VALIDATION_MODE/CRAIG_PORTALTOKEN_VALIDATION_MODE:jws,introspectorauto(the default), with the same meaning as a service’sCRAIG_<SVC>__TOKEN_VALIDATION_MODE. Underautoa Keycloak JWS login makes no introspection call. -
The introspection principal is required under
autoandintrospect. craig-web usesCRAIG_WEBCLIENT_ID/CRAIG_WEBCLIENT_SECRETand refuses to boot without both, naming them; pinCRAIG_WEBTOKEN_VALIDATION_MODE=jwsto boot without. craig-portal’sCRAIG_PORTALCLIENT_ID/CRAIG_PORTAL__CLIENT_SECRETare required anyway.
Refresh. A session holding a refresh token rotates its token pair when the access token is within 90 seconds of
expiry. For a JWS the BFF
reads the token’s own exp. An opaque or JWE token has no readable exp, so the BFF records the token endpoint’s
expires_in (RFC 6749 §5.1) as the expiry when it mints the session and again on every rotation. A refreshed access
token goes through the same extractor before it is adopted.
Introspection-mode tuning
Plan F (ADR-029) added five per-service knobs for operators running Kanidm / ZITADEL-opaque / authentik-encrypted / Keycloak-lightweight-token deployments where CRAIG_<SVC>__TOKEN_VALIDATION_MODE resolves to introspect. All carry sensible defaults; operators only override when tuning latency vs. revocation-staleness, sizing memory, or shifting availability posture.
| Variable | Default | When to override |
|---|---|---|
|
(auto-discovered) |
Set explicitly when the IdP exposes a non-standard introspection path or runs on a separate host from the OIDC issuer. |
|
|
Switch to |
|
|
Raise (e.g. |
|
|
Raise for high-cardinality bearer populations (many concurrent active sessions across the 9 API services); lower for memory-constrained pods. Hard cap that triggers a clear when exceeded — not an LRU. |
|
|
Set |
All five knobs default to values appropriate for a Keycloak-style deployment with sub-second introspection latency + sub-10000 concurrent sessions. Kanidm + ZITADEL operators with higher-latency endpoints typically raise INTROSPECTION_CACHE_TTL_SECONDS to 120-300. See ADR-029 for the underlying cache-design rationale.
|
Common Deployment Topologies
Docker Compose (devstack)
The default docker-compose.yml ships Keycloak as a reference IdP. Two URLs differ:
-
Public issuer (in JWT
issclaims):http://host.docker.internal:<ephemeral_port>/realms/craig -
Internal fetch URL (Docker-network):
http://keycloak:8080/realms/craig
The split-DNS rewriter in OidcDiscovery::refresh swaps the host portion of jwks_uri and token_endpoint from the public URL to the internal URL automatically. No operator action required.
Kubernetes
For k8s deployments behind an ingress:
-
Public issuer:
https://idp.your-deployment.gov/realms/craig -
Internal fetch URL (cluster DNS):
http://keycloak.identity.svc.cluster.local:8080/realms/craig
Set CRAIG_<SVC>__OIDC_INTERNAL_URL to the internal URL on every CRAIG service deployment. CRAIG validates JWT iss claims against the public URL but reaches the IdP for discovery + JWKS via cluster DNS.
Production (external IdP)
If your agency already runs Okta, Azure AD/Entra, Keycloak, ForgeRock, or any other OIDC provider:
-
Create the
craig-uiandcraig-apiclients per the Required IdP Configuration section above. -
Configure the realm to emit the audience mappers.
-
Set
CRAIG_<SVC>__OIDC_ISSUERon each service to your IdP’s public issuer URL. -
(Optional) Set
CRAIG_<SVC>__OIDC_INTERNAL_URLif your service-to-IdP path differs from the public URL. -
Run
cargo xtask identity verify --issuer <url>to conformance-check the IdP against CRAIG’s contract before going live.
No code changes in CRAIG itself.
Conformance Test
cargo xtask identity verify --issuer <url> (shipped in Plan E Step 12) exercises:
-
Fetch
<issuer>/.well-known/openid-configuration(a trailing/on the issuer is trimmed to build this URL) and verify that itsissuerequals the configured issuer byte for byte (OpenID Connect Discovery 1.0 §4.3, #2655). An absent issuer, or any difference (a trailing slash included), is a failure. Services compare a token’sisswith theirOIDC_ISSUERbyte for byte, so pass the value they are configured with. -
Verify the three required endpoints (
authorization_endpoint,token_endpoint,jwks_uri);end_session_endpointis optional and not checked. -
Fetch the JWKS and parse it; confirm at least one signing key is present.
-
(Optional, when
--client-id/--client-secretorCRAIG_IDENTITY_TEST_CLIENT_ID/CRAIG_IDENTITY_TEST_CLIENT_SECRETare set) Attempt aclient_credentialsgrant against a configured test service principal and validate the response token shape (non-emptyaccess_token,token_typematchesBearercase-insensitively).
Each check reports pass/fail. Three outcome variants:
-
AllPass— every check ran and passed; exit 0. -
Failures(…)— one or more contract failures; exit 1 with per-check diagnostics. A discovery document that answers non-2xx or does not parse is one: the IdP answered, wrongly. -
Inconclusive(…)— the discovery document gave no HTTP answer (connection refused, DNS failure, timeout, TLS), so no check could decide; exit 2 (#2691). A gate fails on any non-zero code; 2 tells "could not reach the IdP" from "the IdP is non-conformant".
A configuration error also exits 1: no issuer, or an issuer that is not an http:///https:// URL with a host or that carries credentials (user:password@), refused before any request so no diagnostic can echo it.
Read-only — no mutation. Safe in dev, CI, and production deploy gating. What runs where (#2656): cargo xtask validate does not run identity verify (its soft step could never fail and was deleted); the battery’s authenticated tests exercise the devstack realm. A deployment runs cargo xtask identity verify --issuer <url> against its own IdP before going live; no CRAIG CI job runs it.
Reference IaC
cargo xtask identity render --backend <name> [--out <path>] [--production] (shipped in Plan E Step 13) emits IaC fragments for supported backends. Pure code generation — no network, no mutation.
-
--backend keycloak [--out realm.json]— Keycloak realm definition with 9 worker roles + 3 portal roles (ADR-076), 11 service:* realm roles (one per service, craig-composition, craig-web and craig-portal included), 14 OIDC clients (craig-ui, craig-portal-ui, craig-api, 11 service-account), each client’s audience set as custom-audience mappers and its access-token lifespan (1800 s;craig-portal-ui300 s), the sign-in clients' default client scopes withbasicamong them (Keycloak: keep thebasicscope forauth_time), and 11service-account-<svc>users (serviceAccountClientId), which carry each service’sservice:<svc>role — Keycloak’s client representation has no role-grant field, so the grant rides the user, as in the devstack realm. Parity with the devstack realm: see Devstack realm and the identity model below. Feed tokc.sh importor merge into a Keycloak Operator CR / Helm chart / Terraform Keycloak provider. -
--backend authentik [--out blueprint.yaml]— Authentik blueprint covering the same canonical shape:authentik_core.groupfor each role +authentik_providers_oauth2.oauth2provider+ linkedauthentik_core.applicationper client. Audience-mapper wiring left as a documented operator merge step (Authentik handlesaudvia per-application property_mapping). -
--backend zitadel [--out craig.tf]— ZITADEL Terraform HCL covering 1zitadel_org+ 1zitadel_project+ 9 worker + 3 portalzitadel_project_role+ 11 servicezitadel_project_role+ 11zitadel_machine_user(each withaccess_token_type = ACCESS_TOKEN_TYPE_JWTpinned for local JWS validation) + 11zitadel_machine_user_secret+ 3zitadel_application_oidc(craig-ui + craig-portal-ui + craig-api) + optional 9zitadel_human_user+ grants. Operator applies via the officialzitadel/zitadelTerraform provider — bootstrap path documented indevstack/zitadel/README.md. -
--backend kanidm [--out bootstrap.sh]— Kanidm CLI bootstrap script (set -euo pipefailbash) invokingkanidm group createfor 9 worker roles + 3 portal roles + 11service:<svc>roles;kanidm system oauth2 create <svc>for 11 service principals;update-scope-map idm_all_accounts openidfor each (per the Phase 0 sandbox finding — Kanidm RS carriesEntryClass::Accountso the map covers the RS-as-principal client_credentials path);show-basic-secretto print each generated secret to stdout; 3 user-facing OAuth2 clients (craig-uiandcraig-portal-uipublic+PKCE,craig-apiconfidential); optional 9 dev users viakanidm person create. No admin API client per ADR-026 — operators run the script against their Kanidm instance authenticated asidm_admin. Bootstrap path documented indevstack/kanidm/README.md. Kanidm requires Plan F’s introspection mode at runtime (CRAIG_<SVC>__TOKEN_VALIDATION_MODE=introspect).
--production toggles between devstack-friendly defaults (9 dev users + filled callback URIs) and production-clean output (no dev users, empty URIs with operator-hint comments). Keycloak’s 11 service-account-<svc> users are service principals, not dev users, and stay in both modes.
The multibackend devstack’s committed bootstraps (devstack/kanidm/bootstrap.sh, devstack/zitadel/craig.tf,
devstack/authentik/blueprints/craig.yaml) are exactly these devstack renders. A unit test pins each one to its
render (#2373), so a model change that is not re-rendered fails cargo xtask test; regenerate with
cargo xtask identity render --backend <name> > <path>. cargo xtask dev kanidm-bootstrap provisions one Kanidm
resource server per service in the model’s CRAIG_SERVICES, not a copy of the list.
Operators of unsupported backends (Okta, Entra, ForgeRock, PingFederate, custom) use the Required IdP Configuration spec above to configure their backend manually. The conformance test (Step 12) gives them the contract.
Devstack realm and the identity model
The devstack realm devstack/keycloak/craig-realm.json is edited directly — nothing renders it. The identity model
(xtask/src/cmd/identity/model.rs) is the reference IaC shape and MUST be kept in parity with it: a change to a realm
role, client, audience mapper, access-token lifespan, dev user or service-account grant lands in BOTH in the same
change. The model carries no client scopes: a CRAIG-specific client scope lands in the realm, in UNRENDERED_SCOPES
(the keycloak.rs tests) and under CRAIG-specific OAuth2 scopes in the same change. The committed_realm_* tests in xtask/src/cmd/identity/render/keycloak.rs fail
naming every entry one side carries and the other lacks.
What the Keycloak render does not mirror:
-
the realm’s client scopes —
partners.replay-checkstays the operator step under CRAIG-specific OAuth2 scopes; -
its SSO session timeouts, its wildcard redirect URIs and web origins, and its devstack secrets;
-
the other way round, the render’s
craig-uicarries PKCE (S256), which the realm’scraig-uiomits. That is render-only hardening, kept. The render’s sign-in clients also name their default client scopes, which the realm’s inherit fromdefaultDefaultClientScopes. The set is the same (Keycloak: keep thebasicscope forauth_time).
Worker and service clients get the 1800 s access-token lifespan per client, so the IdP’s own clients keep the operator’s realm default.
Service Identity Keypair Provisioning (Plan E § Step 14)
Beyond the OIDC client/role provisioning above, each CRAIG service signs X-Craig-Actor JWTs (the on-behalf-of header introduced in Plan E Steps 5–9) with its own ES256 keypair. Peer services verify those JWTs against a deployment-wide JWKS map. Production deployments provision these keypairs once + rotate them on a schedule.
Generating fresh keypairs
cargo xtask gen-actor-keys [--out <path>] [--kid-suffix <suffix>] (shipped in Plan E Step 14) generates 9 ES256 keypairs + the deployment-wide peer-JWKS map. Output matches the env-file shape crates/craig-auth::keypair_env expects.
# Devstack: regenerate the committed keys file
cargo xtask gen-actor-keys --out devstack/devstack-actor-keys.env
# Stdout (production secret-mounting pipeline reads from here)
cargo xtask gen-actor-keys --kid-suffix prod_2026Q2_1
Devstack: inline env vars
The committed devstack/devstack-actor-keys.env carries inline JWK + kid env vars per service plus a single CRAIG_PEER_JWKS_JSON array. docker-compose.yml env_file:-references it. Convenient for dev; never copy these values into production — the leading header in the generated file calls this out explicitly.
Production: file-mount env vars
Production deployments must NOT carry private JWKs in the process environment (visible via /proc/<pid>/environ, audit logs, container introspection). Plan E Step 14 adds file-path variants that read the JWK from a mounted-secret path instead:
-
CRAIG_<SVC>__SIGNING_JWK_FILE=/run/secrets/craig-<svc>/signing-jwk.json— path to the per-service private JWK -
CRAIG_<SVC>__SIGNING_KID=<kid>— kid is non-secret; inline env is fine -
CRAIG_PEER_JWKS_JSON_FILE=/run/secrets/craig-peer-jwks/peer-jwks.json— path to the deployment-wide peer-JWKS array
The loader (crates/craig-auth/src/keypair_env.rs::load_signing_keypair_from_env) tries inline env first, then file-path. When both are set, inline wins — but in production neither operator should be setting the inline variant.
Mount the secrets via Docker secrets, Kubernetes secretKeyRef, HashiCorp Vault Agent sidecar, or whatever your platform provides. The content written to the file is byte-identical to what cargo xtask gen-actor-keys emits for the inline form (one JSON JWK per file for the signing key; the JSON array for peer-JWKS).
Rotation procedure
ES256 keypairs should rotate on a cadence (industry baseline: annually; tighter for high-security deployments). The rotation flow exploits the peer-JWKS map’s ability to carry multiple entries per iss so callers can verify either old or new signatures during the cutover window:
-
Pre-rotation — generate new keys with a fresh kid suffix:
cargo xtask gen-actor-keys --kid-suffix rot_2026Q2 --out /tmp/new-actor-keys.env -
Advertise — extend the deployment-wide
CRAIG_PEER_JWKS_JSON(or its file-mounted variant) to include both the old + new entries per service. Every service redeploys; verifiers now accept signatures from either kid. -
Rotate — rolling-restart each service with its new
SIGNING_JWK+SIGNING_KIDfrom/tmp/new-actor-keys.env. Each restarted service starts minting JWTs under the new kid; peers still verify old + new during the rollout. -
Drain — wait at least one actor-JWT TTL (Plan E uses 10 minutes; bump if your deployment uses a longer TTL) past the last rolling-restart. All in-flight tokens minted under the old kid are now expired.
-
Retire — redeploy with the old kid removed from
CRAIG_PEER_JWKS_JSON. The rotation is complete. -
Audit — the
audit_log.actor_service+actor_user_subcolumns (Plan E Step 11) make it easy to confirm no requests are still riding the old kid after the drain window:SELECT DISTINCT actor_service FROM audit_log WHERE timestamp > <rotation-start>.
If a key is compromised, skip the drain window and remove the bad kid from peer-JWKS immediately — every service issuing tokens with that kid will fail verification on its next outbound call, which is the intended failure mode for an emergency rotation.
Internal issuer
CRAIG’s own token issuer (ADR-085) is craig-security’s issuer process
(the compose service craig-security-issuer, port 8011). Not yet trusted: until the switch (ADR-085 D15, plan
U17) no service validates what it mints and no sender asks it; the IdP-issued path above stays in force. Its routes
are in the issuer’s API page; its settings in
the configuration reference § craig-security-issuer.
The token endpoint (#2743)
POST /identity/token takes an application/x-www-form-urlencoded form of at most 64 KiB; a repeated or undefined
parameter is invalid_request. Its first grant is client_credentials with an RFC 8707 resource
(urn:craig:service:<receiver>), which mints a service token: a compact ES256 JWS, header exactly alg, kid,
typ: at+jwt, claims iss sub aud exp iat nbf jti client_id scope, sub = client_id, 600 s, one audience.
-
Client authentication is
private_key_jwt(RFC 7523, ADR-085 D11):client_assertion_typeisurn:ietf:params:oauth:client-assertion-type:jwt-bearerandclient_assertiona JWS signed by one of the client’s registered keys: header exactlyalg(ES256),kid(the key’s RFC 7638 thumbprint) andtyp(client-authentication+jwt, or absent);iss=sub= the client id;audthe issuer identifier (CRAIG_SECURITY__IDENTITY_ISSUER) alone;expafter now and at most 60 s ahead; ajtiused once across every replica; at most 8 KiB. craig-auth’sidentity::assertion::AssertionSignersigns one. No secret is shared. -
Policy (ADR-085 D4) is compiled into craig-auth’s
identity::policy: a client may mint for a receiver only along a call-graph edge that carries service tokens, and itsscopeis a subset of the pair’s purpose (all of it whenscopeis absent; none when the pair has no purpose). Only craig-intake → craig-cases has one today,partners.replay-check. A test holds the graph to the census of every service’s*_URLsetting indocker-compose.yml; a URL setting the census cannot classify as a peer or a non-peer fails it. -
Order of checks. The per-IP limit (
IDENTITY_TOKEN_RATE_LIMIT_RPM, craig-api’s limiter keyed through craig-common’sclient_ipandTRUSTED_PROXIES); the form; the grant; the assertion; the client’s runtime status (identity_client_status, the latest row winning, read through a memo of at most 5 s); its budget (rate_limit_rpm, 429slow_down); the edge and the scopes; the signed mint; then the jti, spent in the issuance log’s commit that holds the mint’s row (#3151). So a disabled client is refused before its jti is spent, and a replay is refused whatever else the request found. -
Answers are RFC 6749 § 5.1 / § 5.2 with
Cache-Control: no-store: 400invalid_request,unsupported_grant_type,invalid_targetorinvalid_scope; 401invalid_client; 413 for a form over 64 KiB; 429; 503temporarily_unavailable.error_descriptionis the refusal code the issuance log records (for examplejti_reused,client_disabled), never the input. -
Issuance log (ADR-085 D13). Every mint and refusal appends a row to
identity_issuance_logthrough a group-commit writer on its own connection; the server suppliesrecorded_at(a column default) and a SHA-256row_digest. Each batch commits in one transaction: its assertion jtis in(client_id, jti)order, then its rows, so a mint costs one commit and takes no request-pool connection (#3151). A token is released only after its row commits; otherwise the answer is a 503 that releases nothing. The log is partitioned by UTC day (#3173): the ordinary craig-security process archives a closed day with the ADR-058 engine and drops its partition through the owner’sidentity_issuance_log_drop_partition, which never drops the current day. -
jti sweep (ADR-085 D16). Each replica calls the owner’s
identity_purge_client_assertions(1000)every 60 s within a 2 s budget, repeating while batches come back full; a row is kept until its assertion’sexp+ 60 s.
Client keys
craig-manage gen-client-keys --registry-out <json> --env-out <env> generates one ES256 key per compiled confidential
client: the issuer’s registry (public keys, for CRAIG_SECURITYIDENTITY_CLIENT_KEYS_FILE) and the private keys as
CRAIG_<SVC>CLIENT_JWK=<json> lines. The devstack pair, devstack/identity/client-keys.json and
devstack/devstack-client-keys.env, is a deliberately public fixture (ADR-064, ADR-085 D10). Production generates
its own and mounts each private key from its secret store as CRAIG_<SVC>__CLIENT_JWK_FILE, never from the
repository. To rotate, register the new public key beside the old one (two per client), restart the issuers, move the
client to the new key, then remove the old one. To stop a client at once without a restart, the owner appends a
disabling row to identity_client_status; every replica refuses it within 5 s (the admin route arrives with plan
U10).
Checking a deployment
cargo xtask identity verify --issuer <idp> --internal-issuer <issuer> adds two checks to the conformance test
above: the issuer’s JWKS is non-empty and every key is a P-256 point named by its thumbprint; and, with
--internal-client-id <client> and --internal-client-jwk-file <file> (or CRAIG_IDENTITY_INTERNAL_CLIENT_ID and
CRAIG_IDENTITY_INTERNAL_CLIENT_JWK), one client_credentials mint for the first receiver the client’s service
edges reach, whose token must verify under a listed key, meet the service layout and name the issuer and that
receiver. The mint spends one jti and writes one log row; nothing else changes.