Architecture

CRAIG follows a modular, service-oriented architecture modeled after OpenStack. Like OpenStack, all functionality is accessible through three equivalent interaction modes, so no capability is exclusive to any one client:

  • REST APIs: each functional domain (case management, eligibility, data exchange, etc.) is exposed as an independent, versioned REST service. The APIs are the authoritative interface and the foundation for all other clients.

  • CLI (craig): a first-class command-line client providing full access to all API functionality, suitable for scripting, automation, and administrative workflows.

  • Web UI: a browser-based interface for caseworkers, constituents, and providers, built entirely on the public REST APIs.

  • Message Bus (RabbitMQ): asynchronous event-driven communication between services, for data exchange, notifications, and audit events.

  • Rules and Policy Engine (GoRules / Zen Engine): jurisdiction-configurable policy rules evaluated at runtime using JSON Decision Models (JDM). Title IV-E eligibility, safety and risk assessment, timeliness monitoring, and other policy logic are defined as portable rule sets that each jurisdiction loads without modifying core code, which directly satisfies the 45 CFR § 1355.53(a)(1) requirement to separate business rules from core programming.

  • Modular Design: components can be independently developed, deployed, replaced, or shared with other states and tribes, per 45 CFR § 1355.53(a)(1).

  • Plain Language Documentation: all automated functions are documented in non-technical language, per 45 CFR § 1355.53(a)(2).

Service Architecture

Infrastructure
CRAIG Core Services
Clients
/report, /report/status
wildcard audit subscriber
OIDC authn for every service
domain events
Identity Provider
Keycloak OIDC
RabbitMQ
Message Bus
Garage
Object Storage
Rules & Policy Engine
GoRules / Zen Engine
Case Management
Service
Placement & Foster Care
Service
Data Exchange
Service
Financial & Claims
Service
Reporting & Data Quality
Service
Security & Compliance
Service
Public Intake
Service
Document Composition
Service
Web UI BFF
Server-rendered HTML
Web UI
Caseworker / Constituent / Provider
craig CLI
Scripting & Administration
Direct API Clients
Integrations & Automation
Public Reporter
Unauthenticated

