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::JwksProvider decodes 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::IntrospectionClient POSTs 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 client_credentials grant load-bearing for CRAIG: the craig-cases authz bootstrap, the craig-web BFF outbound path, and audit attribution all depend on per-service client_credentials tokens. Backends that do not support that grant cannot host CRAIG. Notably, Dex 2.45.1 does not implement the grant (compiled out of the server’s allSupportedGrants map; no config can enable it) and is therefore not a supported backend.

Tested backends (JWS or introspection-validating):

Backend Mode IaC adapter Notes

Keycloak

JWS

keycloak

Devstack reference; production-tested with the full E2E suite green. Supports "lightweight access tokens" (opaque) per Plan F’s introspection path.

authentik

JWS

authentik

Verified end-to-end against Authentik 2026.2.2 (!266). Rendered blueprint imports cleanly; full client_credentials mint round-trip in CI. Encrypted-token mode supported per Plan F’s introspection path.

ZITADEL

JWS (with ACCESS_TOKEN_TYPE_JWT pin) or introspection

zitadel

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 TOKEN_VALIDATION_MODE=introspect. Full mint needs operator Terraform bootstrap (devstack/zitadel/README.md).

Kanidm

Introspection only

kanidm

Kanidm 1.11 or later. Kanidm 1.10 never puts auth_time in the id_token, asked or not, which fails ADR-085 D1; 1.11’s source sends it on code exchange and refresh and honours max_age and prompt=login (the ITI U1 spike, #2738; #2965). The devstack pins 1.11.2, and #2965 records the spike’s Kanidm checks re-run on it. Verified structurally against Kanidm 1.10.1 (!272 / !273). client_credentials access tokens are unconditionally JWE-encrypted (oauth2.rs:1861); validation requires introspection. Renderer emits operator CLI bootstrap script. Set CRAIG_<SVC>__TOKEN_VALIDATION_MODE=introspect (or rely on the Auto default which detects the 5-segment JWE shape). Full mint needs operator-side bootstrap.sh after idm_admin password recovery (devstack/kanidm/README.md).

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

craig-ui

Authorization Code + PKCE (Proof Key for Code Exchange)

Web UI (craig-web BFF). Public client; no client secret. Redirect URI: https://<your-deployment>/auth/callback.

craig-portal-ui

Authorization Code + PKCE

The self-service portals (the craig-portal BFF; ADR-076). Public client; CLIENT-level lifespans (access 300 s, session idle 1800 s, session max 28800 s — the portal BFF caches no identity and ends its session on any refresh failure); audience mappers for craig-placement and craig-financial ONLY. Its principals hold a PORTAL role (foster_parent / family / provider — craig_auth::PORTAL_REALM_ROLES, disjoint from the worker roles); craig-web refuses them a session and every backend refuses them as a bearer — they reach a backend only as the subject a portal BFF relays (X-Craig-Subject). Redirect URI: https://<your-portal-host>/callback.

craig-api

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 client_credentials clients (one per CRAIG 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

sub

Stable user UUID. Used as the worker identity for all data writes. An IdP whose sub is not a UUID is unsupported until #2689’s internal issuer mints CRAIG subjects.

preferred_username

Human-readable username; rendered in the web UI.

email

Optional; populated into worker_identities.email, the worker directory. A worker’s own token (the CLI, a direct API call) refreshes it on every write; a browser-only worker’s email comes from their ACCESS token, which craig-web relays on the actor JWT (#2472). A relay without one keeps the cached value.

name

Optional full name (the profile scope’s full-name mapper); populated into worker_identities.display_name and shown to foster parents through the portal projections. It reaches the directory the same way as email: from a worker’s own token, or for a browser-only worker from their ACCESS token through craig-web’s actor JWT (#2472). An IdP whose access tokens omit name yields the username as the display name.

the roles claim, at CRAIG_IDENTITY_ROLES_CLAIM_PATH (default realm_access.roles)

RBAC roles, read at one configured path; see The roles claim per IdP. CRAIG_IDENTITY_SERVICE_ROLE_PREFIX (default service:) selects which role entries mark a token as a service-caller.

aud

Multi-valued array of service names. CRAIG validates that the token’s audience contains the target service (craig-cases, craig-rules, etc.). See ADR-021 for full strictness rules.

typ (optional)

When present, must be "Bearer". Absent values are tolerated for non-Keycloak issuers.

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 {role: {orgId: domain}} shape). This applies at any path, the default included.

Absent, or null at any segment

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

realm_access.roles (the default)

The realm-roles mapper.

authentik

groups

The groups scope mapping, or a property mapping.

Okta

groups

A groups claim on the authorization server, filtered to the CRAIG groups.

Entra ID

roles

App roles. Entra also puts them on client-credentials tokens for service principals.

Auth0

a claim name without a ., e.g. craig_roles

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

urn:zitadel:iam:org:project:roles

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.

Administrative units are NOT an IdP claim: a worker’s counties are a CRAIG registry fact (worker_admin_units on craig-security, ADR-077) that the authz engine enriches into claims.admin_units at evaluation time, so architecture B needs no IdP mapper (the ADR-026 amendment, #1086).

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

partners.replay-check

craig-intake (default client scope)

services/craig-cases/src/api/jws_replay.rs::check_jws_replay — guards the /v1/cases/_internal/jws-replay-check S2S dedup endpoint (#489). The role check beneath it (require_caseworker_or_above) is bypassed for a DIRECT service caller per Plan E (ADR-028); a relayed call is judged on its acting worker (#2522); this scope is what stops a different compromised service-account or a worker token from writing to the JWS replay ledger.

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:

  • basic MUST be a default client scope on every sign-in client: craig-ui, craig-portal-ui and ADR-085’s craig client. An optional client scope is not enough, because CRAIG does not request basic;

  • the basic scope MUST keep its auth_time mapper 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-ui and the craig-portal BFF): craig-placement and craig-financial only. No token names craig-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 or service: 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:

  1. Leave the worker account unchanged. Never add a portal role to it.

  2. 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_parent for 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).

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

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

CRAIG_<SVC>__OIDC_ISSUER

Public issuer URL, e.g. https://idp.your-deployment.gov/realms/craig. Required.

CRAIG_<SVC>__OIDC_INTERNAL_URL

Internal URL for split-DNS deployments (Docker / k8s). When set, CRAIG fetches the discovery doc + JWKS via this URL and rewrites the doc’s jwks_uri + token_endpoint host portions accordingly. Browser-facing endpoints (authorization, end_session) keep the public URL. Optional — defaults to OIDC_ISSUER.

CRAIG_IDENTITY_ROLES_CLAIM_PATH

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 realm_access.roles; a malformed value refuses boot.

At boot, each service:

  1. Builds an OidcDiscovery client pointing at the issuer (and internal URL if split-DNS).

  2. Fetches <issuer>/.well-known/openid-configuration and caches the four endpoints CRAIG consumes: jwks_uri, token_endpoint, authorization_endpoint, end_session_endpoint.

  3. Fetches the JWKS from jwks_uri and 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 its kid, and a token naming it is refused (401, body invalid 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 unknown kty such as a post-quantum AKP key, EC secp256k1, OKP Ed448 or X25519, an RSA key with no e) is skipped the same way, with the warn reason key 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 whose kid misses 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, missing kid) never triggers IdP traffic, and a failed on-demand refresh still rejects the token (fail-closed).

  4. 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 and azp = the login client, typ: ID, the login nonce, and the at_hash binding 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 ClaimsExtractor dispatch 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 to azp = 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’s aud. 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, introspect or auto (the default), with the same meaning as a service’s CRAIG_<SVC>__TOKEN_VALIDATION_MODE. Under auto a Keycloak JWS login makes no introspection call.

  • The introspection principal is required under auto and introspect. craig-web uses CRAIG_WEBCLIENT_ID / CRAIG_WEBCLIENT_SECRET and refuses to boot without both, naming them; pin CRAIG_WEBTOKEN_VALIDATION_MODE=jws to boot without. craig-portal’s CRAIG_PORTALCLIENT_ID / CRAIG_PORTAL__CLIENT_SECRET are 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

CRAIG_<SVC>__INTROSPECTION_ENDPOINT

(auto-discovered)

Set explicitly when the IdP exposes a non-standard introspection path or runs on a separate host from the OIDC issuer.

CRAIG_<SVC>__INTROSPECTION_AUTH_METHOD

client_secret_basic

Switch to client_secret_post for IdPs that disallow Basic auth on the introspection endpoint, or private_key_jwt for ADR-026-style mTLS-equivalent deployments where the introspection client uses an asymmetric keypair instead of a shared secret.

CRAIG_<SVC>__INTROSPECTION_CACHE_TTL_SECONDS

60

Raise (e.g. 300) for slow IdPs or to reduce introspection load on the issuer; lower (e.g. 10) when revocation latency matters more than RTT amortization. Actual TTL is min(claims.exp - now, this) so short-lived tokens cap naturally.

CRAIG_<SVC>__INTROSPECTION_CACHE_MAX_ENTRIES

10000

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.

CRAIG_<SVC>__INTROSPECTION_SERVE_ON_OUTAGE

false

Set true for resilience against IdP blips — expired cache entries continue serving up to 1× INTROSPECTION_CACHE_TTL_SECONDS past expiry while the introspection endpoint is unreachable (worst case 2× that knob after the last successful validation, since the TTL itself is capped by it). Keep false (fail-closed) when strict revocation semantics outweigh availability.

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:

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:

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:

  1. Create the craig-ui and craig-api clients per the Required IdP Configuration section above.

  2. Configure the realm to emit the audience mappers.

  3. Set CRAIG_<SVC>__OIDC_ISSUER on each service to your IdP’s public issuer URL.

  4. (Optional) Set CRAIG_<SVC>__OIDC_INTERNAL_URL if your service-to-IdP path differs from the public URL.

  5. 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:

  1. Fetch <issuer>/.well-known/openid-configuration (a trailing / on the issuer is trimmed to build this URL) and verify that its issuer equals 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’s iss with their OIDC_ISSUER byte for byte, so pass the value they are configured with.

  2. Verify the three required endpoints (authorization_endpoint, token_endpoint, jwks_uri); end_session_endpoint is optional and not checked.

  3. Fetch the JWKS and parse it; confirm at least one signing key is present.

  4. (Optional, when --client-id/--client-secret or CRAIG_IDENTITY_TEST_CLIENT_ID/CRAIG_IDENTITY_TEST_CLIENT_SECRET are set) Attempt a client_credentials grant against a configured test service principal and validate the response token shape (non-empty access_token, token_type matches Bearer case-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-ui 300 s), the sign-in clients' default client scopes with basic among them (Keycloak: keep the basic scope for auth_time), and 11 service-account-<svc> users (serviceAccountClientId), which carry each service’s service:<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 to kc.sh import or 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.group for each role + authentik_providers_oauth2.oauth2provider + linked authentik_core.application per client. Audience-mapper wiring left as a documented operator merge step (Authentik handles aud via per-application property_mapping).

  • --backend zitadel [--out craig.tf] — ZITADEL Terraform HCL covering 1 zitadel_org + 1 zitadel_project + 9 worker + 3 portal zitadel_project_role + 11 service zitadel_project_role + 11 zitadel_machine_user (each with access_token_type = ACCESS_TOKEN_TYPE_JWT pinned for local JWS validation) + 11 zitadel_machine_user_secret + 3 zitadel_application_oidc (craig-ui + craig-portal-ui + craig-api) + optional 9 zitadel_human_user + grants. Operator applies via the official zitadel/zitadel Terraform provider — bootstrap path documented in devstack/zitadel/README.md.

  • --backend kanidm [--out bootstrap.sh] — Kanidm CLI bootstrap script (set -euo pipefail bash) invoking kanidm group create for 9 worker roles + 3 portal roles + 11 service:<svc> roles; kanidm system oauth2 create <svc> for 11 service principals; update-scope-map idm_all_accounts openid for each (per the Phase 0 sandbox finding — Kanidm RS carries EntryClass::Account so the map covers the RS-as-principal client_credentials path); show-basic-secret to print each generated secret to stdout; 3 user-facing OAuth2 clients (craig-ui and craig-portal-ui public+PKCE, craig-api confidential); optional 9 dev users via kanidm person create. No admin API client per ADR-026 — operators run the script against their Kanidm instance authenticated as idm_admin. Bootstrap path documented in devstack/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-check stays 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-ui carries PKCE (S256), which the realm’s craig-ui omits. That is render-only hardening, kept. The render’s sign-in clients also name their default client scopes, which the realm’s inherit from defaultDefaultClientScopes. The set is the same (Keycloak: keep the basic scope for auth_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:

  1. 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
  2. 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.

  3. Rotate — rolling-restart each service with its new SIGNING_JWK + SIGNING_KID from /tmp/new-actor-keys.env. Each restarted service starts minting JWTs under the new kid; peers still verify old + new during the rollout.

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

  5. Retire — redeploy with the old kid removed from CRAIG_PEER_JWKS_JSON. The rotation is complete.

  6. Audit — the audit_log.actor_service + actor_user_sub columns (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_type is urn:ietf:params:oauth:client-assertion-type:jwt-bearer and client_assertion a JWS signed by one of the client’s registered keys: header exactly alg (ES256), kid (the key’s RFC 7638 thumbprint) and typ (client-authentication+jwt, or absent); iss = sub = the client id; aud the issuer identifier (CRAIG_SECURITY__IDENTITY_ISSUER) alone; exp after now and at most 60 s ahead; a jti used once across every replica; at most 8 KiB. craig-auth’s identity::assertion::AssertionSigner signs 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 its scope is a subset of the pair’s purpose (all of it when scope is 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 *_URL setting in docker-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’s client_ip and TRUSTED_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, 429 slow_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: 400 invalid_request, unsupported_grant_type, invalid_target or invalid_scope; 401 invalid_client; 413 for a form over 64 KiB; 429; 503 temporarily_unavailable. error_description is the refusal code the issuance log records (for example jti_reused, client_disabled), never the input.

  • Issuance log (ADR-085 D13). Every mint and refusal appends a row to identity_issuance_log through a group-commit writer on its own connection; the server supplies recorded_at (a column default) and a SHA-256 row_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’s identity_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’s exp + 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.

Edit this page · latest