Three fan-outs are drawn at the subgraph level, or described in prose, to keep the graph legible (#1418); no information is lost:

  • OIDC: the identity provider authenticates every core service (the single AUTH → CORE edge). Keycloak is the reference backend, not a CRAIG service itself; see the IdP integration guide.

  • Message bus: every API service publishes and consumes domain events over RabbitMQ, with two exceptions. craig-web is a pure BFF with no bus connection at all; it reads exclusively through service APIs. craig-intake, the stateless edge, holds no MQ connection either; it forwards over HTTP only (ADR-017). craig-security’s dashed edge is the informative special case: the wildcard audit subscriber (routing key `#) described under Cross-cutting Service Contracts below.

  • Databases: each core service owns its like-named PostgreSQL database (craig_rules, craig_cases, and so on), schema-per-service, with no cross-service DB access. The canonical service-to-port-to-database table is in Services. craig-intake is the stateless exception (ADR-017); craig-web is DB-less.

  • Admin-units snapshot: every service that boots the shared authz engine — all eight, craig-rules included (its one outbound HTTP edge, #1903) — reads craig-security’s `GET /v1/security/worker-identities/admin-units on its OWN principal (CRAIG_<SVC>__SECURITY_BASE_URL; ADR-077 D4): one CORE → SEC fan-in, described here rather than drawn. craig-security reads its own table.

Cross-cutting Service Contracts

Every CRAIG service except the pure-BFF craig-web honors the cross-cutting contracts below, enforced by shared middleware and helper crates. Since #1186 (ADR-061) that includes worker supervision: every background worker registers on a per-process Supervisor under an expected-worker manifest. A Critical worker’s death fail-fasts the process, with bounded drains and a nonzero exit, and /readyz gates on the worker registry + the RabbitMQ parent connection; a knob-disabled worker shows up as Disabled on /healthz.

Contract Implementation

OIDC authentication

craig_auth::middleware::auth_middleware — validates JWTs against the configured OIDC issuer’s JWKS with auto-refresh. The issuer is resolved at boot via <issuer>/.well-known/openid-configuration (craig_auth::OidcDiscovery) so the jwks_uri, token_endpoint, authorization_endpoint, and end_session_endpoint come from the discovery doc rather than hard-coded Keycloak paths. Any OIDC-compliant issuer that supports the client_credentials grant (Keycloak, authentik, Okta, Azure AD/Entra, ForgeRock, PingFederate, Auth0) works without code changes. Dex 2.45.1 does not support client_credentials and is therefore not a viable backend — see IdP integration guide. Every protected route is nested under the auth layer; public endpoints (craig-intake /public/v1/*, health checks) opt out explicitly.

Record-level authorization

craig_authz::AuthzEngine (zen-engine/JDM) — every protected handler routes its access decision through authz.check(…​) (single row) or authz.auto_scope_list(…​) (LIST). Per-resource policies live in each jurisdiction layer’s {jurisdiction}-authz-{resource}.json; roles, scoping, and approval workflows are inputs to decision tables — no require_caseworker_or_above() hard-codes. Spans all 8 authz-consuming services (incl. craig-composition; the site count drifts — grep authz.check/auto_scope_list for a live figure). Engine boots from craig-rules via OIDC-discovered HTTP for the other 7 services; craig-rules reads its own policies from local Postgres (DbRulesetSource) to avoid HTTP self-loopback. RMQ-driven cache invalidation + post-boot warm-up keep caches consistent. See ADR-023 + ADR-024.

RFC 9457 Problem Details

craig_common::ApiError → IntoResponse emits application/problem+json with type, title, status, detail. Every handler returns Result<_, ApiError>. Per-variant problem-type URLs live in the craig_common::error::problem_types catalogue (23 constants); the BadRequest and Conflict variants carry an Option<&'static str> type_url field populated by sub-typed constructors (bad_request_typed(url, detail, field) / conflict_typed(entity, detail, url)) when the precise cause is known. Catalogue includes category defaults (NOT_FOUND / BAD_REQUEST / UNAUTHORIZED / FORBIDDEN / CONFLICT / INTERNAL / VALIDATION_FAILED), BadRequest sub-types (INVALID_UUID / INVALID_ENUM_VALUE / INVALID_DATE / REQUIRED_FIELD_MISSING / INVALID_STATE_TRANSITION), Conflict sub-types (DUPLICATE_RESOURCE / FOREIGN_KEY_VIOLATION), middleware-specific (PAYLOAD_TOO_LARGE / IDEMPOTENCY_* / RATE_LIMITED), and domain-specific (MALFORMED_MULTIPART / CAPTCHA_FAILED / BATCH_TOO_LARGE / INVALID_RULESET / STRUCTURAL_MISMATCH). Since ADR-068 the surface also carries the degradation taxonomy: a GatewayTimeout (504) variant (REQUEST_TIMEOUT from the route-class ceiling middleware; DB_TIMEOUT for a server statement cancel), sub-typed ServiceUnavailable URLs (DB_CONNECTION_LOST, DB_OUTCOME_UNKNOWN for a commit whose verdict never arrived) with a variant-specific Retry-After: 5 ONLY on pool-exhaustion refusals, and the manual From<sqlx::Error> classifier (classify_db_error) every ?-propagated DB error rides — enforced by the blocking db-error-construction lint. Since 1272 the body-extractor tier speaks the same shape: services use craig_common::extract::{Json, Multipart} (drop-in wrappers), so pre-handler rejections (422 data / 400 syntax / 415 media type incl. the new UNSUPPORTED_MEDIA_TYPE URL / 413 body limit / multipart envelope) are problem documents with their original statuses preserved — retiring the plain-text BODY-extractor class. Since #2523 every extractor rejection (Json, Path, Query, Form, Multipart) is value-free: a service answers a problem document through craig_common::extract::{Json, Multipart, Path, Query, Form} (a Path / Query data error is a 400 bad-request; a route misconfiguration stays a 500 internal), the BFFs answer plain text through craig_bff::extract::{Path, Query, Form}, and both render the detail through craig_common::json_detail (a data error names its path or parameter, never the value). An upstream refusal reaches a client detail or a verbatim relay only through craig_common::problem (bounded read, validated document, bounded detail). An error type holding such a body never renders it in its Display, which feeds logs and internal-500 details: it names the status, plus the validated problem type through craig_common::problem::display_suffix (#2529; the value-free census’s C6 refuses an [error] that captures body). Upstream text a worker sees, in a flash or an inline notice, is display-escaped by craig_bff::text::display (each NUL and Unicode format character, Cf, as the literal \u{XXXX}; markup stays Askama’s to escape), and craig_bff::session::set_flash also cuts its text, with a …[truncated N bytes] marker, so the signed flash cookie stays within RFC 6265’s 4096 bytes for any text (#2869). The answer to a malformed typed value depends on its transport: A malformed typed value, per transport. Discipline: new URLs join the catalogue, not call sites.

Request validation (#2662)

craig_common::extract::{Json, Query, Form} require the extracted type to implement garde’s Validate and run it after a successful deserialize, so no handler can skip the check. A failure is the 422 validation-failed problem document with its field errors, the same document a handler’s own validate()? gives. It runs before the handler body, so before any check the handler makes itself: a request that is both invalid and refused by a handler’s own permission or feature check is answered 422, not 403 or 404. That is accepted because the 422 describes only the caller’s own request and reveals nothing about any record; authentication (401) is middleware and still comes first. A handler that must answer its permission check before a query’s errors takes Result<Query<T>, ParamRejection> and maps ParamRejection::is_invalid() itself. Path does not validate; its payloads are ids. The BFFs (craig-web, craig-portal) use their own craig_bff::extract wrappers, which do not validate.

Request idempotency (ADR-062 §B)

craig_api::request_claims — convert-class endpoints claim their client-minted client_request_id as the FIRST statement of the domain transaction (claim_first); replays classify against the durable claim (scope + entity kind + effective actor + intent hash) and re-derive the endpoint’s own success shape. The legacy Idempotency-Key response-cache middleware was DELETED in B2 (#1194, zero senders); each service prunes request_claims on the fleet-wide CRAIGREQUEST_CLAIMSWINDOW_DAYS horizon (default 30 d) via the request-claims-retention worker. Since #2707 a replayed 2xx carries the Idempotent-Replayed: true response header (request_claims::IDEMPOTENT_REPLAYED, after Stripe’s header of the same name): a craig-api tokio::task_local! marker is set where a claim resolves to a replay (classify yielding ClaimOutcome::Replay; upload_attempts::resolve_claim on FetchPromoted / FetchSuperseded) and cleared by a later fresh claim, so it holds the request’s latest claim decision, and one apply_global_layers layer just outside the request-ceiling middleware scopes it per request and stamps a marked 2xx, so no claim-substrate handler sets it. Since #2764 a replay a service resolves outside the shared claim code marks itself through the crate-root craig_api::mark_replayed(): cases' report resubmission on its received_request_id UNIQUE, and the cases SSA-screening forward when exchange’s answer carries the header. craig-intake (no ApiServer) relays the upstream header for its two proxied uploads, and its cases-backed sink relays cases' header on public and partner report submissions. Since #2783 its SHINES sink marks a report submission it answers from a receipt the request did not claim (a stored receipt, or the winner of a receipt claim it lost), and the public and signed confirmations carry the header.

Shared reqwest::Client

craig_common::build_shared_client(name, version) — one pool per service, 30s timeout, 5s connect timeout, 32 idle connections per origin, <service-name>/<version> user-agent. Injected via axum::Extension and cloned into handlers / adapters. Removes per-request reqwest::Client::new() pool churn.

Stateless session cookies (craig-web only)

tower-cookies + AES-GCM encrypted private() cookie carrying the JWT and locale, HttpOnly + SameSite=Strict. CRAIG_WEB__SESSION_SECRET (≥64 bytes) is the master key; see ADR-013. CSRF protection is enforced separately by the verify_csrf middleware (Sec-Fetch-Site / Origin / Referer header verification on state-changing requests, #763), not by a cookie field. Enables horizontal scaling of the web tier without a shared session store.

Wildcard audit subscriber

craig-security binds queue craig-security.events to the craig.events topic exchange with routing key #, writing every domain event to the audit_log table. This is how audit logging gets implemented once and for all — no per-service audit wiring.

A malformed typed value, per transport

The answer to a malformed UUID depends on the transport that carries it, by design (#2782). The extractors keep axum’s statuses: #1272 (Json, Multipart) and #2523 (Path, Query) turned their rejections into problem documents without moving a status, so no client’s status handling moved. A multipart field is hand-parsed by its handler, so its refusal is a typed problem. The same rule covers any other malformed typed value (a date, a number, an enum token): the extractor’s answer in a JSON body, a path or a query string, the handler’s typed problem in a multipart field. No answer echoes the value.

Transport Parsed by Answer Names the value’s place

JSON body

craig_common::extract::Json (axum’s JsonDataError)

422 validation-failed

the field, in detail (#2335, #2523)

Path segment

craig_common::extract::Path (FailedToDeserializePathParams)

400 bad-request

the route parameter, in detail (#2523)

Query string

craig_common::extract::Query (FailedToDeserializeQueryString)

400 bad-request

the parameter, in detail (#2523)

Multipart text field

the handler: the upload attempt’s client_request_id (craig_api::upload_attempts::required_upload_fields) and craig-intake’s upload edge (api/edge_validation.rs)

400 invalid-uuid

the field, in the field member

craig-intake’s report submissions (public, partner and signed) parse their JSON body by hand as well, so a malformed client_request_id there is its typed 400 structural-mismatch, the path named in detail.

Data Exchange Topology

Mandatory
Mandatory
Mandatory
Mandatory if applicable
Mandatory if applicable
Mandatory if applicable
Mandatory if applicable
To the extent practicable
To the extent practicable
To the extent practicable
Optional §1355.54
CRAIG
Data Exchange
Service
Child Welfare
Contributing Agencies
Financial Payments
& Claims
Medicaid
Eligibility
Child Abuse
& Neglect Systems
Title IV-A
TANF Systems
Title IV-D
Child Support
External Data
Collection Systems
Court
Systems
Education
Systems
Health
Agency Systems
Tribal
Entities
All exchanges use a single jurisdiction-defined data exchange standard per 45 CFR § 1355.52(f).

Reference Data Architecture

CRAIG uses a two-tier approach to reference data:

  • Tier 1: Compile-time (craig-reference crate). Domain enums (Sex, RaceCategory, PlacementType, etc.), FIPS codes for all US states and administrative units, and AFCARS/NCANDS field translations are defined as Rust enums with strum-derived conversions. These are shared across the workspace and validated at compile time. The crate includes 48 unit tests.

  • Tier 2: Runtime (Admin Unit Registry). Deployment-specific administrative units, such as counties, regions, boroughs, chapters, districts, and municipalities, are managed through CRUD endpoints on craig-security. Default seeds for all 57 US jurisdictions (50 states, DC, 5 inhabited territories, and the Minor Outlying Islands; 3,235 county-equivalents sourced from the Census Bureau’s national_county2020.txt) are compiled directly into craig-reference::counties, with no on-disk CSV layer involved. craig-manage seed-admin-units [--only <jurisdiction_key>] performs an idempotent UPSERT keyed on (name, jurisdiction). A deployment config endpoint, GET /v1/security/admin/config, returns the admin_unit_label (e.g., "County" for Georgia, "Region" for Texas), so the UI can adapt its labels without code changes. That label itself comes from the required CRAIG_<SVC>__ADMIN_UNIT_LABEL env var; there is no in-code default.

Post-deployment extensions, such as custom non-FIPS units like county consortia or experimental tribal compacts, go through the same craig-security::admin_unit_registry CRUD endpoints. That’s the operator extension mechanism.

Worker Identity

All API handlers identify the acting worker by claims.sub — the OIDC issuer’s stable user UUID. The web UI continues to display preferred_username for human readability. craig-security lazy-populates the worker_identities table from JWT claims on first authenticated request — no IdP admin-API dependency; this works across any OIDC backend. Devstack test users have pinned UUIDs in devstack/keycloak/craig-realm.json so seed data and integration tests can reference them deterministically.

Multi-Jurisdictional Posture

CRAIG ships jurisdiction-neutral by default: onboarding a new state, tribe, or county requires only data, not code.

  • Domain rules: add JDM JSON files named <jurisdiction>-<function>.json (e.g. georgia-ive-eligibility.json) to the jurisdiction’s config layer (craig-config-<jurisdiction>, pinned in config-sources.lock; Where rule sets live). The rules engine evaluates them following the {jurisdiction}-{function} naming convention.

  • Authorization policies: add JDM JSON files named <jurisdiction>-authz-<resource>.json to the jurisdiction’s config layer. The authz engine (craig-authz) consumes the same naming convention. Roles, scoping, approval workflows are inputs to the decision tables.

  • Admin units: craig-manage seed-admin-units --only <jurisdiction_key> --database-url <craig-security database> (or CRAIG_SECURITY__DATABASE_URL; there is no default target) upserts the compiled-in dataset, any of the 57 US jurisdictions, into admin_unit_registry. For deployment-specific units, such as county consortia, tribal compacts, or multi-state regional districts, operators use the craig-security::admin_unit_registry CRUD endpoints instead: the same flow, but at runtime, so it doesn’t require redeployment.

  • Reference data: rates, codes, calendars, theme, terminology and the outbound trigger matrix are files under bundle/ in the jurisdiction’s config layer, loaded at boot (the bundle/ file map).

  • Env vars: every service requires CRAIG_CONFIG_SOURCE, the configuration layers whose manifest names the jurisdiction, and CRAIG_<SVC>ADMIN_UNIT_LABEL=<label>; craig-web also requires CRAIG_WEBTHEME and CRAIG_WEB__BRANDING_AGENCY. There’s no silent fallback to Georgia.

  • OIDC identity: any compliant issuer works, since OIDC discovery resolves endpoints at boot. Worker identities populate from JWT claims.

See the archived Multi-Jurisdictional Authorization plan for the underlying architectural decisions (14 step MRs, 5 ADRs, May 2026).

Plugin Runtime

Server-side UI plugins extend the craig-web BFF without modifying it (Plan W; ADR-033). A plugin is a crate under plugins/ whose sync-pure render fn is annotated with #[craig_plugin(slug, manifest)] (craig-plugin-macros). That annotation emits a linkme CRAIG_PLUGINS registration carrying the plugin’s Plugin.toml manifest and its render fn. The host owns all I/O; the plugin only renders.

  • Boot: craig-web materializes a validated PluginRegistry (craig-plugin-contracts) from the slice, failing fast on a duplicate slug, an unknown required_role, or a display_name {term.*} key that doesn’t resolve against the materialized terminology.

  • Render: GET /plugins/<slug>, inside protected_routes, host-fetches the manifest-declared [data] endpoint. That fetch is SSRF-guarded by a deny-by-default host allow-list, per the auth mode (none / service_token / user_jwt), and maps the response to a FetchOutcome; a non-2xx answer is classified on its status and its body is never read (#2872). The plugin’s render fn is then called and returns a four-state (data / empty / error) CSP-clean HTML fragment; loading is the shell’s own htmx placeholder. A composed item’s __span outside its export’s allowed_spans is refused with 400 before any fetch (#2871).

  • Cache and single-flight (PluginCache): a per-replica render cache keyed by plugin, resolved endpoint, jurisdiction, principal, auth mode and grid placement holds the fragment of a Data or Empty fetch outcome for the manifest’s cache_ttl; an Error outcome’s fragment is never cached. It holds about 10 000 entries (RENDER_CACHE_CAPACITY), exceeded only by stores landing concurrently, one each: an expired entry is removed when read, and an insert at capacity sweeps expired entries first and is skipped when the cache is still full. Concurrent misses for one key share one flight, which runs on its own task: they make one upstream fetch and receive the same fragment, an error fragment included, or the same render-failure 500 (#2870). A zero-TTL plugin is neither cached nor coalesced.

  • Opt-in: plugins compile into craig-web behind per-plugin Cargo features (a #[cfg(feature = "…")] use … as _; linkme force-link), so a deployment composes its own plugin set. Production omits the reference plugin.

  • Source-agnostic seam: the PluginSource trait stays stable across backends. v1 is the compile-time linkme slice; v2 is WASM, with no contract change, since every value crossing the plugin boundary is serde-serializable.

The full design is in Plan W — Plugin Manifest + Render Runtime. The composition engine that arranges plugins into surfaces is Plan X (ADR-035).

Edit this page · latest