Shared Crates Reference

For a contributor or agent writing service code against the shared crates: every crate under crates/ has one entry here — its job (from the crate’s //! header) and the public entry points a caller reaches for. The crate source and cargo doc are the authoritative detail; this page orients. Five crates have a single consumer (canopy-composition and canopy-plugin-macros → canopy-web, canopy-scanner-clamd → canopy-applications, canopy-typst → canopy-notices, canopy-validators → canopy-verification) and are shared in the sense of living under crates/, not of fan-in.

canopy-common

Shared types and utilities for every service. The modules are listed by pub mod in crates/canopy-common/src/lib.rs; the ones a service author meets first:

  • error::ApiError — enum whose variants include BadRequest, Unauthorized, Forbidden, NotFound, Conflict, Gone, UnprocessableEntity, PayloadTooLarge, NotImplemented, ServiceUnavailable, BadGateway, Coded and Internal; the handler return type, rendered as RFC 9457 Problem Details JSON via IntoResponse. ApiError::database(context, err) (and From<sqlx::Error>, which calls it) maps a database failure whose constraints client input can trip: pool exhaustion → 503, an error::ConstraintViolation → its coded 409 / 422, anything else → a redacted 500. ApiError::internal_database(context, err) is the server-computed twin: the same 503, and every constraint refusal a redacted 500. The rule set is in Coding Conventions › Database errors.

  • Typed ids, actor identities and the pure vocabulary, pagination and date types are not here: canopy-types holds them, and canopy-common re-exports none of them.

  • The sqlx feature — off by default, and the only thing that makes sqlx a dependency of the crate. It adds From<sqlx::Error> for ApiError, ApiError::database, ApiError::internal_database and error::ConstraintViolation, and switches on canopy-types/sqlx with them. No other code in canopy-common uses sqlx: the database modules it used to hold are in canopy-db. Who enables it follows the same rule as canopy-types' feature, checked by the same xtask test (canopy-types): a crate with a normal sqlx dependency declares canopy-common = { workspace = true, features = ["sqlx"] }, and a crate with none (canopy-cli, canopy-auth, canopy-signing, canopy-pack-check, the clients) declares it bare and links no database driver through it. Cargo unifies features across the packages of one build, so the shipped canopy binary is built in a cargo invocation of its own, and both halves are checked: canopy-cli's boundary test refuses sqlx in the CLI's own dependency tree, and the devstack build refuses a staged canopy that links the driver (The devstack's binaries, #3414). cargo xtask feature-builds compiles canopy-common with the feature off.

  • settings::ServiceSettings — the shared baseline every service boots on (port, database/broker URLs, the canopy-identity issuer pair identity_issuer / identity_internal_url, the configuration source config_source / policy_root / config_allow_unverified, pool and rate-limit tunables); ServiceSettings::config_snapshot() loads the canopy-config snapshot those three name. The jurisdiction is not a setting: it is the snapshot’s (ConfigSnapshot::jurisdiction()). settings::load_service_config(prefix, &LoadOptions { .. }) collects ONE layered map — config/<service>/default.yaml, then the overlay CANOPY_ENV names (dev.yaml for development, prod.yaml for production, <value>.yaml otherwise, none when unset), then the whole-stack CANOPY_CONFIG_SOURCE, CANOPY_POLICY_ROOT and CANOPY_CONFIG_ALLOW_UNVERIFIED, then CANOPY_{SERVICE}__* env — and partitions it by ServiceSettings::FIELDS into the baseline and the caller’s <Svc>Config. LoadOptions::reserved_keys drops keys read elsewhere on purpose (secrets via canopy-secrets, overrides via their own strict recognizers) before serde sees them; mirrored_keys copies a key both structs declare (such as canopy-security’s identity_issuer and identity_internal_url, which its issuer reads too) into both halves. settings::load_single(prefix, &opts) loads one struct with no partition. Both refuse a map that names no config_source, naming CANOPY_CONFIG_SOURCE and the per-service key (#2627). settings::config_root() is the one resolution of the directory holding every service’s config: CANOPY_CONFIG_ROOT (CONFIG_ROOT_ENV) when set, else the working directory; the layered load uses it when LoadOptions::config_root is None, and canopy-security reads its client registry under it (#2550). Its secret fields (the database and broker URLs) are re-read through the audited provider in canopy-api's bootstrap_with (ADR-017). Variable names and defaults: Configuration Reference.

  • crypto::encrypt(plaintext, key) / crypto::decrypt(ciphertext, key) — AES-256-GCM with a random 12-byte nonce prepended to the ciphertext; the 32-byte key is loaded from CANOPY_ENCRYPTION_KEY (base64).

  • http::data_path_client() — the single blessed reqwest::Client builder with explicit connect and total timeouts, so a black-holed upstream fails fast instead of hanging a lock, an MQ handler or an SSR handler, and no redirect followed, so a 307/308 cannot carry its callers' credentials to another origin (#2534); build_data_path_client(connect, total) is its timeout-parameterized core, for a client class with its own total (the canopy-appeals, canopy-enrollment and canopy-web upstream clients, and the 5 s and 10 s clients of canopy-applications, canopy-eligibility, canopy-portal and canopy-verification) and for fault-injection tests. data_path_client_builder(connect, total) returns the builder with the bounds and the no-redirect policy already stated, for a client that adds a setting of its own (canopy-auth’s TLS trust anchors and scheme rule, a pinned resolver, a bound local address), and blocking_data_path_client_builder(connect, total) is its blocking twin behind the blocking feature, which otel turns on (the OTel metric exporter’s transport, xtask’s commands). Each call builds a new client, and a build reads the system root certificates (about 22 ms): every build trusts webpki's roots and the system's, since object_store pins reqwest's native roots and the workspace names them too (#3329). So a client is built once per process and shared, never per request; the program services' signing-key registration shares one across its retries. Every production client, in the services, the shared crates, tools/ and xtask, goes through one of the four (#2298, #2584): cargo xtask http-clients audit-builders refuses a client constructor anywhere else outside canopy-test-lib, unless compliance/client-builder-allowlist.toml gives the reason. A client built any other way must still state its own connect_timeout and whole-request timeout: cargo xtask http-clients audit-timeouts refuses one that does not, a bare reqwest::Client::new() included, and a per-read read_timeout stands in for the timeout only under an allowlist entry for a streamed body (#2536).

  • http::error_body(resp) (#3410) — the body of a response a caller is about to report as a failure. A body that cannot be read comes back as a marker beginning http::UNREADABLE_BODY, never as an empty string, so an error says whether the peer sent nothing or what it sent was lost. A service client that reads a failed response's whole body as text reads it here; one capping what an uncontrolled peer may send reads through http::egress instead.

  • owner_only (#2646; ADR-049 Amendment 23; #2848) — owner-only files for stored credentials: canopy-auth’s device store (canopy-cli’s sessions) and xtask’s devstack identity files. write_owner_only(path, contents) creates any missing directory 0700 (narrowing a looser existing one), stages the contents in a fresh 0600 sibling (O_EXCL, so no planted file or link is followed), fsyncs it and renames it over path; on Unix it then fsyncs the directory, and each directory it created into its parent, so an acknowledged store survives a crash. It sweeps a crashed store’s staged copy once a minute old. Each staged copy it cannot remove is a Leftover, returned for the caller to report (in Stored::leftovers, or in OwnerOnlyError::Store beside any failure once the directory exists), never printed. remove_owner_only(path) removes a file durably (a missing one is no error). open_owner_only_lock(path) opens a lock file only as a regular file, creating it 0600; on Unix a file swapped in before the open is refused by its identity. Off Unix the files inherit their directory’s ACL, and directories are not synced.

  • http::client_ip (ADR-049 Amendment 22; #2841) — the client-IP rule canopy-api’s per-IP limiters key on, one source for every reader of a forwarded client. TrustedProxies::from_env() reads CANOPY_TRUSTED_PROXIES (TRUSTED_PROXIES_VAR: exact addresses and CIDR ranges, IPv4 or IPv6, comma-separated, blanks skipped, each entry that is neither, or a range with host bits set, warned and ignored; #2846); parse(raw) is the same rule, and Default trusts none. trusts(peer) holds for a listed address or a peer inside a listed range of its family; resolve(peer, headers) is the peer, or the leftmost X-Forwarded-For hop when the peer is trusted and that hop is an address; client_ip(Option<SocketAddr>, headers), the limiters' form, keys a request with no peer as 127.0.0.1. An unlisted peer’s X-Forwarded-For is never believed.

  • shutdown::shutdown_signal() → io::Result<impl Future> — registers the graceful-shutdown handlers (SIGINT and SIGTERM on unix, ctrl-c on Windows) when called, so a refused handler is a boot error, and returns the future a server’s graceful shutdown awaits; every canopy_api service’s ApiServer::serve and the applicant portal share it.

  • Modules shared by more than one service: workdays (only load_from_jurisdiction_doc, which reads the pack's [jurisdiction.holidays] into a canopy_types::workdays::WorkdayCalendar and refuses a malformed one), expedited_postponement (the postponed-verification month table, its loader, and the certification-period arithmetic), retention (the batch loop every retention sweep shares, #2577), access_log, credentials, clock, fault, env, telemetry. error::error_chain_text renders an error with its source chain; the excerpt that bounds it is canopy_types::text::bounded_excerpt.

  • intake_document_types::DocumentTypes (load_from_jurisdiction_doc, get, contains) — the pack's [[intake.document_types]] rows, in its order: canopy-applications holds an upload's type to them, canopy-web labels a document from them, and canopy-portal builds its picker from them. Each refuses to boot on a missing or malformed table.

  • intake_reported_income_sources::ReportedIncomeSources (load_from_jurisdiction_doc, contains, label_or_code) — the pack's [[intake.reported_income_sources]] rows, read by the same three services under the same rules.

  • issuance_cycle::IssuanceCycle (load_from_jurisdiction_doc, from_key) — the pack's snap.issuance.cycle_granularity (benefit_month only): next_cycle_start dates canopy-appeals' cessation of continued benefits and cycle_end closes canopy-enrollment's enact window. Both refuse to boot on a missing or unknown value.

  • key_material — the loader policy for signing keys, verifying keys and client secrets (#2489): require_key_material / require_secret / optional_secret read through a SecretProvider, and DevKeyFiles is the .keys/ fallback, which only from_process_env in a CANOPY_ENV=development process opens. The rules and the secret-loads gate: Configuration Reference › Secrets.

canopy-types

The pure types every crate shares, with no I/O and no configuration read: its dependencies are serde, chrono, uuid, utoipa and thiserror (crates/canopy-types/Cargo.toml). A crate imports them as canopy_types::…; the modules are listed by pub mod in crates/canopy-types/src/lib.rs.

  • id — the define_id! macro generates typed newtype UUID wrappers (PersonId, HouseholdId, ApplicationId, …) that prevent compile-time ID mixing; all UUID v7 (Uuid::now_v7()). canopy_types::Id is the raw Uuid alias.

  • identity — who performed an act (#1008, ADR-043 Amendment 1). OidcSubject is an OIDC sub: opaque, 1–255 ASCII bytes with no control character, compared byte for byte and never trimmed, case-folded or parsed as a UUID. ServicePrincipal is a service’s name (a system caller’s client id) under the same rule. Both are built only through validating constructors (TryFrom<String> / FromStr, serde try_from), and their Postgres Decode (under the sqlx feature) re-validates, so a malformed stored value is a decode error. Actor is Human { subject } | Service { service }, internally tagged on actor_type on the wire; in Postgres it is a <col> + <col>_service column pair, read with Actor::from_columns (both set is refused, neither is no actor) or, for a mandatory act, Actor::from_mandatory_columns (both or neither is a MandatoryActorColumnsError, which a reader may map to its own error naming its column or row; #2341), and bound with Actor::columns(). Deliberately separate from id: nothing here is a UUID.

  • pagination::PageRequest / PageResponse — pagination query/response structs, also at the crate root (canopy_types::PageRequest).

  • date::age_years(dob, as_of) — calendar-aware age (not num_days() / 365).

  • month_period::MonthPeriod — an inclusive span of whole calendar months, first_month to last_month, each the first day of its month (new, spanning(from, through) for the months two days fall in). A value that exists is in order; one that is not does not deserialize. The period an overpayment covers is written in it.

  • date::age_months(dob, on) — whole months: the largest n with dob + n months on or before on, under chrono’s month clamp (a 29 February birth reaches 12 months on 28 February); None before the birth. canopy-wic’s infant bands and food packages and the demo seed’s WIC ages read it.

  • policy_target — the composite policy identity a determination pins (CorpusHashHex/ParamsDigest 64-hex newtypes, the half-open EffectivePeriod, PolicyTarget, ParamsProvenance, and the request-side PolicyTargetRef a dry-run caller names a target policy with; ADR-028 Amendment 6); trigger::DeterminationTrigger is the ADR-002 Amendment 1 provenance classifier.

  • text::bounded_excerpt(body) — truncates upstream-derived text to text::ERROR_BODY_EXCERPT_BYTES (256) on a character boundary, with a marker that states the original size; the HTTP clients bound an error body with it before it reaches an ApiError or a log.

  • expedited_postponement::PostponementDispatch / ConversionDispatch — the open postponement and the in-certification conversion as a determination request carries them; the month table and the period arithmetic stay in canopy-common.

  • workdays::WorkdayCalendar — a jurisdiction's working-day calendar and its arithmetic (add_workdays, checked_add_workdays, last_workday_on_or_before, first_workday_on_or_after). WorkdayCalendar::new takes the holiday dates and coverage years as given; a service builds one from a pack through canopy_common::workdays::load_from_jurisdiction_doc, which does the validation.

  • The vocabulary modules shared by more than one service: filing, recert, effective_date_basis, household, au_composition, administrative_denial, rep_disqualification, advisory, causal, and hex (panic-free lowercase hex encoding).

  • The sqlx feature — off by default. It adds sqlx::Type to every define_id! type and the Postgres Type / Encode / Decode impls to OidcSubject and ServicePrincipal, and makes sqlx a dependency of the crate. define_id! is defined once for each state of the feature (crates/canopy-types/src/id.rs), so a service crate that invokes it gets the definition canopy-types was built with. A workspace crate that has a normal sqlx dependency declares canopy-types = { workspace = true, features = ["sqlx"] }; a crate with none never enables it in [dependencies]; a crate whose only sqlx is a dev-dependency enables it in [dev-dependencies] (canopy-portal). canopy-common's sqlx feature follows the same rule, and canopy-common itself, whose sqlx is optional, reaches this feature through its own. The xtask test every_workspace_crate_enables_the_sqlx_features_exactly_when_it_depends_on_sqlx (xtask/src/sqlx_feature_rule_tests.rs) names a crate that breaks the rule for either crate, canopy_commons_own_sqlx_dependency_is_optional keeps canopy-common's dependency optional, and cargo xtask feature-builds compiles the crate with the feature off.

canopy-auth

canopy-identity’s token types, receivers and senders, canopy-web’s session engine, canopy-cli’s device client, the upstream identity provider’s client, and canopy’s role vocabulary (ADR-049). Every service’s /v1 sits behind an IdentityReceiver, every outbound call takes its bearer from a sender, and canopy-identity, hosted in canopy-security, is the only token issuer.

  • roles (#515; ADR-049 Amendment 15) — canopy’s role vocabulary and named role bars, re-exported at the crate root. ROLE_VOCABULARY is every role name canopy authorizes on, sorted: the union of the bar constants, the inline role literals the routes' admissions name, and canopy-web’s WorkerRole names; an xtask source scan pins it to exactly those names, and the upstream projection grants no role outside it. SERVICE_ROLE_PREFIX (service:) is the retired service-marker prefix, which the projection never grants. The bars (CASEWORKER_OR_ABOVE_ROLES — caseworker, eligibility_specialist, supervisor, quality_control, admin; CASEWORKER_WRITER_ROLES, the same minus quality_control, which every write route takes; CITATION_RENDER_ROLES; DETERMINATION_OPERATOR_ROLES, the writers above caseworker, which canopy-eligibility’s quarantine routes admit, #2061; and the delegated routes' CASE_READER_ROLES, WORKER_READER_ROLES, AUDIT_READER_ROLES and SUPERVISOR_VIEW_ROLES, #2801) are the slices Admission::user_roles and its siblings name. See RBAC matrix.

  • load_applicant_verifier(secrets, env_key, dev_keys) / boot_applicant_verifier(service, env_key) (applicant_verifier.rs, #1442) — the origin services' applicant-claim verifier under the #2489 loader policy: the portal’s verifying key from env_key through the audited SecretProvider, else, in development only, .keys/portal-applicant-public.pem plus a staged portal-applicant-public-next.pem; each concatenated PEM block registers under its own derived kid (#1569). ApplicantVerifierAdapter is the production ApplicantClaimVerifier, over canopy-signing’s claim verification.

  • CanopyRequestBuilderExt — the outbound reqwest::RequestBuilder decorator with_finalize_step(Option<FinalizeStepHeaders>); the x-canopy-finalize-* header names live here as the single source shared by the writer (canopy-persons-client) and the reader (canopy-persons), ADR-038. ACTOR_HEADER is the retired X-Canopy-Actor, which a receiver refuses with 400 actor_header_retired.

  • identity_policy (ADR-049 §3, §4, §10, Amendment 3 and Amendment 4, #2549, #2641, #2643, #2645) — canopy-identity’s compiled policy and its token layouts. The clients and receivers are compiled: ConfidentialClient is a client that authenticates with private_key_jwt, its 15 variants canopy-web, canopy-portal and the 13 services that call another service; NativeClient is a public client bound by DPoP, its one variant canopy-cli; Client is Confidential() or Native(), and Client::all() yields all 16 identities; CanopyService is one of the 16 services that serve another canopy caller. Each is serialized as its id (as_str), and its FromStr and serde refuse any other string, a near miss in case or whitespace included, with an error of its own (UnknownConfidentialClient, UnknownNativeClient, UnknownClient, UnknownCanopyService) that does not echo it. Client::opens_sessions() is true for canopy-web and the native clients. ConfidentialClient::service() is the service a client runs as and shares its id with (None for the two portals); CanopyService::audience() is its audience URI and CanopyService::from_audience the exact inverse. purposes() is the compiled purpose registry: each SystemPurpose { name, client, audience, scopes } is named <client-id>/<audience-service>, and purpose_for(client, audience) returns the one purpose of a (client, audience) pair, if any. An audience is a URI, SERVICE_AUDIENCE_PREFIX (urn:canopy:service:) plus the service name (service_audience). The portal’s nine purposes, first in the registry, are canopy-portal’s Target::op_scopes, which a canopy-portal test holds equal. Every other confidential client has one purpose for each of its System or Both edges (46; Amendment 16, #2807), whose one scope is its own name: the scope is informational, since a receiver judges a service’s system token by its edge and the route’s client list, and a test holds the purposes to the call graph’s system edges one for one. SystemTokenClaims (iss sub aud exp iat nbf jti client_id purpose scope; jti a UUID, scope space-separated, split by scopes()) and ClientAssertionClaims (iss sub aud exp iat jti) name their client as a ConfidentialClient, so a native client’s id parses in neither, and are deny_unknown_fields, so a payload carrying a user claim (sid, roles, programs, act, auth_time) or any other unknown claim does not deserialize; aud is a single string. Validating them is the issuer’s and the receivers' job. The call graph (Amendment 4, #2643): edges() yields one Edge { caller: Client, target: CanopyService, kind: EdgeKind } per pair a compiled client calls, each Delegation, System or Both; edge(caller, target) is a pair’s kind, may_delegate reads the delegation edges (Delegation, Both), may_hold_system_token(ConfidentialClient, target) the pairs a purpose may name (System, Both), and delegators_of(target) the clients that may delegate to a target. MAX_ACT_DEPTH (8) is the most actors a delegation chain can hold, which a test computes from the table. EdgeKind is written delegation, system or both (as_str, Display); FromStr refuses any other string with UnknownEdgeKind, which does not echo it. The delegation token layout (#2645), which canopy-identity mints and identity_token's validate_delegation validates: DelegationTokenClaims is iss sub aud exp iat nbf jti client_id sid roles programs act auth_time under the header ACCESS_TOKEN_TYP (at+jwt, which a system token carries too), deny_unknown_fields, so purpose, scope, cnf or any other claim refuses the payload and neither access token parses as the other. sub is a SubjectId and sid a SessionId, each a UUID of any version; mint() makes a new one as a UUID v7 (#2712), Display writes the hyphenated lowercase UUID, and FromStr reads any form Uuid::try_parse does, refusing anything else as InvalidSubjectId or InvalidSessionId, which quote nothing. roles is a RoleSet of RoleNames (^[a-z_]{1,64}$; the issuer holds the vocabulary), non-empty, sorted in byte order and duplicate-free; programs is a ProgramSet of canopy_reference::Program, non-empty, duplicate-free and sorted by wire id (caps, chip, medicaid, snap, tanf, wic). act is an ActorChain, current actor first, which serializes as RFC 8693’s nested {"sub": …, "act": {…}}; the innermost object has no act member, and an explicit "act": null refuses. Parsing refuses a payload that breaks one of these rules; the refusal is the deserializer’s error, whose message names the rule (the typed errors come from building the parts directly: ActorChain::new returns ActorChainError, RoleSet and ProgramSet::try_from return ClaimSetError, RoleName::from_str returns InvalidRoleName): the chain’s innermost actor opens sessions, every other actor is a confidential client that runs as a service, no actor repeats and at most MAX_ACT_DEPTH actors stand; client_id is the current actor and nbf equals iat, which are not stored but derived (client_id(), nbf()), so no value disagrees with them. For the delegation mint (#2720): RoleSet::intersect and ProgramSet::intersect answer the values both sets hold in this set’s wire order, None when they share none, and is_subset whether another set holds every value; ActorChain::extended_by(actor) is the chain an onward mint gives actor, every actor moving one place inward, refused through ActorChainError, in new's order, when the chain would pass MAX_ACT_DEPTH (TooLong), actor runs as no service (ActorNotAService) or actor already stands in the chain (ActorRepeats), so a full chain refuses even a repeat as too long. The lifetime (1 to DELEGATION_TOKEN_MAX_LIFETIME_SECS, 300 s), iss, aud and the last hop’s edge are the validator’s. For security administration (#2731): RoleSet::has_role(role) is a receiver’s role check on a delegation token, under the name xtask’s vocabulary scan reads, and ROLE_VOCABULARY holds security_admin, the role canopy-security’s security-admin routes require.

  • identity_jws (ADR-049 Amendment 3, #2553) — the one compact JWS form canopy-identity’s validators accept. CompactJws::parse(token, max_len) refuses, in order, a token over the cap, anything but three segments, a segment that is not canonical unpadded base64url, a protected header that is not a JSON object of exactly alg, kid and an optional typ (each a string, each once; crit, b64, jwk, jku, x5c, x5u and cty are refused, so no JOSE extension is honoured), an alg other than ES256, a kid that is not a Kid, and a signature that is not a 64-byte r‖s pair (JwsRefusal, which carries none of the token). verify(&VerifyingKey) checks the signature over the signing input as received; claims::<T>() reads the payload only from a JSON object. typ_names(typ, subtype) is RFC 7515 §4.1.9’s media-type equivalence (an optional application/ prefix, case-insensitive). identity_policy holds the client assertion’s CLIENT_ASSERTION_TYP (client-authentication+jwt) and CLIENT_ASSERTION_MAX_LIFETIME_SECS (60).

  • jws_corpus (feature test-helpers, #2553) — the evil-JWS corpus every canopy-identity token parser is held to. A target describes the token it accepts (CorpusInputs: the trusted KeySigner, typ, payload and size cap), and each EvilCase (alg: none, HS256 confusion, an embedded jwk, a signed unknown crit, a signed b64: false, nested JWS, oversize, =-padded base64, a truncated signature, a duplicate header key) differs from it by one attack, signed by the trusted key wherever the attack allows. jws_evil_cases!(setup:, refused:, accepted:) expands to one test per case plus a control test proving the unaltered token is accepted. Only a [dev-dependencies] entry enables the feature (canopy-security’s); cargo xtask feature-builds covers canopy-auth without it.

  • identity_token (ADR-049 §4, §9, Amendment 1; Amendment 3; Amendment 7; Amendment 14; 2555, #2721, #2793, #2794) — the receiver’s validator for canopy-identity tokens. IdentityTokenValidator::new(issuer, receiver, key_source) is built for one compiled CanopyService, its audience the receiver’s audience URI. validate_system(token, request_start) → Result<SystemTokenClaims, IdentityTokenError>, validate_delegation(…) → Result<VerifiedDelegation, IdentityTokenError> and validate(…) → Result<VerifiedBearer, IdentityTokenError> (either kind, verified once, each layout refusing the other’s claims) accept, in order: identity_jws's form within 8 KiB (MAX_TOKEN_BYTES); a typ naming at+jwt (at+jwt or application/at+jwt, case-insensitive, RFC 9068 §4); a kid the key source holds and an ES256 signature under it; exactly one layout, SystemTokenClaims with sub = client_id or DelegationTokenClaims, any other claim refusing as Rejection::Claims; iss and aud exact; exp − iat of 1 to 600 s for a system token and 1 to 300 s for a delegation token, iat and nbf at most 60 s past the request’s start, and the request before exp + 60 s; and the last hop: a delegation token’s current actor has a delegation edge to the receiver (may_delegate, else Rejection::LastHop), and a system token’s client a system edge (may_hold_system_token, else Rejection::SystemEdge), so no purpose could have named a refused pair. VerifiedDelegation holds the claims() and the token as presented, kept for the onward delegation sender; the token zeroizes, its Debug prints only the token’s length, and it is Clone for axum’s Extension. VerifiedBearer is System(SystemTokenClaims) or Delegation(VerifiedDelegation). IdentityTokenError separates Rejected(Rejection) from KeysUnavailable, which fails closed and judges no token. IdentityKeySource ([async_trait], key(kid, request_start) → Result<Option<VerifyingKey>, KeysUnavailable>, VerifyingKey re-exported from p256) is where the keys come from. HttpJwksKeySource::new(jwks_uri, IdentityHttpClient) fetches canopy-identity’s JWKS: on first use, once the set is 300 s old (JWKS_REFRESH), and on an unknown kid, every attempt at least 30 s after the last (UNKNOWN_KID_DEBOUNCE), concurrent lookups sharing one fetch, which runs on a task the shared key cache owns so a dropped lookup never cancels it (ADR-049 Amendment 6); a set is dated by the fetch’s start less its Age, and past 720 s (STALE_AFTER) at the request’s start the source answers KeysUnavailable, a failed fetch keeping the held set until then; a 64 KiB body cap (JWKS_BODY_CAP), keys that are not ES256 P-256 signing keys skipped, a kid listed twice refusing the set, an empty set valid. start_refresher() (Amendment 14; true when it started one) spawns the source’s refresher on the current Tokio runtime: a tick every 30 s, the first at once, fetching whenever no set is held or the set is 240 s old, so while the issuer answers the set is replaced before 280 s (ticks on time) whether or not lookups arrive, and a revoked key stops verifying within 300 s, a bound that rests on the next rule, not on tick timing. While the refresher is live (it ticked within 60 s) and the latest fetch that ran failed, a set up to 720 s old answers a lookup that finds its kid without waiting on a fetch; without a live refresher, or after a fetch that succeeded, the rules above hold unchanged, and the outage rule never answers an unknown kid. The refresher holds the source weakly, ends at its first tick after the source is dropped, and its task clears its own liveness however it ends (aborted, its runtime shut down, or a panic); it starts none while one is live, or with no runtime. The upstream key source starts no refresher. IdentityHttpClient::new() is the bounded, redirect-refusing client every canopy-identity call uses; IdentityHttpClient::bound_to(IpAddr) is the same client connecting from one local address, as the identity capacity harness’s senders do (#2756). canopy-security’s in-process source is identity::key_source::MemoKeySource over the JWKS memo.

  • identity_receiver (ADR-049 Amendment 14; Amendment 15; #2795, #2796, #2797, #2801) — canopy-identity’s receivers, one in front of every service’s /v1. Principal is the caller a validated bearer names, built From<VerifiedBearer>: User(UserPrincipal) from a delegation token or System(SystemPrincipal) from a system token, the portal among the latter. UserPrincipal holds the VerifiedDelegation, the token kept for the onward sender (delegation()), and answers subject(), session(), roles(), programs(), actor_chain(), current_actor(), auth_time(), jti(), exp() and oidc_subject() (the canopy subject as an OidcSubject); SystemPrincipal answers client(), purpose(), scopes(), has_scope(scope) (never for an empty scope), jti() and exp(). Principal::user() and system() are Options; client() is a system token’s client or a delegation’s current actor; has_role(role) is false for a system caller; actor() → Result<Actor, ApiError> is Actor::Human named by the canopy subject’s hyphenated form (equal, through the seed links, to the subjects rows already hold) or Actor::Service named by the client id; attribution_sub() → String is the same name as a string, for records that store one (a system token’s sub is its client id). Admission is a route’s admission: const, never empty, built from arms — starts Admission::system(), system_from(&[ConfidentialClient]), portal(scope), user_roles(roles) and user_roles_via(&[Client], roles), and and_system(), and_portal(scope), and_user_roles(roles) and and_user_roles_via(actors, roles), each setting its arm and replacing one already set, so a route names each arm once. The system arm admits any confidential client but the portal, or the listed ones; the portal arm, canopy-portal holding the scope; the user arm, a user holding a listed role through any actor; the via arm, the same only when the token’s current actor is listed. principal.admit(&admission) refuses with a 403 whose code is the first ReceiverDenial in order: the portal without a portal arm (portal_on_non_portal_route) or scope (portal_scope_missing); a system caller without a system arm (service_class_on_user_only where a user arm exists, else portal_only_route) or off its list (service_not_allowlisted); a user without a user arm (system_caller_required where a system arm exists, else portal_only_route), through an actor no user arm admits (actor_not_allowed), or holding none of the roles (required_role_missing). require_owned_application, require_owned_household and require_owned_person(ownership, id) are the portal ownership checks after admission: inert for every caller but the portal, which needs a claim binding the resource (ownership_claim_missing, ownership_mismatch). xtask’s role-vocabulary scan reads the roles the user arms name. Admission's arms are readable (system_arm() as a public SystemArm — None, Any or From(clients) — portal_scope(), user_arm(), via_arm()). delegated_routes() (Amendment 15; Amendment 16; #2801, #2809) lists the 120 routes a user’s delegation reaches through a named actor, each a DelegatedRoute { name, service, method, path, admission } whose admission carries one via arm naming those actors (canopy-web, canopy-cli, or a service delegating onward) with the roles their gates let through; verification’s SOLQ adapter route admits canopy-eligibility’s system tokens and, via canopy-eligibility, the writer bar. Each row’s admission is a named constant in canopy_auth::delegated, for the row’s handler to admit with (principal.admit(&delegated::PERSONS_GET_PERSONS_ID_ASSETS)?), named <SERVICE>_<METHOD>_<PATH WORDS> (the path’s segments without v1, braces and separators, camelCase split, uppercase) and recorded as the row’s name; its tests hold every row’s name to that rule, every via actor to a delegation edge, every kept system arm to a system caller other than the portal (so appeals, wic, reporting and notices drop theirs), each row’s admissions and refusals, and the deliberate rows' arms. The layer (#2796) is identity_receiver_middleware, installed with axum’s from_fn_with_state and an IdentityReceiver state: IdentityReceiver::new(validator) over any IdentityKeySource (canopy-identity’s JWKS over HTTP, or canopy-security’s in-process registry), with_applicant_verifier(verifier) for a service that reads the portal’s applicant claims. In order, a request carries exactly one Authorization header whose scheme is Bearer, compared case-insensitively, followed by one RFC 6750 b64token, else 401 token_missing with the challenge Bearer; carries no X-Canopy-Actor, else 400 actor_header_retired, before any key is looked up; holds a token the validator accepts at the wall clock within RECEIVER_KEY_BUDGET (2 s), else 401 token_rejected with Bearer error="invalid_token", or 503 keys_unavailable when no trustworthy key set answered in time; and carries an X-Canopy-Applicant claim only from the portal, verified once, else 403 applicant_claim_not_portal, applicant_claim_unverifiable (no verifier) or applicant_claim_invalid (a refused or repeated claim). An admitted request gains the Principal and, from the portal, the ApplicantOwnership as extensions. Only a token failure answers 401, each with its challenge. A refusal logs its code, and a rejected token its validator rule, never the token or the claim. IdentityReceiver::over_http(&IdentitySettings, receiver, IdentityHttpClient) (#2797) builds a receiver over an HttpJwksKeySource at the settings' JWKS URL with its refresher started.

  • identity_admin (ADR-049 Amendment 20; #2830) — canopy-security’s admin routes on the wire, shared by the routes and their clients so the contract has one source. ADMIN_PATH (/identity/admin) and ADMIN_BODY_LIMIT (4096 bytes). The request bodies (ReasonBody, CreateSubjectBody, LinkBody, each deny_unknown_fields) keep String fields, so the server answers each field’s own 400 code in its order; the lookup query UpstreamPair ignores other parameters. The input rules are checked types, each the one Rust source of its rule, which the server calls after parsing and a client sends: AdminReason::parse (1 to 200 bytes, no control character), CheckedPair::new(iss, sub) (the issuer 1 to 2048 bytes of visible ASCII, the subject 1 to 255 of printable ASCII), canonical_uuid (lowercase hyphenated only), NewSubjectId::parse (canonical and not nil, refusing Malformed or Nil) and AdminKid::parse (an RFC 7638 thumbprint whose last character carries zero padding bits); each refusal’s Display is the server’s message, and AdminReason's and CheckedPair's Debug print no reason and no upstream subject. The answers carry ids as their newtypes (SubjectId, SessionId, and ActionId for an action row), absent options as null and times as RFC 3339: SubjectRef, SubjectView with LinkView and SessionView (its opener text), Recorded { action_id, changed }, KeyList of KeyView, ClientList of ClientView (its client text, its kind a ClientKind, ClientKind::of(Client)). AdminProblem::read(body) is the problem body’s code, none for a body that is not JSON. No database dependency: canopy-security maps its rows onto the views. AdminClient (#2831), behind canopy-web’s security-administration pages: AdminClient::new(&IdentitySettings, IdentityHttpClient) calls the routes under admin_url(), one method per route over the request’s WebOutbound (lookup_subject(&CheckedPair), subject(SubjectId), create_subject(NewSubjectId, &AdminReason), suspend, lift, revoke_session(SessionId, …), link(&CheckedPair, SubjectId, …), keys(), revoke_key(&AdminKid, …), clients(), disable_client and enable_client(Client, …)), its bearer a delegation for canopy-security on canopy-web’s Both edge, taking only checked inputs. A write whose JSON is over ADMIN_BODY_LIMIT is BodyTooLarge before a bearer is had or anything sent. Each attempt is bounded by the lesser of ADMIN_CALL_TIMEOUT (6 s: the server’s 5 s budget and a second of transport) and what remains of the request. A 401 whose WWW-Authenticate challenge or problem code is insufficient_user_authentication (RFC 9470) is StepUpRequired { max_age }, the challenge’s max_age else 600 s, never retried; the guard’s refusal of the bearer (refuses_the_bearer: a 401 whose Bearer challenge names no error or invalid_token) calls rejected(Security) and retries once with a new bearer, unless less than RETRY_FLOOR (1 s) remains, and a 401 under no Bearer challenge is final at once, its token kept; a final 401 is SessionEnded (session_ended, session_refused), ClientDisabled or Unauthorized(code). Otherwise 403 Forbidden, 400 Invalid(code), 404 NotFound(code), 409 Conflict, 413 TooLarge, 429 Limited (never retried), 503 Unavailable(code), any other status Status(u16), Timeout, Transport (its URL dropped, as the lookup’s carries an upstream subject), Malformed for a success that is not its view, and Send(WebSendError); a problem body that is not JSON gives no code. step_up_options() asks for max_age STEP_UP_MAX_AGE (300 s) without prompt=login: with the relying party’s 60 s leeway a stepped-up session is at most 360 s old, which a const assertion holds under the server’s 600 s, leaving 240 s of administration; the session it replaces ends through WebSessionEngine::supersede.

  • identity_settings (ADR-049 Amendment 14; Amendment 16; #2797, #2808) — canopy-identity’s settings as receivers and senders read them, which canopy-api’s bootstrap builds from ServiceSettings' required identity_issuer and identity_internal_url. IdentitySettings::new(issuer, internal_url, development) holds each URL to identity_url's rules, a defect naming its setting (ISSUER_SETTING, identity_issuer; INTERNAL_URL_SETTING, identity_internal_url, the ServiceSettings fields' names). issuer() is the identifier exactly as written and issuer_url() the same as a URL, a client assertion’s aud; jwks_uri(), token_endpoint(), revocation_endpoint(), device_verification_endpoint() (Amendment 21; #2836) and admin_url() (Amendment 20; #2831) are the jwks, token, revoke, device_verification and admin endpoints under the internal URL, the last at ADMIN_PATH. device_authorization_endpoint() is the device_authorization endpoint under the internal URL, and metadata_url() the issuer’s RFC 8414 metadata at METADATA_PATH on the internal URL’s origin, the two routes canopy-web’s edge forwards beyond the token, revocation and JWKS endpoints (Amendment 22; #2844).

  • identity_sender (ADR-049 Amendment 16; #2808) — canopy-identity’s sender, which canopy-api’s bootstrap builds for each service that runs as a confidential client. IdentitySender::over_http(&IdentitySettings, ConfidentialClient, Arc<dyn KeySigner>, IdentityHttpClient) and from_secrets(&IdentitySettings, ConfidentialClient, &dyn SecretProvider, IdentityHttpClient) build a service’s one sender: its key, and one SystemTokenSource and one DelegationTokenSource over it. from_secrets reads the key through the provider alone under client_key_secret(client) (CANOPY_<SERVICE>__IDENTITY_CLIENT_PRIVATE_KEY); over_http signs with a signer its caller built. A client that runs as no service (canopy-web, canopy-portal) is SenderError::NotAService, before any key is read, and a key that cannot be loaded SenderError::Key. calls(Origin) opens one request’s Outbound with its delegation cache; Origin::of(&Principal) is User(&VerifiedDelegation) for a user and System for a system caller, the portal included, and a detached or background task, a durable retry or boot uses Origin::System. Outbound::bearer(target) takes the token from the compiled edge and the origin: no edge is SendError::NoEdge; a System edge takes a system token whatever the origin; a Delegation edge delegates the user onward, never narrowed, and refuses a system origin (SystemOrigin); a Both edge goes by origin. system_bearer(target) asks for a system token on a System or Both edge (NoSystemEdge on a delegation-only one). A local refusal sends nothing, and system tokens are asked for with no scope. Each acquisition is bounded by SENDER_BUDGET (6.5 s, DELEGATION_BUDGET plus a second), else SendError::Timeout; the other errors wrap SystemTokenError and DelegationError. rejected(target), after a receiver’s 401, invalidates the target’s system token and forgets the request’s delegation tokens for it, so the caller’s one retry asks again; the sender never retries on its own. A Bearer is read through expose_for_call(), is_delegation() names its kind and its Debug prints nothing more; owned() is an OwnedBearer, which zeroizes and has no Clone, Debug or Display, for a task the request spawns.

  • identity_web_sender (ADR-049 Amendment 19; #2826) — canopy-web’s sender, built at boot; a middleware opens each request’s WebOutbound. WebSender::over_http(engine, &IdentitySettings, Arc<dyn KeySigner>, IdentityHttpClient) and from_secrets(engine, &IdentitySettings, &dyn SecretProvider, IdentityHttpClient) (the key under client_key_secret(ConfidentialClient::Web), CANOPY_WEB__IDENTITY_CLIENT_PRIVATE_KEY, no file fallback) build canopy-web’s one sender over the session engine: a cheap Clone holding a DelegationTokenSource and a SystemTokenSource over canopy-web’s key. calls(key, LiveSession, deadline) opens one request’s WebOutbound over the record at key, which owns what it holds (Send + Sync + 'static, so canopy-web can share it through an Arc). bearer(target) takes the bearer from canopy-web’s compiled edge: a Delegation or Both edge mints from the session, never narrowed (canopy-web’s narrowing would cap every onward hop); a System edge takes a system token; no edge is WebSendError::NoEdge and sends nothing. system_bearer(target), on the outbound for an in-request system call and on the sender for a detached task, works on System and Both edges only (NoSystemEdge). Each target has one slot for the request, never removed: calls to different targets mint concurrently, calls to one target share its mint, and callers queued behind a failed attempt, one its bound cancelled included, answer SharedFailure instead of minting again. rejected(target), after a receiver’s 401, bumps the target’s epoch, so no caller, queued or new, is served the rejected token (a token minted across it goes to its own caller uncached), and invalidates its system token; the caller retries once. Every bearer is an owned, zeroizing OwnedBearer, and each mint attempt is bounded by the lesser of SENDER_BUDGET and what remains of the request’s deadline (Timeout), a stale call’s renewal by what remains less one second. WebSendError is NoEdge, NoSystemEdge, Timeout, SharedFailure, System, Delegation, SessionEnded, RenewalPending or Store; none carries a token or credential. The sender never fails open. For its renewal (#2827), a mint refused session_stale renews the session once per request, through WebSessionEngine::maintain_now at the served version within what remains less one second for the retry, which every concurrent stale call shares; a successful renewal bumps the request’s renewal epoch, so no pre-renewal token is served again, and each stale call retries its mint once, a second session_stale being Delegation. A renewal that does not advance fresh_until, or too little time to try, is RenewalPending with no retry. session_ended and subject_suspended end the record through end_refused and answer SessionEnded; any other refusal, a 429 included, is its typed error with no retry.

  • identity_call (ADR-049 Amendment 16) — one outbound call to a canopy-identity receiver. BearerSource (bearer(target) → Result<OwnedBearer, BearerError> and an async rejected(target)) is where a call’s bearer comes from: a service’s IdentitySender for system-origin work, a request’s RequestOutbound or SharedOutbound, canopy-web’s WebOutbound, the PortalSender and canopy-cli’s DeviceClient. request_outbound_middleware, installed inside the receiver layer with the service’s sender, inserts each request’s RequestOutbound (RequestOutbound::of(sender, &principal): onward delegation for a user, system tokens for a system caller, one delegation cache per request); a handler that asks for one on a request without a Principal fails closed (500). send_with_retry(source, target, deadline, build) sends once and, after a receiver’s refusal of the bearer (refuses_the_bearer: a 401 whose Bearer challenge names no error or invalid_token), drops the target’s tokens and sends once more while RETRY_FLOOR (1 s) of the deadline remains; a step-up 401, a route’s own 401 and a second refusal are returned as they came. CallError carries no token and no URL. FixedBearer (feature test-helpers) answers one fixed token, for a test whose receiver is a stub.

  • identity_portal_sender (ADR-049 Amendment 23; #2852) — canopy-portal’s sender, through which every portal call goes. PortalSender::over_http(&IdentitySettings, Arc<dyn KeySigner>, IdentityHttpClient) and from_secrets(&IdentitySettings, &dyn SecretProvider, IdentityHttpClient) (the key under client_key_secret(ConfidentialClient::Portal), CANOPY_PORTAL__IDENTITY_CLIENT_PRIVATE_KEY, no file fallback; a missing key is SenderError::Key) build the portal’s one sender: a SystemTokenSource over its key. bearer(target) → Result<OwnedBearer, SendError> asks for the portal’s system token for target, with no scope, so it carries every scope of its purpose, within SENDER_BUDGET (SendError::Timeout), as an owned, zeroizing copy; a target off the portal’s nine compiled System edges is SendError::NoEdge, with nothing sent. rejected(target) drops the target’s cached token after a receiver’s refusal of it, so the caller’s one retry asks again; the sender never retries on its own. The portal holds no user token, and the applicant’s claim stays portal-signed.

  • identity_web_session (ADR-049 Amendment 18; 2820) — canopy-web’s session engine, over canopy-web’s PgWebSessionStore. A WebSessionRecord is a worker’s web session as canopy-web keeps it: the FederatedSession, the UpstreamBinding (the profile’s issuer and client_id as written at sign-in), the optional UpstreamRefreshToken, the latest upstream id_token (for logout’s hint) and maintain_at; its fields are public so a store restores it from its own columns, and it has no Debug, Clone or Serialize. WebSessionStore ([async_trait], Send + Sync + 'static, its own Key) is the contract canopy-web’s refresh claim (#2224) states, each call bounded by its within and answering StoreFault::{Timeout, Unavailable}: view (a SessionRow: RecordVersion, ClaimState::{Free, Live, Lapsed}, and the record, None for a row that no longer decodes); claim(key, version, ClaimId, lease) (only at that version with no claim, the lease on the store’s clock, answering Claimed::{Record, Undecodable, Nothing}); commit (only under the claim, live or lapsed, stepping the version and freeing the row); release (only a live claim); end_claimed and end_lapsed (only under the claim, the latter once lapsed, as RefreshLost); end(key, reason) (unconditional, answering the record it ended in the same step); and end_reason. Every write steps the version, an ended key is never live again, and a lapsed claim is never cleared. WebSessionEndReason spells the engine’s signed_out, expired, identity_refused, upstream_ended, upstream_changed and refresh_lost, and canopy-web’s own superseded, idle and operator (as_str, parse). Feature test-helpers adds identity_web_session::contract::check(store, seed, corrupt) → Result<(), ContractViolation>, the contract as a suite any store runs (canopy-web’s PgWebSessionStore runs it, and its PgNativeStore runs it and check_due), with sample_record(now), and memory::MemoryWebSessionStore, an in-process store that decodes every read from stored columns and offers fault hooks (edit, end_with, drop_next_commit_ack, fault_next_claim, foreign_clear, corrupt, delay_ops) and claim and commit counters. WebSessionEngine::new(UpstreamRelyingParty, FederationClient, store) (#2821) keeps sessions fresh, a cheap Clone that each leader it spawns shares; store() and relying_party() reach its parts. current(key, budget) → Result<LiveSession, Unserved> serves within one absolute deadline covering every read, poll, wait and cleanup, each store call bounded by the lesser of STORE_OP_TIMEOUT (2 s) and what remains: a session bound to another upstream ends UpstreamChanged before anything is presented; a lapsed claim ends it RefreshLost; a fresh one (fresh for SERVE_MARGIN, 15 s, more) is served, and when due a detached leader maintains it; a stale one with no refresh token or within SERVE_MARGIN of its end ends Expired; a stale, due one is led, or waited on while another leader’s claim is live; otherwise, or past the deadline, Unserved::Pending. LiveSession holds the version and the FederatedSession, never an upstream token; Unserved is NoSession, Ended(WebSessionEndReason), Pending or Store(StoreFault). A leader claims with CLAIM_LEASE (60 s, outlasting every store write it makes), refreshes upstream within UPSTREAM_TOKEN_TIMEOUT, and renews by the profile’s renewal() evidence: a successful refresh’s rotated tokens are stored whatever the renewal answers, unless the answer ends the session, each kept from the record when the grant omits it; a refresh the upstream did not process asks for grace (not_processed) only when fresh_until is within FRESHNESS_LEAD (120 s); canopy-identity’s session_ended, upstream_refused, projection and subject_suspended refusals end the session IdentityRefused, and an upstream refusal ends it UpstreamEnded; anything else keeps the session, retried after MAINTENANCE_RETRY (30 s). The next maintenance is the earliest of the grant’s refresh_due(), fresh_until less FRESHNESS_LEAD and VALIDATION_CADENCE (780 s) ahead, never sooner than 30 s; a renewal fresher than a validation now could make (900 s plus 60 s) is a grace, retried in 30 s. The successor is stored with canopy-web’s commit recovery (COMMIT_RECOVERY_CAP, 6 s); one whose session ended under the leader is revoked upstream only after a SignedOut or Operator end, and a row found live at the claimed version without the claim after a presented token ends RefreshLost. Every end a request or leader writes and sees acknowledged, but IdentityRefused, revokes canopy-identity’s session in a detached task within 2 s; sign-out revokes it inline, and end_refused (below) revokes only for a suspended subject. UpstreamRelyingParty::renewal() and binding() (the profile’s issuer and client_id as written) feed it. complete_sign_in(pending, returned_state, code, redirect_uri) → Result<WebSessionRecord, SignInError> (#2822) redeems the code through the relying party, then opens canopy-identity’s session (with the upstream access token only under a userinfo profile), and answers the record, bound and scheduled, for canopy-web to insert under its own key; SignInError is RelyingParty(RelyingPartyError) or Federation(FederationError) (AuthTimeTooOld is the cue for prompt=login), and a failed open revokes the grant’s refresh token. sign_out(key, post_logout_redirect_uri) → Result<SignedOut, StoreFault> ends the record first, the end answering it, then revokes canopy-identity’s session within 2 s, then uses the upstream’s end-session endpoint with the id_token as its hint or, with none, revokes the upstream refresh token; with no record, or one bound to another upstream, it still offers the configured upstream’s end-session endpoint without a hint and sends nothing of the record’s. SignedOut { ended, identity_revoked, upstream } reports each leg, UpstreamSignOut being EndSession(Url), Revoked, RevocationFailed or PromptLogin (every variant but EndSession leaving canopy-web to send prompt=login next); its Debug never prints the end-session URL, which carries the hint. A failed leg never stops the others; a store fault at the end revokes nothing. For canopy-web’s sender (Amendment 19; #2825), maintain_now(key, seen, budget) forces maintenance at the served version seen whatever the local freshness, since canopy-identity found the session stale: single-flight through the claim at the version, served as current would once another leader moved past seen, ending an unbound record, a lapsed claim, or a record with nothing to renew it, and holding the 30 s retry spacing while the local freshness is near its end. end_refused(key, refusal, budget) ends the record IdentityRefused after canopy-identity refused a mint, revoking canopy-identity’s session only for SubjectSuspended, which canopy-identity itself revokes only at a renewal. An engine maintains sessions of one kind (Amendment 21; #2837): WebSessionEngine::new's are web sessions, and NativeSessions holds one of kind native, whose renewals present the native-revalidation type both ways and schedule NATIVE_FRESHNESS_LEAD (300 s) before freshness ends, and which revokes upstream, best-effort, every refresh token it holds for a record bound to its upstream at any end, UpstreamEnded included, the grant being the native session’s alone; a web engine’s ends are unchanged. supersede(key) → Result<Replaced, StoreFault> (Amendment 20; #2831) ends the record a step-up replaced as Superseded and revokes only its canopy-identity session within 2 s, sending the upstream nothing, so neither the old refresh token’s revocation nor a leader’s revocation of its rotated successor can end the session that replaced it; Replaced { ended, identity_revoked } reports it, and a store fault revokes nothing. DueSessions: WebSessionStore (Amendment 21; #2838) adds due(now, limit, within) for the native sweep: the live rows whose maintain_at is at or before now, earliest first, at most limit, whatever their claim and whether or not their rows still decode; a web store needs none of it. The memory store implements it, and feature test-helpers adds contract::check_due(store, seed, corrupt), holding a store to it.

  • identity_url (ADR-049 §2; Amendment 14; #2797) — canopy-identity’s mount URLs, shared by canopy-security’s issuer settings and every receiver’s. IDENTITY_PATH (/identity) is the whole path of the issuer identifier and the parent of its endpoints. The routes canopy-security serves are its constants, one source for every crate that names them (Amendment 22; #2842): TOKEN_PATH, REVOKE_PATH, DEVICE_AUTHORIZATION_PATH, JWKS_PATH and METADATA_PATH (/.well-known/oauth-authorization-server/identity, RFC 8414 §3.1), and MAX_FORM_BYTES (64 KiB), the longest form body canopy-identity reads. identity_url(name, value, development) accepts an absolute https URL (http too under development) with no userinfo, query or fragment, whose path is exactly IDENTITY_PATH, written in canonical form so its string is exactly value; else the first IdentityUrlError (Unparseable, Userinfo, Scheme, Query, Fragment, Path, NotCanonical), each naming the setting; none quotes the value, and NotCanonical gives only its canonical spelling, which holds no userinfo. identity_endpoint(name, base, segment) builds an endpoint under a mount by path segment. canopy-security’s IssuerConfig converts each defect one for one into its own IssuerConfigError.

  • upstream (ADR-049 Amendment 5; Amendment 6; 2692, #2693, #2694, #2695, #2696, #2697, #2713) — canopy-identity’s upstream identity provider, which canopy-security’s federation grant and canopy-web’s sign-in federate through. UpstreamProfile is the deployment’s one upstream profile, <config root>/identity-upstream.yaml (UPSTREAM_PROFILE_FILE, Configuration reference). UpstreamProfile::load(config_root, development) and load_from(path, development) return Result<Option<UpstreamProfile>, UpstreamProfileError>, None when the file is absent; parse(yaml, development) returns the profile or the refusal; path_in(config_root) is the file’s path. The file is read through the config crate and taken apart by hand into a wire enum tagged by profile (kanidm, keycloak, zitadel or oidc-generic; ADR-049 Amendment 26), each variant refusing a field its file may not state, so that every refusal names its field: UpstreamProfileError is Read, NotAMap, UnknownProfile, Missing, PresetField (a vendor file stating a preset field), UnknownField or Invalid { field, fault: UpstreamFieldFault }, and never quotes a value. The resolved profile, its vendor’s presets filled in (a zitadel profile’s ZitadelIds too, its project and organisation), holds kind() (ProfileKind); issuer() (UpstreamIssuer: as_str() exactly as written, the string iss is compared with, and url() parsed; canonical or a bare origin without its /, with no userinfo, query or fragment, https unless development); client_id() (UpstreamClientId, 1 to 255 bytes of printable ASCII, not a Client); algorithms() (UpstreamAlgorithms, a non-empty set of UpstreamAlgorithm: ES256, ES384, RS256, PS256 and EdDSA, each binding one UpstreamKeyType through key_type(): P-256, P-384, RSA of at least MIN_RSA_MODULUS_BITS (2048) bits, Ed25519); claims_from() (ClaimsFrom); refresh() (RefreshRenewal, whose renews(claims_from) says whether it reads the claims from that source), the two naming one source (id_token with reissues_id_token, userinfo with userinfo) or the file is refused as Invalid { field: "refresh", fault: MixedSources }; client_auth_method() (UpstreamClientAuth: client_secret_basic or client_secret_post); claims() (ClaimPointers, the roles, programs and username JsonPointers: RFC 6901 pointers, validated at parse, JsonPointerError naming a pointer that is not rooted or holds a bad ~ escape; and shape(), the roles' and programs' ClaimShape: Array, or ObjectKeys { organization }, which only the zitadel preset sets and no file can state); and the optional jwks_uri() and userinfo_endpoint() (url::Url: https unless development, no userinfo or fragment, a query allowed) and tls_trust_anchors() (TrustAnchorFile, one bare file name, resolve_in(config_root)). TlsTrustAnchors::load(file, config_root) reads the bundle a TrustAnchorFile names, at most MAX_TLS_BUNDLE_BYTES (1 MiB), with the PEM parser of rustls' pki-types, and refuses it (TlsTrustAnchorsError: Read, TooLarge, or Invalid { path, fault: TlsBundleFault }) when it is malformed PEM (MalformedPem(PemFault)), holds a section other than a certificate (NotACertificate, naming its position and kind), holds a -----BEGIN marker anywhere that yielded no section (UnreadBlock: the parser silently skips a label it does not know, such as ENCRYPTED PRIVATE KEY or OPENSSH PRIVATE KEY), holds no certificate (NoCertificate), or holds a certificate rustls cannot use as a trust anchor (UnusableCertificate); no refusal quotes the bundle. The anchors give count(), iter() over TlsTrustAnchor (der(), fingerprint()) and fingerprints() (Sha256Fingerprint, displayed as OpenSSL prints one). UpstreamHttpClient::new(anchors, development) builds, with no request, the one client every upstream call goes through, in one builder chain: UPSTREAM_CONNECT_TIMEOUT (2 s), UPSTREAM_REQUEST_TIMEOUT (2.5 s, body included), no redirect, https only unless development, and the built-in roots switched off exactly when anchors are given, each anchor then added as a root; with none it trusts reqwest’s built-in roots. The system proxy (HTTPS_PROXY) applies. Feature test-helpers adds resolving(anchors, development, host, address), the same client resolving one host to a fixed address (the Kanidm lane). get(url, headers) answers an UpstreamResponse once the status and headers arrive (status(), headers()); the caller judges the status, then reads body(limit) through read_capped_body. UpstreamRequestError is UrlRefused, Connect, Tls or ConnectTimeout (no request sent), Timeout or ConnectionLost (the upstream may have received it), or TooLarge, and carries neither the URL nor any of the response; UpstreamClientError is a TLS backend that could not be built. UpstreamKeySource::new(profile, http, development) (or with_clock(…, clock), an IdentityClock) holds the upstream’s discovery and keys, fetched on first use, never at boot, under the rules identity_token's HttpJwksKeySource follows, through the crate-private key cache both instantiate: refreshed once 300 s old, an unknown kid refetching at most once per 30 s, concurrent lookups sharing one fetch, and a set 720 s stale at the request’s start answering UpstreamKeysUnavailable, a failed fetch keeping the held set until then. Each fetch runs on a task the cache spawns and owns, which every lookup needing it awaits, so a lookup dropped or past its deadline, whether a key lookup or userinfo’s endpoint lookup, never cancels it: the fetch completes and installs its set for the next lookup. An attempt is stamped for the 30 s debounce, dated at its start, once it has run, whether it completed or its task ended without a result (a panic), so a repeating panic is held off like a failure; a fetch with no runtime to run on is not stamped. Each fetch reads discovery, <issuer>/.well-known/openid-configuration (the issuer as written, one trailing / dropped), then the JWKS, each request sending Cache-Control: no-cache and each body capped at UPSTREAM_DOCUMENT_CAP (64 KiB); anything but a 200 fails the fetch. Discovery must be a JSON object whose issuer is a string equal to the profile’s exactly and whose jwks_uri and userinfo_endpoint are each absent or a string (null is malformed, not absent), none of the three repeated; the profile’s jwks_uri and userinfo_endpoint win over discovery’s, and a discovered one must pass the endpoint rule and share the issuer’s origin; jwks_uri is required unless the profile names one. The set is dated by the fetch’s start less the larger of the two responses' Age (absent is 0, malformed fails the fetch), so an older cached copy never replaces a newer set. The JWKS must be a JSON object holding keys once, as an array. Each JWK is judged on its own: skipped when it is not an object, when a member it is judged by is present and not a string (null included) or appears twice, when its use is present and not sig, when it has no kid, or when its key type fits none of the profile’s algorithms, a declared alg binding it to that one alone, which must be the profile’s; two kept keys under one kid refuse the set. key(kid, request_start) answers the UpstreamKey under an UpstreamKid (opaque, compared exactly): decoding_key() (jsonwebtoken’s DecodingKey), permits(alg) and algorithms(). userinfo_endpoint(request_start) answers the profile’s or discovery’s userinfo endpoint, read without a kid. UpstreamIdTokenValidator::new(profile) and validate(token, keys, now) → Result<VerifiedUpstreamIdToken, UpstreamIdTokenError> verify an upstream id_token, with now injected (production passes chrono::Utc::now()) and keys an UpstreamKeys ([async_trait], key(kid, request_start)), which UpstreamKeySource implements. A header pre-check runs before any key is looked up: at most MAX_UPSTREAM_ID_TOKEN_BYTES (16 KiB) and three segments; a canonical base64url header holding alg, kid, an optional typ and the ignored x5t and x5t#S256, each a string and each once, and no other member (crit included); alg among the profile’s; and a typ naming application/jwt (typ_names, so at+jwt refuses). The kid's key must permit alg; jsonwebtoken then checks the signature and judges no claim’s value (no claim required, its exp, nbf and aud checks off), and the payload must be a JSON object naming each claim once, in which no object nested in a claim, at any depth, names a member twice either. jsonwebtoken still parses the registered claims, and refuses as a malformed payload only a shape its parser cannot step over: an array or object sub, or a non-empty array or object exp or nbf. The validator judges every claim itself: iss byte for byte; aud exactly the client (the string, or an array of it alone, so another audience refuses whatever azp says); azp, when present, the client; sub an OidcSubject; exp, iat and auth_time present and every time claim a NumericDate (a finite JSON number truncated to whole seconds within i64); exp after now − 60 s, nbf no later than now + 60 s, iat at most 300 s old and 60 s ahead, auth_time no later than iat + 60 s or now + 60 s; a nonce a string, returned unjudged; amr and acr never read. VerifiedUpstreamIdToken holds the UpstreamAnchor (iss(), sub(), auth_time() as a NumericDate, nonce()), issued_at() (its iat, a NumericDate) and the whole payload(), which its Debug omits; the anchor’s Debug prints only the lengths of the subject and the nonce. UpstreamIdTokenError separates Refused(UpstreamIdTokenRefusal), naming the broken rule (with a TimeClaim for a missing or malformed time claim) and none of the token, from KeysUnavailable. UpstreamUserinfo::new(profile, http) and fetch(access_token, expected_sub, keys, now) → Result<UpstreamUserinfoClaims, UpstreamUserinfoError> call userinfo for the subject a verified id_token names (OIDC Core §5.3.2): the access token a Zeroizing<String>, expected_sub an OidcSubject, keys the same profile’s UpstreamKeySource and now injected. The endpoint is the profile’s userinfo_endpoint, called without consulting discovery, else the one discovery advertises. The request is one GET with Accept: application/json and Authorization: Bearer <token>, its value marked sensitive so reqwest and hyper never print it; a token longer than MAX_UPSTREAM_ACCESS_TOKEN_BYTES (8 KiB) or not an RFC 6750 b64token is never sent, refused before the endpoint is looked up. Only a 200 is read, with exactly one Content-Type whose essence is application/json (any case, parameters such as ; charset=utf-8 tolerated, so a signed application/jwt answer refuses), a body of at most UPSTREAM_USERINFO_CAP (64 KiB) that is a JSON object in which no object, at any depth, names a member twice (the crate-private reader the id_token payload shares, so a claim read through a nested pointer cannot resolve to either of two values), and a sub that is a string equal to expected_sub byte for byte. UpstreamUserinfoClaims holds every claim answered (claims(), into_claims()), which its Debug omits. UpstreamUserinfoError is the userinfo call’s three outcomes, none carrying the token, nor anything of the answer but its status: Unavailable(UpstreamUserinfoUnavailable) (Request for a Connect, Tls, ConnectTimeout, Timeout or ConnectionLost, a body cut short included; Status for 408, 425, 429 or a 5xx; Discovery when no endpoint is named and discovery is unavailable), which renews an existing session within its grace and fails a sign-in; Refused(StatusCode) for any other 4xx; and Invalid(UpstreamUserinfoInvalid) (AccessToken, NoEndpoint when neither the profile nor discovery names one, UrlRefused, Status for a 1xx, a 3xx, another 2xx or one past 599, MediaType, TooLarge, Body, NoSubject, SubjectMismatch); a renewal sorts each outcome into its verdict (RenewalVerdict, below). upstream::project(profile, anchor, claims) → Result<FederatedIdentity, ProjectionRefusal> projects a verified identity: a ProjectionAnchor (the issuer, subject and authentication time, built From<&UpstreamAnchor>, which only the validator builds, so the validator stays the one route from token bytes to an anchor, or From<&StoredAnchor>, a caller contract the type cannot enforce: StoredAnchor::new checks nothing about where its values came from, so canopy-security builds one only from its own session row, written from a validator’s anchor) and the claims payload the profile’s claims_from() names, the verified id_token’s payload() or userinfo’s claims(), read through the profile’s ClaimPointers. Roles are the names at the roles pointer, which must be an array of strings (under ObjectKeys, an object, whose keys count only when their value is an object naming the organisation, and whose counted keys are the names), that ROLE_VOCABULARY holds, a name with SERVICE_ROLE_PREFIX never granting and any other name ignored; programs are the canopy_reference::Program wire ids at the programs pointer (chip and medicaid distinct; under ObjectKeys, the counted keys' remainders after PROGRAM_KEY_PREFIX, program_); each list is sorted and deduplicated into identity_policy's RoleSet and ProgramSet. The username at its pointer is a string of 1 to MAX_UPSTREAM_USERNAME_BYTES (256) bytes with no control character (Unicode Cc; format characters such as the zero-width non-joiner are kept), held as an UpstreamUsername (as_str()), whose Debug prints only its length. FederatedIdentity holds iss() (the issuer exactly as written, a &str), sub() and auth_time() from the anchor, roles(), programs() and username(); its Debug prints only the lengths of the subject and the username. ProjectionRefusal, carrying nothing of the claims, is the first of NoRole (no_role: the roles pointer resolving to nothing or to a value not of the profile’s shape, or no vocabulary role left), MissingPrograms (missing_primary_programs: nothing at the programs pointer, or an empty array), MalformedPrograms (malformed_primary_programs: any other shape, null included, or an element that is not a program’s wire id) and NoUsername (no_username: missing, not a string, or out of bounds); code() answers the code. A web session’s renewal judges against StoredAnchor::new(iss, client, sub, auth_time, nonce_digest, last_iat, last_digest), which canopy-security builds from its store: the upstream issuer and client the session opened under (strings as written), the upstream sub (OidcSubject), the original auth_time, nonce_digest(nonce) of the original nonce, and the iat and id_token_digest(token) of the latest id_token recorded, each Option; the two digests are SHA-256 of the nonce’s bytes and of the compact id_token as presented, and its Debug omits the subject and digests. bound_to(&profile) → Result<(), BindingMismatch> compares the profile’s issuer as written and its client with the stored ones byte for byte (Issuer, then Client). upstream::check_refreshed(&stored, &verified, presented_digest) → Result<Refreshed, RefreshMismatch> matches a refreshed id_token the validator accepted (so its aud is exactly the profile’s client): its iss, sub and auth_time the stored ones, its nonce the original’s or none (a nonce where the original had none mismatches); then Replay when the presented digest is the latest recorded, Newer when its iat is after the latest recorded, else NotNewer, a session with no recorded iat refusing as NotNewer. RefreshMismatch (Issuer, Subject, AuthTime, Nonce, NotNewer) and BindingMismatch name the rule, never a value. RenewalVerdict is Revoke(RevokeReason) (UpstreamRefused, ProjectionRefused, UpstreamChanged), Grace or Lapse(LapseReason) (Presentation, Deployment), its classifiers matching every variant by name: classify_userinfo (every Unavailable, Discovery included, is Grace; Refused revokes; Invalid::AccessToken lapses as a presentation defect, NoEndpoint and UrlRefused as a deployment defect, every other Invalid revokes), classify_keys_unavailable() (Grace), classify_id_token (a refreshed id_token the validator refused lapses as a presentation defect; KeysUnavailable is classify_keys_unavailable()'s grace), classify_projection (revokes), classify_mismatch (lapses as a presentation defect) and classify_binding (revokes as UpstreamChanged). canopy-security loads the profile at boot after the client registry, then the anchors it names and the client, logging the anchor count and fingerprints, and its federation grant validates through them; canopy-web loads the same profile for its relying party. For canopy-web’s relying party (ADR-049 Amendment 17; #2814), the profile also holds scopes() (UpstreamScopes: RFC 6749 scope tokens holding openid, each once; iter(), joined() space-separated; the kanidm preset openid profile, which a kanidm file may not state; an oidc-generic file must state it) and endpoint_overrides() (UpstreamEndpointOverrides: the optional authorization, token, revocation and end_session URLs, held to the endpoint rule and not to the issuer’s origin). UpstreamKeySource::endpoints(request_start) answers UpstreamEndpoints, each member a Result<Option<Url>, EndpointFault>: the override when named, else discovery’s member read in a pass of its own, after the key fetch accepted the document, so that none of the four ever refuses the fetch; a discovered one is held to the endpoint rule and the issuer’s origin, else EndpointFault (Null, NotAString, Repeated, Refused(UpstreamFieldFault), CrossOrigin, Unreadable). UpstreamHttpClient::post_form(url, form, auth, timeout) posts a form-urlencoded body with Accept: application/json, authenticated by ClientAuth::{Basic, Post} over a ServiceCredentials (the client id and a zeroizing secret, Debug redacting it; basic_authorization() form-urlencodes both before the Basic encoding, RFC 6749 §2.3.1, and authenticate(request) sets that header marked sensitive, the one encoder the operator tools send client credentials through, #2427) (ClientAuth::of(method, credentials) follows the profile’s client_auth_method: Basic sends ServiceCredentials::authenticate's header, Post adds client_id and client_secret, through ServiceCredentials::client_secret_for_body(), to the form), timeout replacing the 2.5 s request bound for that call, the connect bound and the refusal of redirects kept. UpstreamRelyingParty (Amendment 17; #2815) is canopy-web’s confidential client of the upstream: new(&profile, UpstreamHttpClient, UpstreamClientSecret, development) sends nothing, its client secret read by UpstreamClientSecret::from_secrets(&dyn SecretProvider) under UPSTREAM_CLIENT_SECRET (CANOPY_WEB__UPSTREAM_CLIENT_SECRET) alone (ClientSecretError: Missing, Blank, Unreadable). authorization(redirect_uri, &AuthorizationOptions { prompt_login, max_age }) answers the authorization URL (response_type=code, client_id, redirect_uri, the profile’s scope, a fresh 256-bit state and nonce, an S256 code_challenge, the essential auth_time claim on every request, and prompt=login and max_age only when asked) and the PendingAuthorization, whose expose_for_store() gives the state, nonce, verifier and max_age (StoredAuthorization) and whose restore(state, nonce, verifier, max_age) refuses a malformed value (MalformedAuthorization). redeem(pending, returned_state, code, redirect_uri) refuses a foreign state before any request (StateMismatch), then within one UPSTREAM_TOKEN_TIMEOUT (10 s) deadline (Deadline) exchanges the code with the verifier and the profile’s client auth and holds the answer to RFC 6749 §5.1 (Malformed(AnswerDefect): the body, token_type, expires_in, or a token empty or past its cap), validates the id_token (NoIdToken, IdToken(UpstreamIdTokenError)) and checks its nonce (NonceMissing, NonceMismatch) and, under max_age, its auth_time (AuthTimeTooOld); a non-200 is Refused { status, error: TokenEndpointError }. The UpstreamGrant answers id_token(), access_token(), take_refresh_token() (UpstreamRefreshToken, restore and expose_for_store, at most MAX_REFRESH_TOKEN_BYTES), expires_in(), received_at() and the verified() id_token. The secret, the pending authorization, the refresh token and the grant’s tokens zeroize, and those four types have no Debug, Display, Serialize or Clone; no RelyingPartyError carries a token, code, secret, state or nonce. The session (#2816): refresh(&UpstreamRefreshToken, within) posts the refresh_token grant within one deadline, the lesser of within and UPSTREAM_TOKEN_TIMEOUT, covering discovery, and sorts every outcome by Amendment 2 into RefreshFailure::NotProcessed(NotProcessedReason) (discovery unavailable or unfinished at the deadline, the token endpoint not advertised or refused, the connection refused, failed or timed out at the 2 s connect bound, or a 408, 425 or 429: the token was never spent; a connect still pending when the deadline runs out is a request timeout, Ambiguous) or RefreshFailure::Ended(EndReason) (Refused { status, error } for any other 4xx, AcceptedUnreadable(AnswerDefect) for a 200 it cannot read or one missing the id_token a reissuing profile needs, Ambiguous otherwise); the reissued id_token is not validated, canopy-identity judging it at renewal. revoke(&UpstreamRefreshToken) posts RFC 7009’s revocation (token_type_hint=refresh_token), and end_session(id_token_hint, post_logout_redirect_uri) answers the end-session URL with post_logout_redirect_uri, client_id and the hint when given, or None when no endpoint is advertised; each runs within UPSTREAM_LOGOUT_TIMEOUT (2 s), discovery included. UpstreamGrant::refresh_due() is RefreshDue::At(receipt + lifetime − lead), the lead a quarter of the lifetime clamped to MIN_REFRESH_LEAD (30 s) and MAX_REFRESH_LEAD (300 s), always after receipt, or RefreshDue::ShortLived { lifetime } for a lifetime of 30 s or less.

  • identity_session (ADR-049 Amendment 6; #2712) — canopy-identity’s web-session primitives, for the federation grant in canopy-security and for canopy-web. SessionCredential is a web session’s credential: mint() draws 32 bytes from the thread CSPRNG; parse(presented) accepts exactly SESSION_CREDENTIAL_LEN (43) characters of unpadded base64url whose two unused low bits are zero, the one spelling of its bytes, and refuses anything else (padding, the standard alphabet’s + and /, 42 or 44 characters, non-canonical trailing bits, non-ASCII) as MalformedSessionCredential, which quotes nothing; hash() is the SessionCredentialHash (as_bytes()), the SHA-256 of the 32 bytes and all the session store holds; and expose_for_wire() is the one way to read it, a Zeroizing<String>. The bytes zeroize on drop, and the type has no Debug, Display, Serialize or Clone, which compile-time probes pin. The grant’s wire names: TOKEN_EXCHANGE_GRANT (RFC 8693’s, which a delegation request names too), ID_TOKEN_TYPE, WEB_SESSION_TOKEN_TYPE (urn:canopy:params:oauth:token-type:web-session), N_A_TOKEN_TYPE, the parameters UPSTREAM_ACCESS_TOKEN_PARAM, UPSTREAM_ID_TOKEN_PARAM and UPSTREAM_OUTCOME_PARAM, and NOT_PROCESSED, upstream_outcome's one value. CanopyRefusal is the closed set of refusals canopy-web acts on, code() its wire code: Projection(ProjectionRefusal) (the projection’s own four codes), auth_time_too_old, subject_suspended, upstream_refused, grace_exhausted, session_ended, session_stale (a session past its freshness, which the delegation mint refuses until the session is renewed, #2720), and user_code_invalid (a user code naming no device awaiting a decision, #2740) and approver_mismatch (an approval’s step-up signed in as someone other than the approving web session’s worker, ADR-049 Amendment 21, #2835); from_code(code) reads a code back, None for any other. A session’s terms are pure functions of injected times, every instant a whole-second NumericDate (NumericDate::from_seconds builds one). SessionLimits::new(web_session_max_seconds, grace_seconds) holds the two settings, refusing a maximum outside MIN_WEB_SESSION_MAX_SECONDS..=MAX_WEB_SESSION_MAX_SECONDS (1800 to 86400) or a grace outside 0..=MAX_SESSION_GRACE_SECONDS (3600) as SessionLimitsError (WebSessionMax, Grace), naming the setting and never its value; the defaults are DEFAULT_WEB_SESSION_MAX_SECONDS (43200) and DEFAULT_SESSION_GRACE_SECONDS (1800). with_native_session_max(seconds) sets the native session’s maximum, refusing one outside MIN_NATIVE_SESSION_MAX_SECONDS..=MAX_NATIVE_SESSION_MAX_SECONDS (1800 to 86400) as NativeSessionMax; it is DEFAULT_NATIVE_SESSION_MAX_SECONDS (28800) until set, and session_max_seconds(kind) reads a SessionKind's (Web, Native; as_str() the store’s kind). SessionTerms::open(kind, auth_time, validated_at, now, &limits) → Result<SessionTerms, OpenRefusal> gives a new session’s session_ends_at() (auth_time plus the kind’s maximum) and fresh_until(), judging now (a chrono::DateTime<Utc>, production passing Utc::now()) in whole seconds as the id_token validator does: an end under FRESHNESS_SECONDS (900) after now is OpenRefusal::AuthTimeTooOld, and one past the last NumericDate is EndOutOfRange. fresh_until(validated_at, ends_at) is the validation plus 900 s, never after the end; grace_until(last_success, ends_at, &limits) is the last successful validation plus 900 s plus the grace, never after the end, so a second grace before the next success ends where the first did. The token-exchange deadline, exported for canopy-web and checked against itself at compile time: TOKEN_EXCHANGE_DEADLINE (13 s from the request’s start) is TOKEN_EXCHANGE_FIRST_PHASE (2.5 s: the form, authentication and a renewal’s session read) plus TOKEN_EXCHANGE_UPSTREAM_BOUND (7.5 s: TOKEN_EXCHANGE_UPSTREAM_CALLS, 3, each bounded by UPSTREAM_REQUEST_TIMEOUT) plus TOKEN_EXCHANGE_AUDIT_RESERVE (3 s: the final transaction or a refusal’s log row). SECURITY_ADMIN_MAX_AGE_SECONDS (600, #2731) is the step-up bound: canopy-security’s security-admin routes refuse a token whose auth_time is older, and canopy-web asks the upstream for a sign-in this fresh; DEVICE_APPROVAL_MAX_AGE_SECONDS (600, #2740), asserted equal to it, bounds the sign-in that approves a device.

  • identity_device_client (ADR-049 §7; Amendment 23; #2850, #2851) — canopy-cli’s device client and its device store, behind canopy login, canopy logout and every command’s bearer. DeviceClient::new(&IdentitySettings, DeviceStore, IdentityHttpClient) calls the settings' internal device-authorization, token and revocation endpoints, its DPoP proofs (identity_dpop::mint_proof) naming the issuer identifier’s /token. begin_login() → PendingLogin (the user code, the page, and the fresh device key; no Debug, Display or Clone) and complete_login(pending, resource) → NativeToken follow RFC 8628: an absent interval is 5 s, each slow_down adds 5 s, a failed connection doubles the interval, a 429 waits the larger of its Retry-After and the interval, a 503 the interval, and the whole poll ends at the code’s expiry (the expiry and interval each capped at 1800 s); a pending login is bound to its issuer (IssuerMismatch), and a refused, denied or expired login (LoginFailed, Denied, Expired) leaves the stored session as it was. A redemption’s 200 carrying a well-formed refresh credential stores the new session and then, best effort, revokes a prior session of the same issuer, even when its access token fails a check (Malformed), since the device code is spent; one without (Malformed(RefreshCredential)) stores nothing and keeps the stored session. token(target) refreshes under the store’s lock with a fresh proof and resource, holds the 200 to the delegation client’s checks (Bearer, a lifetime within 300 s, the target as aud, canopy-cli as the current actor; AnswerDefect names the first failed), and stores the successor before answering, even when the token fails a check; session_stale is Stale and subject_suspended Suspended, both keeping the credential, any other invalid_grant is LoginRequired, the session removed, and any other refusal is Refused, the session kept. logout() revokes as a public client and removes the session on a 200. NoEdge, and LoginRequired for a missing session or another issuer’s, send nothing. Each call is bounded by DEVICE_CALL_TIMEOUT (10 s), a const assertion holding it above the edge’s body read, forwarding bound and a second of transport; an answer lost past every bound spends the credential, so the next refresh ends the session. NativeToken zeroizes and offers expose_for_call() and expires_at(). The store: DeviceStore::at(dir) over one owner-only directory per profile, device_store_dir(canopy_dir, &ProfileName) being <canopy_dir>/identity/<profile> (ProfileName::parse refuses an empty or overlong name, ., .., and any /, \, NUL or :). session.json holds the issuer, the DPoP device key as PKCS#8 PEM lines and the refresh credential: serialized into a buffer reserved up front and refused growth, read back into a zeroizing buffer of at most 16 KiB, and replaced by canopy_common::owner_only's durable rename. session.lock is never removed; its exclusive lock (std File::try_lock, retried for DEVICE_LOCK_BOUND, 15 s, then StoreError::Busy) serializes every mutation across processes. Each mutation runs as one spawned task that holds the lock from its acquisition until its work ends, so cancelling a caller detaches it rather than aborting a write. A session file not in this store’s format, or of another version, is StoreError::Malformed and is kept until a later write replaces it; a session the format cannot hold (an empty issuer, key line or credential, or a file past 16 KiB) is refused before any write as StoreError::Unstorable, so whatever is written reads back.

  • identity_dpop (RFC 9449; ADR-049 §5’s DPoP row, Amendment 9; #2741) — DPoP proofs, an exact-header validator, for the native grants in canopy-security and canopy-cli. verify_proof(proof, htm, htu, now) reads at most MAX_DPOP_PROOF_BYTES (2048) as three segments of canonical unpadded base64url, decoding all three, then refuses, first that holds: a header other than exactly typ (DPOP_PROOF_TYP, dpop+jwt), alg (ES256) and jwk, each once, the key a JSON object of exactly kty EC, crv P-256, x and y on the curve (so a private d, a kid, any other member or an array spelling refuses); claims other than exactly jti, htm, htu and an integer iat (ath, nonce and exp refuse); a signature that does not verify under the embedded key; an htm other than the request’s method; an htu other than the request’s target, compared once both are normalized by the URL parser (WHATWG: case, dot segments, the default port, an empty path as /, covering RFC 3986 §6.2.2 and §6.2.3) and by RFC 3986 §6.2.2.2’s percent-escape rule, and refused with a query, a fragment or user information; an iat more than DPOP_IAT_TOLERANCE_SECONDS (60) from now; and a jti empty, over 128 characters or holding a control character. Each refusal is a DpopRefusal whose reason() is a dpop_* code and which quotes nothing. The answer, VerifiedDpop, gives the key’s RFC 7638 thumbprint() (the binding a native session holds), the jti() the caller spends once per thumbprint, and retain_until() (iat plus DPOP_JTI_RETENTION_SECONDS, 120). single_proof(values) takes a request’s DPOP_HEADER values, refusing none, several or a non-ASCII value; mint_proof(signer, htm, htu, iat, jti, deadline) makes a proof with that header.

  • identity_native (ADR-049 §7; Amendment 9; #2740) — canopy-identity’s native-session primitives, for the device flow in canopy-security and canopy-cli. DeviceCode (RFC 8628’s device code) and RefreshCredential (the native session’s rotating refresh credential) are opaque bearers spelled exactly as SessionCredential is: mint() draws 32 CSPRNG bytes, parse(presented) accepts only the canonical 43-character unpadded base64url spelling (MalformedDeviceCode, MalformedRefreshCredential, quoting nothing), hash() gives the SHA-256 the store holds (DeviceCodeHash, RefreshCredentialHash), and expose_for_wire() is the one way to read one; each zeroizes on drop and has no Debug, Display, Serialize or Clone. UserCode is the code a worker types: mint() draws USER_CODE_SYMBOLS (8) symbols uniformly from USER_CODE_ALPHABET (the 20 consonants BCDFGHJKLMNPQRSTVWXZ, about 34.6 bits, RFC 8628 §6.1); expose_for_display() shows XXXX-XXXX; parse(typed) reads it case-insensitively, ignoring - and spaces, and refuses anything else (another character, other than eight symbols, more than 32 bytes) as MalformedUserCode; hash() is the SHA-256 of the eight canonical symbols (UserCodeHash). The wire names: DEVICE_CODE_GRANT, REFRESH_TOKEN_GRANT, NATIVE_REVALIDATION_TOKEN_TYPE (urn:canopy:params:oauth:token-type:native-revalidation, the credential canopy-web alone presents), and the parameters DEVICE_CODE_PARAM, USER_CODE_PARAM, WEB_SESSION_PARAM (the approving worker’s web-session credential, at code entry and, since Amendment 21, at approval) and REFRESH_TOKEN_PARAM; the flow’s times: DEVICE_CODE_LIFETIME_SECONDS (600) and DEVICE_POLL_INTERVAL_SECONDS (5); and NATIVE_BUDGET, a redemption’s or refresh’s budget, equal to DELEGATION_BUDGET.

  • identity_native_session (ADR-049 §7; Amendment 21; #2837, #2838) — canopy-web’s native sessions, over canopy-web’s PgNativeStore. NativeSessions::new(UpstreamRelyingParty, FederationClient, store) owns a session engine of kind native over its own store and exposes no engine, so a native session never reaches canopy-web’s sender; store() is where canopy-web inserts an approved record. describe(&approver, &UserCode) and deny(…​) are code entry with the approving worker’s served web session; step_up(redirect_uri) is the authorization a device approval needs (step_up_options(), max_age 300 s), leaving the worker’s web session untouched, its grant the native session’s alone. complete_approval(pending, (returned_state, code, redirect_uri), &UserCode, &approver) → Result<WebSessionRecord, ApprovalError> redeems the step-up, refuses a grant without a refresh token before approving anything (NoRefreshToken, the user code still usable), has canopy-identity approve the device for the approver’s web session (the issuer holding the approval to its approver), revokes the step-up’s refresh token on any failure, and answers the native record, bound, scheduled NATIVE_FRESHNESS_LEAD (300 s) before its freshness ends and holding no id_token; a lost answer leaves the outcome unknown, the orphaned native session minting only until its fresh_until. ApprovalError is RelyingParty, NoRefreshToken, Federation (AuthTimeTooOld, UserCodeInvalid, ApproverMismatch) or OtherPerson, the backstop for an answer naming another subject, whose native session is revoked before the refusal. revoke(key) → Result<NativeEnded, StoreFault> is a worker’s revocation of a device: the record ended SignedOut, canopy-identity’s session revoked within 2 s, then, for a record bound to the configured upstream, its refresh token, never through the end-session endpoint; NativeEnded { ended, identity_revoked, upstream_revoked }. Its store is a DueSessions, and sweep(budget) → Swept is one pass of the sweep canopy-web runs every SWEEP_INTERVAL (30 s): within one absolute deadline, which bounds the due listing too, it takes at most SWEEP_BATCH (256) due rows, earliest first, and runs each row’s step (read, decide, act) in a spawned task holding one of SWEEP_CONCURRENCY (16) permits that the handle’s clones share, so one replica’s overlapping passes maintain at most 16 rows at once. A step leads a due row, ends a row as a request would (Expired, UpstreamChanged, a lapsed claim’s RefreshLost), ends a row it cannot read RefreshLost (revoking its sessions when the end still answers a record), and skips another replica’s live claim or a row just renewed; the claim keeps replicas from leading one row twice. No step starts once the deadline has passed; reaching it, or dropping the pass, detaches running steps and never aborts a leader. Swept { led, ended, skipped, faults, unfinished } reports the pass, unfinished counting both steps left running and rows no slot freed for, which wait for the next pass; a full batch or an unfinished row logs a warning. A const assertion holds the design load inside the native lead: SWEEP_INTERVAL + (SWEEP_BATCH / SWEEP_CONCURRENCY) × DESIGN_RENEWAL (5 s) + CLAIM_LEASE < NATIVE_FRESHNESS_LEAD (30 + 80 + 60 < 300 s).

  • identity_edge (ADR-049 §2; Amendment 22; #2844) — canopy-web’s edge forwarder, whose router canopy-web merges outside the session and CSRF layers and under its per-IP limit. EdgeForwarder::new(&IdentitySettings, IdentityHttpClient, TrustedProxies) is a cheap handle; router() serves canopy-identity’s public routes alone, each sent to its twin under the internal URL: POST TOKEN_PATH, REVOKE_PATH and DEVICE_AUTHORIZATION_PATH, and GET JWKS_PATH and METADATA_PATH, a HEAD sent upstream as a GET so it advertises the representation’s length. Code entry, the admin routes, any other path or method and any query are never forwarded, and no form is parsed: the issuer judges every grant. A request keeps only its body (at most MAX_FORM_BYTES, read within EDGE_BODY_READ_TIMEOUT, 2 s, into a buffer wiped once sent), its Content-Type, every DPoP value in order, and an X-Forwarded-For overwritten with the one client the shared client-IP rule resolves under canopy-web’s own trusted proxies; a body past the cap answers 400 invalid_request, a slow one 503, and a request with no ConnectInfo 503, never forwarded under a made-up address. An answer keeps its status, its body (at most 64 KiB) and only Content-Type, Cache-Control, Pragma, Retry-After and Age; a call with no complete answer within EDGE_FORWARD_TIMEOUT (6.5 s, held above the native and delegation budgets, 5.5 s, and the client-credentials budget, 5 s), a transport failure, an answer over the cap, an encoded answer or any 3xx is answered 503 temporarily_unavailable with no-store, so no Location reaches the internet.

  • identity_delegation (ADR-049 Amendment 7; #2720) — the delegation grant’s rules the issuer’s mint, the receivers and the senders share. The wire names: ACCESS_TOKEN_TOKEN_TYPE (urn:ietf:params:oauth:token-type:access_token, a delegation request’s requested_token_type, an onward request’s subject_token_type and the answer’s issued_token_type), and the parameters REQUESTED_ROLES_PARAM and REQUESTED_PROGRAMS_PARAM. Narrowing is what a request asks a token’s roles and programs to narrow to, each a canonical set or None for its base (new, roles(), programs()): parse(roles, programs) reads each parameter as values separated by one ASCII space, in any order, held sorted, and refuses an empty token, a malformed role name, an unknown program or a value named twice as NarrowingError(NarrowedSet), naming the parameter and never a value; roles_param() and programs_param() render the canonical values parse reads back; apply(base_roles, base_programs) grants a requested set only within its base and an absent one the base, refusing an empty base (None, the subject token’s set and the session’s sharing nothing) as ScopeRefusal::Exhausted and a wider request as ScopeRefusal::Widened, roles before programs. delegation_expiry(iat, subject_exp, session_end) is a token’s exp in NumericDate seconds, the least of iat + 300 s, the onward subject’s exp and the session’s end, refused under DELEGATION_MIN_LIFETIME (5 s) as ExpiryRefusal::SessionEnding (judged first) or SubjectExpiring; an end after iat whose distance overflows i64 lasts. The mint’s budget, checked at compile time: DELEGATION_BUDGET (5.5 s, exported for senders) is TOKEN_EXCHANGE_FIRST_PHASE (2.5 s) plus DELEGATION_AUDIT_RESERVE (3 s), and the 5 s floor leaves a second beyond a whole-second iat and the reserve.

  • identity_client (ADR-049 §10; Amendment 3; #2556) — the sender’s side of canopy-identity’s client-credentials grant, which every sender’s system tokens come through. ClientAssertionMinter::new(signer: Arc<dyn KeySigner>, client, issuer: Url) and mint() sign a private_key_jwt assertion: iss = sub = the client, aud the issuer identifier, exp = iat + 60 s, a fresh v7 jti, typ: client-authentication+jwt. SystemTokenSource::new(minter, token_endpoint: Url, IdentityHttpClient) and token(resource, scope) → Result<Arc<str>, SystemTokenError> trade a fresh assertion for a token per (resource, scope) and cache it for the shorter of 300 s (MAX_CACHE, the receivers' JWKS refresh) and expires_in − 60 s (EXPIRY_MARGIN), both from when the request was sent; callers that miss together share one acquisition, a failure included (SharedFailure); invalidate(resource, scope) drops an entry so the next call reacquires. SystemTokenError is Mint, Transport, Body (the 64 KiB answer cap), Refused { status, error: TokenEndpointError } (the RFC 6749 / RFC 8707 code, typed; an unlisted code is Unrecognized and not kept), Malformed or SharedFailure; none carries a token, an assertion or a body. The delegation sender, identity_client::delegation (Amendment 7; #2727), sends through it: DelegationTokenSource::new(minter, token_endpoint, IdentityHttpClient) asks canopy-identity’s token endpoint (RFC 8693’s token-exchange grant, TOKEN_EXCHANGE_GRANT) for a delegation token for one CanopyService, with a fresh assertion each time, by from_session(cache, &FederatedSession, target, &Narrowing) (canopy-web, from a web session, its token held to the session’s sub, sid and end: ADR-049 Amendment 19) or delegate(cache, &VerifiedDelegation, target, &Narrowing) (a service, onward from the token it received), each returning Result<&DelegationToken, DelegationError>. Tokens are reused within one request: the caller makes a DelegationCache per request with request_cache(), and only its source serves it (another source’s is ForeignCache, with no request), keyed by the SHA-256 of the issuer, the client, the subject as presented, the target and each narrowed set or its absence, length-prefixed, and an entry is served while its exp is more than 5 s ahead of the local clock. A 200 must carry the access-token type, Bearer, an expires_in of 1 to 300 s, and a token whose payload, read unverified, names the target as aud, this client as client_id and a lifetime of 1 to 300 s, and onward the subject token’s sub and sid and an exp no later than its own, a comparison of two issuer-clock times (AnswerDefect names the first broken). DelegationError is ForeignCache, Mint, Transport, Body, Refused { status, error, refusal: Option<CanopyRefusal> } or Malformed(AnswerDefect). DelegationToken zeroizes and has no Debug, Display, Serialize or Clone; expose_for_call() reads it, expires_at() its exp. DelegationCache::forget(target) drops one target’s tokens, after its receiver refused one (Amendment 16; #2808). The federation client, identity_client::federation (ADR-049 Amendment 6; Amendment 11; #2767), is canopy-web’s side of the federation grant, behind its sign-in: FederationClient::new(minter, &IdentitySettings, IdentityHttpClient), its token, revocation and code-entry endpoints under the settings' internal URL (Amendment 21; #2836), then open(id_token, upstream_access_token: Option<&str>), renew(&SessionCredential, SessionKind, RenewalEvidence) (IdToken, UpstreamAccessToken or NotProcessed, which asks for grace; the kind’s token type presented both ways, a web session’s or a native session’s revalidation credential) and revoke(&SessionCredential) (RFC 7009, a web or native session’s credential), each with a fresh assertion and each request bound by FEDERATION_REQUEST_TIMEOUT (the grant’s 13 s deadline plus 2 s, overriding the client’s own bound). For the device flow (Amendment 9), describe_device(&web, &UserCode) → DeviceRequest { client: NativeClient, started_at, expires_at } and deny_device(&web, &UserCode) post code entry with the worker’s web-session credential, each within DEVICE_VERIFICATION_TIMEOUT (6 s), and approve(id_token, upstream_access_token, &UserCode, &approver) exchanges a step-up id_token, the user code and the approving worker’s web-session credential for a native session; each answer must be issued as the kind asked for (SessionDefect::IssuedTokenType), and a describe naming no compiled native client is SessionDefect::Device. The user code is sent as the worker reads it, XXXX-XXXX. An open or renewal returns a FederatedSession: the credential, sid, sub, auth_time, session_ends_at, fresh_until, the role and program sets and the username (an UpstreamUsername), after checking the answer’s types, the credential (a renewal must echo the one it presented), the times' order, canonical sets and the username (SessionDefect names the first broken). FederationError is classified from the answer’s status and body, since the endpoint answers every OAuth error but temporarily_unavailable with 400: Refused(CanopyRefusal) when the body names one, ClientRejected for invalid_client, InvalidRequest(TokenEndpointError) otherwise, Limited { retry_after } (429, the wait its Retry-After names in seconds, as the device flow’s attempts budget names one), Unavailable (503) or Status, beside Mint, Transport, Body and Malformed; none carries a token, an assertion, a credential or a body.

canopy-api

Shared Axum server infrastructure.

  • AppState { db: DbPool, receiver: Option<IdentityReceiver> } — standard service state: ApiServer mounts /v1 only behind a receiver.

  • ApiServer::router(state, routes, public_routes, options, openapi) — builds the Axum router with CORS, rate limiting, body limit, idempotency middleware, /livez + /readyz + /version, and OpenAPI/Swagger UI; ServerOptions carries service_name (the service label of the idempotency lease-renewal pool’s gauges, #2541, and /version's service), config (the boot Arc<ConfigSnapshot>, BootstrapResult.config), cors_origins, body_limit, rate_limit_rpm. ServerOptions::new(service_name, config) fills the rest with the baseline’s defaults; there is no Default. /version's body is canopy_config::VersionInfo, { service, build, config: ConfigStamp, verified } (re-exported here), built once per router (VersionInfo::of(service, &snapshot); build is CANOPY_BUILD_DESCRIBE at build time, else the crate version); version_route(service, &snapshot) is the route, which canopy-web mounts on its own router. readyz_check(State, ReadinessArms) takes its opt-in arms through one extractor, ReadinessArms { mq, outbox, worker, subscriber, redis, identity_key, config }, each the request extension its router layers or None; the config arm (Extension<Arc<ConfigSnapshot>>, layered by ApiServer::router and canopy-web) gates readiness while any layer is stale (Deployment Guide › Health). public_routes (a Router carrying its own state) merge at the root: outside the bearer middleware, the idempotency layer and the per-IP limiter, inside every outer layer. Every service passes Router::new() except canopy-security, whose public route is the canopy-identity JWKS, GET /identity/jwks (#2500), and a noop-adapters canopy-verification, whose public routes are its /internal/v1 API-key adapter routes (#2510).

  • outer_stack(router, &options) — the layers ApiServer::router puts around every response (body limit, access log, request span, OTel propagation, compression, CORS, the security and API-version headers) for a router built without it; refuses a wildcard CORS origin outside development with CorsWildcardRefused (#2755: the identity capacity harness’s replicas).

  • API_PREFIX (/v1) is the mount ApiServer::router nests the protected routes under. A service registers each route as v1_route!(paths::X): the macro strips the prefix from the canopy-contracts-* constant in a const item through the const fn v1_relative, so a constant off the /v1/…​ convention fails the build (E0080) rather than the boot.

  • load_config::<C>(prefix, RESERVED_KEYS, MIRRORED_KEYS) → (ServiceSettings, C) — the single per-prefix load (ADR-012): one collected map partitioned into the shared baseline and the service’s own config struct, both #[serde(deny_unknown_fields)], so a misspelled CANOPY_<SVC>__* key fails boot by name. The two consts live in the service’s src/config.rs.

  • bootstrap_with(prefix, settings, service_name, migrator) → (ServiceSettings, BootstrapResult) — standard startup: load the configuration snapshot (ServiceSettings::config_snapshot, a load error refusing the boot naming the layer; BootstrapResult.config), install telemetry with the pack’s ADR-041 logging policy read through it (telemetry::init_for_pack(level, service, &snapshot)), resolve secrets through the audited provider, build canopy-identity’s settings, the service’s receiver over HTTP (none for canopy-security, canopy-web and canopy-exchange) and its sender from its client key (BootstrapResult.identity, .receiver, .sender; a missing key refuses the boot before migrations), validate the database name, apply the supplied sqlx::migrate::Migrator over a dedicated migration connection (callers pass sqlx::migrate!("./migrations") so the path resolves at their crate), then connect the app pool before the OutboxDrainer spawns, connect RabbitMQ, create publisher and subscriber. bootstrap_requiring(…, requirement) → (ServiceSettings, BootstrapResult, R) is the same sequence with a caller-supplied boot requirement run right after telemetry and before secret resolution and migrations — the sealing services pass their CANOPY_ENCRYPTION_KEY read, so a KEK-premised migration never runs keyless and the read is logged through the redacting subscriber.

  • run_to_completion(what, run) (#3202, #3242) — awaits run on its own task, so a handler's multi-step work outlives a caller that disconnects; a panic in the task answers 500 with what as its context. When a handler uses it: Framework patterns.

  • determination_redaction::publish_determination_redacted(tx, publisher, source_service, &DeterminationRedacted { .. }) — stages the ADR-036 determination.redacted audit event in the redact endpoint’s transaction for all five program services: the id, the steward’s author, the reason and timestamp, no plaintext, stamped with the publishing program (#1519).

  • admin::AdminRoutes — the per-service /v1/admin/* family; .with_replay(pool, manager) enables POST /v1/admin/events/replay behind the mounting service’s receiver, admitted by ADMIN_HUMAN (Admission::user_roles(&["admin"]): a user holding admin through any actor, no system arm).

  • extract::required_extension(parts, name) — clones one boot-registered request extension out of the request parts for a service’s FromRequestParts dependency bundle; absence is a wiring fault answered as a 500 (ApiError::Internal, logged under name), the status axum’s own Extension rejection gives.

  • pagination::{DEFAULT_LIMIT, MAX_LIMIT, clamp_limit} — the single home for the keyset page-size bounds (ADR-001 Amendment 1 §B2): interactive keyset lists clamp limit through clamp_limit; the canopy-reporting universe drains request pages at MAX_LIMIT. A per-endpoint deviation carries a justification comment at the deviating site.

  • retry — a bounded exponential-backoff retry layer for outbound reqwest calls that coordinates with the server-side single-flight idempotency middleware: a retried request resends the same Idempotency-Key and body, so a completed request replays its stored response, one still in flight elsewhere returns a retryable 503 with Retry-After, and a reused key with a changed body returns 409. RetryPolicy::default_http() plus with_* setters (with_overall_timeout is a hard tokio::time::timeout wrap); RetryRequest::{get, head, delete, post_with_idempotency_key, idempotent_put, post_read} — try_new refuses a keyless POST, and the only keyless POST descriptor is the caller-asserted post_read, for an AIP-231 :batchGet read, which canopy-web builds only behind InternalClient::post_read's :batchGet shape guard (#2680); retry_request(&policy, &request, make_req) builds a fresh RequestBuilder per attempt and logs tracing::info!(target: "retry", …) before each sleep. The eligibility orchestrator deliberately keeps single-attempt dispatch (a wide synchronous fan-out should fail fast, not amplify load) while still sending Idempotency-Key: det_id. It retries a 5xx other than 504, a 408, a 429 and connect or timeout errors. A 504 is returned to the caller: a canopy service answers it for a statement cancelled at its budget (ADR-053), and repeating a slow statement only holds a connection again. A 503 that states Retry-After in whole seconds sets the wait before the next attempt: the hint, capped at the policy's longest backoff, jittered upward only, and never past the overall budget.

canopy-config

A deployment’s configuration as ordered layers (ADR-051; the operator’s view is Configuration Reference › Configuration source, the author’s Rulesets › Layers). Every service, canopy-seed and the xtask policy checks read policy files through it, never by joining a root and a slug.

  • Sources (FromStr, Display) — the CANOPY_CONFIG_SOURCE list, lowest precedence first, of Source { name: LayerName, location: Location }. Location is Path(dir) or Git(GitSource { url, reference: GitRef, verify: VerifyMode, pin: Option<CommitSha> }); GitRef is Branch or Tag (full_name() is its refs/heads/… or refs/tags/…); VerifyMode is Head, Tag or TagAndHead (default_for(&reference)); CommitSha is 40 lowercase hex, the &sha= pin canopy-config-fetch resolve writes. Parsing refuses an empty list, a bad or repeated LayerName ([a-z0-9][a-z0-9_-]{0,63}), a git source with no ref, a branch that asks to verify a tag, a malformed pin, a repeated fragment key, and a URL with userinfo. A list prints back in the grammar it parses from, verify= only when it is not the ref's default, so a pinned list round-trips.

  • Manifest / manifest::read(root, layer) — a layer’s canopy-config.toml (MANIFEST_FILE): schema (only SCHEMA = 1 reads), layer (LayerKind::{Base, Jurisdiction, Deployment}), and jurisdiction, required on a jurisdiction layer and refused on any other; unknown keys refused.

  • ConfigSnapshot::load(&sources, &LoadOptions { policy_root, allow_unverified }) — the process’s configuration: a path: source read where it stands (stamped path, loaded only when every source is path: and allow_unverified), a git source from <policy_root>/<name>/current resolved once to its <sha>/ directory, its status.json (SyncStatus, STATUS_FILE) read beside it. resolve(rel) returns rel from the highest layer holding it (resolve_layer also returns the Layer); list(rel_dir) the union of the layers' entries, each resolved, in name order; layers(), jurisdiction() (the jurisdiction layers' one slug), verified(), stale_layers() (layers whose last sync refused) and stamp(). from_path_layers(&[(name, dir)]) builds an unverified snapshot for tests, behind the test-helpers feature, so no production build can reach it (the canopy-config feature-build lane checks the crate without it).

  • ConfigStamp(Vec<LayerRef { name, sha: ConfigSha }>) — the provenance a process runs on: a JSON array of { name, sha }, Display as name@sha,name@sha. ConfigSha is 40 lowercase hex or the literal path.

  • VersionInfo::of(service, &snapshot) — GET /version's body, { service, build, config, verified }, which every server mounts: the canopy-api services through canopy_api::version_route, canopy-web on its own router, the portal beside /healthz. version::BUILD is CANOPY_BUILD_DESCRIBE at build time, else the crate version.

  • ConfigError — every refusal, each message naming what to fix (the layer, the variable); Clone + Eq, so the refusal tests compare values.

  • Constants: SOURCE_ENV (CANOPY_CONFIG_SOURCE), POLICY_ROOT_ENV (CANOPY_POLICY_ROOT), DEFAULT_POLICY_ROOT (/app/policy), ALLOW_UNVERIFIED_ENV (CANOPY_CONFIG_ALLOW_UNVERIFIED), and CURRENT (current), the published link the fetcher flips and a snapshot resolves.

Tests build their snapshots through canopy_test_lib::config (canopy-test-lib).

canopy-db

PostgreSQL connection pool and migration helpers, and the database code more than one service shares.

  • DbPool — wraps sqlx::PgPool: DbPool::connect_with(url, opts); db.inner() returns &PgPool; db.register_metrics(service, pool, max) registers the canopy_db_pool_{size,idle,max} gauges labelled service and pool, a closed PoolName (main, or a service’s own extra pool: session, bookkeeping, run_worker, archive_worker, issuer, identity_admin, verify_audit, verify_tanf, verify_medicaid; #2224, #2537, #2730); canopy_db::register_pool_metrics(&pg_pool, service, pool) registers the same gauges for a raw PgPool a service builds beside its main one, reading the maximum from the pool’s own options. DbPoolOpts — max_connections, idle_timeout, application_name, session_settings, and acquire_test: AcquireTest::Always (the default; sqlx’s test_before_acquire) or AcquireTest::IdleFor(d), which pings a connection before lending it only once it has idled d (needs_ping), through before_acquire, saving a round trip a lend at the cost of lending a connection the server dropped within d (ADR-049 Amendment 13; the issuer pool uses 1 s). opts.to_pool_options() returns the PgPoolOptions connect_with uses, release check included, for a caller holding connect options rather than a URL. Outside development the URL must carry sslmode=verify-ca or verify-full; require is refused, since it accepts any server certificate (#3646).

  • pool_options() — the PgPoolOptions every production pool starts from: DbPool::connect_with and each raw pool a service builds beside its main one (#2538). Its after_release check probes each returning connection with begin_with("SELECT 1"), which reads the server’s own transaction status, and rolls back any transaction block the connection is in, open or failed, before the pool keeps it. So no connection is pooled or handed out inside a transaction, whatever left it there: a raw BEGIN never ended, which sqlx pools as it is, or a request future dropped with its BEGIN in flight, which sqlx left open until 0.9.1. Each rollback logs a WARN (a pooled connection came back inside a transaction block, field block = open or failed). The check costs one round trip per release, off the request path. A pool built from PgPoolOptions::new() goes without it, and so does one whose builder calls after_release again, which replaces the hook. The cargo xtask db-pools gate (a validate stage) refuses PgPoolOptions::new / ::default, PoolOptions::new / ::default, PgPool::connect… / Pool::connect… and any after_release call in production code outside canopy-db. It matches names, not types, so a type alias or a re-export under another name gets past it. canopy-test-lib and test code are exempt, and there is no allowlist (a pool that must differ gets a builder in canopy-db). canopy-test-lib’s ephemeral-schema pools start from pool_options() too, so service infra tests run with the same check. Two kinds of test pool stay raw: canopy-test-lib’s admin pools, which each hold one connection for autocommit DDL (schema create, drop and sweep), are closed by their caller, and run no code under test; and pools a test builds for itself, such as canopy-web’s second-replica fixture (second_pool), whose suites never drop a BEGIN in flight. The decision record (the alternatives weighed, the probe, the cost) is the canopy_db::pool_release module doc.

  • StatementBudget — PostgreSQL's statement_timeout as a type (ADR-053): whole milliseconds, never zero, with the class ceilings REQUEST (30 s), IDENTITY_ISSUER (5 s) and BATCH (300 s). DbPoolOpts::statement_budget sends it as a session setting on every connection of a pool; set_statement_budget(conn, budget) sets it for one transaction (SET LOCAL). Services set a statement limit through these, never a hand-written SET string.

  • commit(tx) — the one way production code commits (ADR-053). It returns CommitError::Refused when the server answered the commit with an error and CommitError::OutcomeUnknown when no answer was read, which ApiError answers as the coded 500 db_commit_outcome_unknown. Converted to a sqlx::Error, the unknown case carries canopy-common's CommitOutcomeUnknown marker, so a store function that returns sqlx::Error does not lose it.

  • validate_database_name(url, service_name) — the ADR-001 guard: a DATABASE_URL whose database is not the service’s own is fatal outside CANOPY_ENV=development.

  • advisory::run_with_advisory_lock(pool, lock_name, f) — tick-level leader election on pg_try_advisory_xact_lock; returns SchedulerOutcome::{Ran, Skipped}. Dedups CONCURRENT invocations only — it backs the manual scheduler triggers; background daily loops use the window fence.

  • advisory::advisory_lock_id(schema, name) / advisory::advisory_lock_id_for(conn, name) — the one derivation of an advisory-lock key from a lock name (#1913): SHA-256(name) in public, SHA-256("<schema>/<name>") in any other schema, so an ephemeral test schema never contends with a live service. advisory_lock_id_for reads current_schema() on the connection that takes the lock.

  • fti_audit — FTI audit logging per IRS Publication 1075: the fti_audit_log entry and purpose-code types, the hash-chained locked insert, the retention sweeps, and scrub_fti_fields, which removes FTI keys from an outbound payload.

  • chain_append / chain_verify — the retirement-bound v2 chain callers (#1207): the append transport and its refusal classifier, and the verifier engine with its status types (chain_verify::status).

  • role_reach_ctes!() — SQL CTEs for the roles a session reaches, scanned from pg_auth_members and pg_database under the statement’s snapshot: member_of (pg_has_role(…, 'MEMBER')'s reach, SET-only grants and the database owner’s pg_database_owner included) and privs (the inheriting reach every ACL check uses), beside the current database’s ACL. PostgreSQL’s role functions read its catalog caches, which no snapshot binds, so a boot guard that pairs them with a catalog scan can combine two moments; canopy-identity’s probes and canopy-reporting’s broad-role guard derive their role facts from these scans instead (#2562, #2572). The statement opens WITH RECURSIVE and defines me (oid, rolsuper) first; the module doc is canopy_db::role_reach.

  • window_fence::run_daily_fenced(pool, job_name, f) — wall-clock window fence for daily schedulers: an INSERT .. ON CONFLICT DO NOTHING election on the service-local scheduler_runs table keyed (job_name, UTC-day); one winner per window across replicas and restarts, the advisory lock composed inside. A failed tick releases its window; a crash mid-tick consumes it. window_fence::run_window_fenced(pool, job_name, window_key, f) takes the caller’s day (a legal date) as the window key, and run_window_fenced_until_complete(…, incomplete) also releases the window when incomplete judges the tick’s value unfinished, reporting it as Ran (#2433). window_fence::consume_window(pool, job_name) lets a manual trigger that did the window’s work stamp the day consumed. Canonical DDL: crates/canopy-db/scheduler-migrations/, copied per service and parity-gated by cargo xtask outbox-migrations.

  • ensure_idempotency_schema(pool) — the fleet idempotency_keys DDL, advisory-lock-serialised and idempotent, owned by the migration path (canopy_api::bootstrap's in-process run and canopy-manage migrate apply) — never by the runtime, so a least-privilege runtime role needs no CREATE. Deliberately raw DDL, not sqlx::migrate!, so a second migrator never fights the service’s own _sqlx_migrations.

  • redaction::PgRedactionKeyStore (ADR-036) — the shared redaction_keys store of the five program services and canopy-persons: mint_unpersisted(kek, kind, id, created_at) then persist_minted_with(executor, minted) (the DEK row rides the caller’s transaction, #2367), shred_with(executor, kind, id, shredded_at) / shred_with_dek_id(executor, dek_id, shredded_at), and the canopy_crypto_shred::RedactionKeyStore impl. Every write is stamped with the caller’s instant, never SQL now() or a column default (#2475), so a DEK’s stamps agree with the request’s.

  • lease::spawn_heartbeat(period, renew) (ADR-038) — the shared holder-side row-lease renewal loop: calls the caller’s lease-fenced extend UPDATE every period, stops and flags on a fence miss, fails toward losing the lease on transient errors; returns an abort-on-drop HeartbeatGuard with lease_lost(). lease::new_claim_id() mints the v7 holder id.

canopy-mq

RabbitMQ event publishing and subscribing over the canopy.events topic exchange (EVENTS_EXCHANGE); ConnectionManager::new(url) → Result<Self, lapin::Error> owns the connection (connection.rs).

  • EventEnvelope — id (UUID v7), source_service, event_type (routing key), payload (JSON), timestamp, optional W3C trace_context, schema_version, optional programs.

  • Publisher — validates the payload before staging: any key in the RESTRICTED_FIELDS list (crates/canopy-mq/src/publisher.rs — SSN, FTI, IEVS and HIPAA field names, ADR-004) is refused. publish_tx(tx, envelope) stages the row in the caller’s transaction (ADR-018); the background OutboxDrainer flushes it. Event hold (ADR-039): publish_tx_held(tx, envelope, EventHold { operation_id, generation }) stages an event the drainer skips; release_held / drop_held clear or delete it — both idempotent, used by the finalize saga so downstream never sees a partial cross-service operation. stage_outbox_tx_held(tx, envelope, hold) stages a held row without a Publisher. hold_for(determination_id) is a determination’s hold, the id at generation 0 (DETERMINATION_HOLD_GENERATION): a program service’s verdict consumer releases or drops it when canopy-eligibility records or disowns the determination (ADR-002 Amendment 7).

  • Subscriber — subscribes to routing-key patterns (determination.completed.*) with an async fn(EventEnvelope) → Result<(), anyhow::Error> callback. A handler that cannot INTERPRET a delivery returns Err(ParkEvent::…): the delivery is durably parked in event_inbox (broker acked, handler tx rolled back) and the per-subscriber unpark scanner (run_unpark_pass on demand) re-offers it until a capable binary processes it; the classify step is row-locked, so replicas never double-run one event. Queues are durable by default; a mismatched pre-existing queue of the same name is self-healed on attach only if empty. Full protocol: Event-Delivery Protocol.

  • Subscriber::subscribe_raw_batched (#2469) — for a consumer whose handler pays a fixed cost per transaction (canopy-security’s audit chain lock). BatchedHandlers { handler, batch_handler, max_batch }: the consume task takes the deliveries the broker has already pushed (never waiting, capped at max_batch; the consumer’s prefetch is raised to at least 2 × max_batch, so the next batch buffers while one commits — a delivery stays unacked until its batch commits); a lone delivery runs handler exactly as subscribe_raw would, while two or more share ONE transaction — inbox dedupe for all of them (a same-batch repeat of an id runs once), batch_handler over the fresh ones in delivery order, inbox::mark_processed_batch, one commit, then every ack. Any failure rolls the batch back and replays each delivery alone through handler, so retries, the DLQ and parking are unchanged. process_batch is the on-demand surface (the run_unpark_pass precedent): it returns each delivery’s DeliveryOutcome, so a service drives its real handlers through the batch and fallback path without a broker.

  • list_held(exec, HeldQuery { cutoff, after, operation, limit }) (held.rs, #3065) — the held set hold by hold: one HeldOperation { hold, held_since, rows } per (hold_operation_id, hold_generation) whose oldest unpublished row was enqueued before cutoff, ordered by (held_since, operation_id) and keyset-paged after after, on the ADR-039 partial index event_outbox_held_idx; operation narrows it to one hold. It reads and never releases or drops. held_cutoff(now, tuning.held_age_warn()) is the cutoff that lists exactly what the held-row watch warns about; the program services' GET /v1/held-determinations reads it.

  • OutboxDrainer::spawn(pool, manager, &tuning) — lease-based three-phase drainer: claim with a FOR UPDATE SKIP LOCKED CTE (skipping held rows), publish outside any DB tx with publisher confirms, mark in short transactions guarded by claimed_by; crashed-drainer recovery via the lease TTL.

  • InboxDrainer::spawn(pool, retention, listen) — the inbox janitor (#2470): canopy-api’s bootstrap spawns one per service, stopped by the shutdown signal it registers through listen once its first hour ends, and it deletes processed event_inbox rows past the service’s inbox_retention_days in batches, never an unprocessed or parked row (Event-Delivery Protocol › Inbox retention).

  • Outbox and inbox schema are single-sourced (ADR-039): the canonical migrations live in crates/canopy-mq/outbox-migrations/, are generated into every service by cargo xtask outbox-migrations --write and parity-gated by --check in the battery.

  • Tunables are process-wide CANOPY_MQ_* variables (DRAINER_TICK_MS, DRAINER_BATCH_SIZE, DRAINER_LEASE_TTL_SECS, DRAINER_PIPELINE_DEPTH, DRAINER_CONFIRM_TIMEOUT_SECS, DRAINER_MAX_ATTEMPTS, OUTBOX_RETENTION_DAYS, OUTBOX_PENDING_ALERT_THRESHOLD, OUTBOX_OLDEST_AGE_ALERT_SECS, HELD_AGE_WARN_SECS, UNPARK_INTERVAL_SECS, PREFETCH_COUNT, QUEUE_PREFIX, REPLICA_ID). The numeric ones are read once at boot into MqTuning (crates/canopy-mq/src/tuning.rs, #2578), whose Default holds the defaults. canopy-api’s bootstrap builds it and hands it to OutboxDrainer::spawn and Subscriber::from_manager, so a malformed value refuses the boot, and returns it as BootstrapResult::mq_tuning for a service to layer as an Extension. Configuration Reference › process-wide is their documented home.

canopy-chain

The chain-v2 byte-level protocol substrate (ADR-014 Amendments 5–6): pure by construction — no DB, no signing, no clock. Retirement-bound: ADR-041 supersedes the chain approach and the crate retires with the hash chain behind #1304; new code should not build on it. Still consumed until then by the SQL append functions' Rust callers and the verifiers: canonical_bytes (RFC 8785 behind an I-JSON validation layer that refuses integers beyond ±(2^53−1)), the validated newtypes (ShardCount, EventSeq, ChainInstanceId, EventHash), ChainEnvelope + the closed per-family payload builders, shard_for, GenesisPlan / verify_genesis_state, AnchorManifest, and the frozen, independently seeded KAT corpus under tests/vectors/.

canopy-crypto-shred

Crypto-shred redaction primitives (ADR-036). A SealedValue is an AEAD envelope over one PII-bearing value: the plaintext is encrypted under a per-value data-encryption key, which is itself wrapped under the service’s CANOPY_ENCRYPTION_KEY (ADR-017) and stored in the service’s redaction_keys table. Redaction = tombstoning that DEK row: the ciphertext stays, so any hash over it (a snapshot’s snapshot_hash, the audit chain) still verifies, and only the plaintext becomes unrecoverable. require_kek(secrets, var) reads the KEK through a SecretProvider and fails closed; require_env_kek(reader) is the boot preflight the sealing services, canopy-seed and canopy-manage migrate apply run, reading CANOPY_ENCRYPTION_KEY through the audit-logged env provider labelled with the reader (#2490); rewrap_dek moves a wrapped DEK from the previous KEK to the current one for the rotation rewrap job (canopy-manage rewrap-keks, #2113).

canopy-secrets

The secret-provider abstraction: every read of a sensitive configuration value goes through SecretProvider, so audit logging, rotation hooks and a Vault backend have one place to land. EnvSecretProvider wraps std::env::var and emits tracing::info! (target = "canopy.secrets"; service, secret name and source — never the value) on every successful lookup; canopy_api::bootstrap_with resolves DATABASE_URL / RABBITMQ_URL through it. get_non_blank(provider, key) is the blank policy every loader shares: a blank (empty or whitespace) value counts as unset, because a SOPS ${VAR:-} substitution yields the empty string (#2489, #2511). require_with_dev_fallback(provider, key, fallback) reads through it, so outside development a blank value is refused like a missing one, and in development the fallback stands in for both; bootstrap_with's secret re-read and canopy_common::key_material apply it too.

canopy-store

S3-compatible object storage.

  • Store — wraps the object_store crate: get(path), delete(path), list(prefix); sanitize_filename(name) prevents path traversal. Every write from outside the crate carries validation (#435): put_validated(path, bytes, claimed_content_type, &UploadValidation, &dyn Scanner) validates, scans and writes, and put_prevalidated(path, bytes, &ValidatedUpload) writes bytes that validate_upload already passed, refusing a proof issued for other bytes (the applications quarantine flow, which scans after the write). Only validate_upload can build a ValidatedUpload, and its fields are private (read through getters), so no caller can alter one. The raw write is crate-private; put_fixture(path, bytes) arranges test objects and compiles only under the test-fixtures feature, which a [dev-dependencies] entry alone may enable (a canopy-store test fails otherwise).

  • ObjectStoreConfig — loaded from CANOPY_STORE* (config::Environment::with_prefix("CANOPY_STORE").separator("")): BACKEND (local | s3), BUCKET, LOCAL_ROOT, S3_ENDPOINT, S3_REGION, S3_ACCESS_KEY, S3_SECRET_KEY, MAX_UPLOAD_BYTES, ALLOW_HTTP; outside development the local backend is refused unless CANOPY_STORE__ALLOW_LOCAL_BACKEND=true.

  • validate_upload(bytes, claimed_content_type, filename, &UploadValidation) — PURE content validation (size, magic bytes, allowlist, SHA-256, filename); scanning is an explicit write-site step, not part of validation. The type is what the leading bytes say (infer), and must equal the claimed one. A PDF must begin with %PDF: infer accepts the header anywhere in the first 1,024 bytes, and canopy-store calls such bytes of no known type, so a page of HTML or a script that carries the four bytes is not stored as a PDF (#3622). The default allowlist (DEFAULT_ALLOWED_MIME_TYPES) is PDF, JPEG, PNG, GIF, TIFF, WebP and the Word and Excel formats (.doc, .docx, .xls, .xlsx). Plain text and CSV are not accepted: neither has leading bytes to recognise, so an upload of either is refused as of unknown type, and the allowlist does not list them (#3638).

  • Scanner trait + ScanReport / ScanResult / ScanError — the pluggable AV seam; NoopScanner ships here, real backends live outside the crate. scan_admitting(scanner, bytes) is the inline write-site scan gate; the applications quarantine lifecycle (ADR-042) scans asynchronously instead.

canopy-scanner-clamd

ClamAV clamd INSTREAM backend for the Scanner trait (ADR-042). Transport via clamav-client (tokio, pure Rust); response parsing is strict and ours (single NUL/newline-terminated line, 512-byte cap, UTF-8). Verdict mapping quarantines what the engine could not inspect (Heuristics.Encrypted., Heuristics.Limits.Exceeded, the INSTREAM size-limit class → Skipped); definition freshness is fail-closed (a verdict without a fresh parseable VERSION line never settles).

canopy-reference

Shared reference data — program enums, determination statuses, income/asset types, verification requirements, FIPS codes and cross-program constants — all Serialize/Deserialize with string representations. The enums: Program, FederalProgram, DeterminationStatus, IncomeType, AssetType, VerificationSource, VerificationRequirement, NoticeType, Confidentiality, DisabilityStatus, MedicarePartABasis, CmdEventType, MedicaidBenefitType (medicaid_labels, the one Medicaid display table left: a class of assistance and a Medicaid denial reason are a pack's own rows, #3422), the denial-reason codes (SnapDenialReasonCode; TANF's are a pack's rows since #3505; DenialReasonCode, the TSNAP/TMA trigger-reason vocabulary, is closed too: a code it does not name neither parses nor deserializes, #3327), Frequency, and the FIPS State / AdminUnitType. VerificationItem is the determination’s verification line item. DeterminationStatus is the written verdict only — Approved | Denied | Sanctioned (#628) — with as_str(), ALL, and TryFrom<&str> / TryFrom<String> / FromStr that refuse any other token with UnknownDeterminationStatus; the other concepts it once listed live where they are modelled (denial reason codes, canopy-snap’s ABAWD tracking, canopy-appeals IPV cases, the application, enrollment, verification and appeal lifecycles). Variant lists are the source (crates/canopy-reference/src/enums.rs and siblings) — do not quote counts from this page. DenialReasonCode's four TSNAP/TMA trigger-reason variants are canopy's own vocabulary, written in crates/canopy-reference/src/enums.rs. canopy builds without reading any configuration layer (#3301), and CrossProgramParameterTable::load refuses, at boot, a federal cross-program-2026.json whose tsnap or tma trigger_reasons names a code with no variant, naming the file, the program and the value. A new trigger reason is a variant first, then data.

denial_reasons (#3422; named medicaid_denial_reasons before #3505) holds the sentence a pack prints for each denial reason of a program, its [[medicaid.denial_reasons]] or [[tanf.denial_reasons]] rows: DenialReasonTable::load(&ConfigSnapshot, ReasonProgram) (and parse, for a file already read) refuses a duplicate or malformed code, a row with no display_text and an unknown key, naming the row, and answers text(code), contains(code) and codes(). CANOPY_EMITTED_DENIAL_CODES and TANF_TIME_LIMIT_CODE name the codes canopy-medicaid and canopy-tanf put on a denial themselves. canopy-medicaid, canopy-tanf and the pack check are its readers.

medicaid_decisions (#3446) names the decisions canopy-medicaid evaluates for a determination (DETERMINATION_DECISIONS); the service's rules client and the pack check both read them, so a decision the service gains is held to the packs by the same edit. medicaid_denial_reasons also holds CANOPY_EMITTED_DENIAL_CODES, the reason codes the service puts on a denial itself.

tanf_decisions (#3507) names the four decisions canopy-tanf evaluates for a determination (DEPENDENT_CHILD, UNIT_MEMBER, ELIGIBILITY, BENEFIT_CALCULATION, DETERMINATION_DECISIONS, and file_name). canopy-tanf's rules client and its boot check read them.

hearing_request_windows (#3394) reads the federal layer's hearing-request-windows.json: HearingRequestWindows::load(&ConfigSnapshot), and check(program, days, key), which refuses a day count under a program's floor or over its ceiling, naming the key and the authority. check_agreement(jurisdiction_toml) refuses a pack in which an enabled program's printed appeal deadline differs from its [appeals.program.<p>].filing_window_days. canopy-appeals and canopy-notices call both at boot.

medicaid_classes (#3419) holds the Medicaid and CHIP class catalogue a pack declares as [[medicaid.classes]] in jurisdiction.toml. ClassCatalogue::load(&ConfigSnapshot) returns the rows in declaration order (rows(), get(&ClassCode), contains), each a ClassRow of a ClassCode (1 to 64 characters of [a-z0-9_]), a label, a ClassTrack (magi, non_magi, chip; program() derives the MedicaidProgram), a MedicaidBenefitType, a ClassTmsis (a federal eligibility group, or the reason the class is outside T-MSIS), named limits (StatedLimit: an AmountRule shape and, when the pack states it, the LimitHousehold the limit is sized on) and named integer values. AmountRule::resolve(fpl_100_monthly, household_size) gives a limit in monthly dollars with checked arithmetic (the shapes and their resolution live in amount_rule, named ClassLimit in medicaid_classes before #3508, and moved out so another program can state its figures in the same shapes), and StatedLimit::household_for(track) names the household to resolve it for: the one stated (household = "magi" or "full"), else the MAGI household for the magi and chip tracks and the full household for non_magi. The load refuses, as a ClassCatalogueError naming the row and the file: a duplicate or malformed code, an empty label, an unknown track, benefit type or row key, a row with both or neither of tmsis_group and outside_tmsis_reason, a group the federal tmsis-eligibility-groups.json does not list, a chip row whose group is not among that file's separate_chip_codes, a limit that is not exactly one shape, a limit whose household is neither value or sits on a flat amount, and no class at all where [jurisdiction].enabled_programs names medicaid or chip. canopy-medicaid loads it at boot and decides from it (#3420); canopy-pack-check loads it for the class check.

canopy-signing

ECDSA P-256 detached JWS (RFC 7515 Appendix F) for determinations (ADR-002), and the KeySigner primitive. canopy-signing does not depend on canopy-auth; canopy-auth depends on it.

  • SigningKey::from_pem(pem, key_id) — loads a PKCS#8 private key; sign_detached(payload) → Result<String, SigningError> returns the base64url JWS, its protected header {"alg":"ES256","kid":…,"typ":"canopy-determination+jwt"} (DETERMINATION_JWS_TYP). sign_detached_as(payload, typ) signs under another token class’s typ: canopy-notices signs documents under DOCUMENT_JWS_TYP (canopy-document+jws, #2956).

  • VerifyingKey::from_pem(pem, key_id) — loads an SPKI public key; verify_detached(payload, jws) → Result<bool, SigningError>. It refuses (InvalidJws) a header whose alg is not ES256 or whose typ is not DETERMINATION_JWS_TYP, absent included, before checking the signature (#2953, RFC 8725 §3.1 and §3.11). verify_detached_as(payload, jws, typ) is the same check for another token class (#2956).

  • VerifyingKeyRegistry (verifier.rs) — in-memory verifying keys keyed by (program, kid), the kid being derive_kid over the key’s LF SPKI PEM (the kid the program’s boot signer stamps, so a CRLF PEM maps to the same kid). add_key(program, key) → Result<String, SigningError> registers one key and returns its derived kid; from_secrets(secrets, dev_keys) registers the current key per program the same way, from CANOPY_VERIFY_KEY_<PROGRAM> or, in development only, .keys/<program>-public.pem (no _PREV slot); rotation_status() reports RotationState::{SingleKey, DualKeyRotation} per program. with_history_provider(Arc<dyn canopy_crypto_shred::KeyHistoryProvider>) installs the ADR-036 lazy-load. verify_with_history(program, payload, jws) → SignatureCheck is the production determination path (#2061): an empty or unparseable detached JWS, one whose header is not ES256 with the determination typ (#2953, absent included), or one with no string kid, is Malformed; a kid without the canopy-{program}- prefix is UnknownKey before any key is tried; the key registered under exactly that kid, or else the key the provider serves for it, decides Verified or Mismatch; a provider miss, or no provider, is UnknownKey; a provider error or an unparseable served PEM is KeyLookupFailed. A determination signed with a since-retired key still verifies through the provider. canopy-eligibility maps each non-Verified outcome to a QuarantineReason (ADR-002 Amendment 5).

  • DeterminationSigner trait — fn sign(&self, payload: &[u8]) → Result<String>, implemented by SigningKey.

  • load_program_signer(secrets, program, dev_keys) → Result<ProgramSigner, ProgramSignerError> — the program services' boot-time signer (program_signer.rs): the PEM from CANOPY_<PROGRAM>__SIGNING_KEY through the audited SecretProvider, else, in development only, .keys/<program>-private.pem; the kid derived from the public key; ProgramSigner { signer, identity } carries the (kid, public_pem) pair canopy_api::spawn_signing_key_registration_if_configured publishes. With no key every program refuses to boot (#2489).

  • ApplicantClaimIssuer and ClaimVerifyingKeyRegistry::verify_applicant_claim (applicant_claim.rs, #1442) — the portal’s applicant ownership-claim minting and its verification; the origin services load the verifier through canopy-auth’s boot_applicant_verifier. A claim’s protected header is {"alg":"ES256","kid":…,"typ":"canopy-applicant-claim+jwt"} (APPLICANT_CLAIM_TYP). Verification refuses any other or absent alg (ClaimVerifyError::UnexpectedAlg) and any other or absent typ (UnexpectedTyp) before it looks up the kid, so a token of another type signed by the portal’s key never passes as a claim (#2575, RFC 8725 §3.1 and §3.11). VerifyingKeyLoadError is that loader’s and from_secrets' error.

  • KeySigner (key.rs, ADR-049 §9) — the backend-agnostic ES256 signer: public() → &PublicKeyInfo (kid: Kid, alg: JwsAlg, jwk: PublicJwk) and async sign(signing_input) → Result<RawSignature, SignError>, where RawSignature is the 64-byte r‖s form (RFC 7518 §3.4) and SignError is Unavailable / Timeout / Refused / Internal. JwsAlg is #[non_exhaustive], Es256 only. Kid is an opaque key id of 1–128 characters from [A-Za-z0-9._-]; Kid::rfc7638(&PublicJwk) is the RFC 7638 thumbprint. PublicJwk (jwk.rs) holds the canonical unpadded base64url x / y of a P-256 point: from_coordinates refuses any other encoding and any point off the curve (JwkError). LocalP256Key::generate() is the in-memory backend: a CSPRNG key under its thumbprint kid, with no accessor, Clone or serialization for the private scalar, zeroized on drop. mint_compact_jws(signer, typ, claims, deadline) builds the compact JWS with the header {"alg","kid","typ"} outside the signer and answers SignError::Timeout when the signer misses deadline. conformance::assert_key_signer_conformance(&dyn KeySigner) is the behaviour every backend must show (a verifying r‖s signature under the published JWK, refused under another key, and a verifying compact JWS naming the published kid); it compiles for canopy-signing’s tests and under the test-helpers feature. Determination signing does not use it yet (#2502).

  • ProvisionedP256Key (provisioned.rs, ADR-049 §10, #2548) — the KeySigner over a provisioned key, for a canopy-identity client’s private_key_jwt assertions. from_pkcs8_pem(&Zeroizing<String>) takes an unencrypted PKCS#8 PEM of an ECDSA key on the named curve P-256 and publishes it under its RFC 7638 thumbprint kid. The scalar has no accessor, Clone or serde implementation, is zeroized on drop, and Debug prints only the public half. load_provisioned_key(secrets, key_name) reads the PEM through require_secret, with no file fallback in any environment; key names end in _PRIVATE_KEY, so the secret-loads gate refuses a raw environment read of one. ProvisionedKeyError is Missing (unset or blank, naming the secret), Unreadable (the provider failed), Malformed, NotP256 (PKCS#8 for another algorithm or curve) or Encrypted (an ENCRYPTED PRIVATE KEY PEM); none carries key material. It passes assert_key_signer_conformance.

  • keygen::generate_p256_pkcs8() → Result<Zeroizing<String>, SigningError> (ADR-049 Amendment 23; #2849) — a fresh P-256 private key as unencrypted PKCS#8 PEM, zeroized on drop, for a client that keeps its own key across runs: canopy-auth’s device client generates canopy-cli’s DPoP device key with it. ProvisionedP256Key::from_pkcs8_pem loads it, and LocalP256Key still has no export.

Generate a production pair: canopy-manage gen-signing-keys --program snap --output-dir <dir>; rotation is Signing Key Rotation.

canopy-typst

PDF rendering via Typst (ADR-010); consumed by canopy-notices.

  • RenderEngine::new(tree: NoticeTree) — over a NoticeTree, one or more notices/ roots lowest precedence first, each file resolved from the highest root that holds it and fonts the union of the roots' fonts/ (ADR-051’s layer rule inside notices/; canopy-notices builds it from every configuration layer’s notices/); spawns a dedicated OS thread for Typst compilation (synchronous on that thread; async wrapper for callers).

  • RenderEngine::with_fixed_clock(at) — pins the instant stamped on every render (the PDF creation date, rendered_at, and the day datetime.today() gives a template), so the same template and inputs give the same bytes (#461). For tests: canopy-notices compares the SNAP approval, expedited approval and denial letters with the PDFs under services/canopy-notices/tests/notices/golden/; UPDATE_GOLDEN=1 rewrites them after an intended change.

  • RenderEngine::render(program, template_key, context) → RenderedNotice — the NOA path: resolves the template via the manifest, compiles the .typ source, returns PDF bytes + metadata.

  • RenderEngine::render_document(relative_path, &serde_json::Value) → RenderedDocument — the general-document path (ADR-029): any template file in the notice tree from free-form JSON inputs, bypassing the NOA manifest and NoticeContext; the path is ../absolute-validated.

  • manifest::Manifest::load(path) — loads manifest.toml, mapping template keys to versioned .typ files with form numbers and each letter’s required hearing_rights flag (#2431), carried on the resolved TemplateRef. NoticeContext is the typed render context (agency identity, recipient, case number, notice date, locale, the fair-hearing and continued-benefits fields, plus free-form program_data each template owns); it deliberately carries no form_number / template_version — the manifest-resolved TemplateRef is their only source, so the archived PDF and an on-demand re-render cannot print different footers. The engine also sets the template_program input, the snake_case slug of the program whose manifest entry the template resolved under, after program_data, so no payload key replaces it; a file several programs' entries share prints per-program content from it (#2463).

Templates live in each configuration layer’s notices/, the neutral ones in the fixtures/config/notices-neutral base layer (shared components in components/; non-NOA templates such as audit/citation.typ beside the program folders).

canopy-rules-client

HTTP client for the canopy-rules evaluation API (POST /v1/evaluate).

  • RulesClient::new(http, base_url) — over the caller’s shared reqwest::Client (a program service’s main passes canopy_common::http::data_path_client()); every call carries RULES_CALL_TIMEOUT (10 s) as its total timeout, whatever total the injected client has.

  • contract::check(decision, raw_jdm, &Supplied { thresholds, inputs }) → Result<(), ContractError> — whether a decision's text reads only the context.thresholds. paths and input. names its service sends; ContractError::Unsupplied names the decision, the half of the input and every unsupplied reference. canopy-snap and canopy-wic call it at boot (the decision contract), and canopy_test_lib::threshold_sync shares its extractors (extract_threshold_refs, extract_input_refs).

  • evaluate(rule_set_name, context_type, context_id, input, source: &dyn BearerSource) → serde_json::Value — evaluates a JDM ruleset (rule_set_name is the decision's file name without .json) and returns the decision-table output; evaluate_with_corpus_hash also returns the ruleset corpus hash the determination pins.

See Rulesets for the JDM format and authoring guide.

canopy-extension-host

Loads a jurisdiction's extension module (ADR-052). canopy-medicaid calls it.

  • Manifest and Bundle read extensions/<name>/ from a ConfigSnapshot or a pack directory: extension.toml, module.wasm and migrations/*.sql. A manifest that does not validate, a second bundle directory, or a directory that does not match the manifest's name is an error, never a skip. Bundle::record is the ExtensionRecord a determination signs.

  • The runtime feature (on by default; canopy-pack-check links the crate without it) adds the WebAssembly runtime and the database sandbox.

  • Runtime::new compiles the component with wasmtime and proves it imports only the contract's host interface. admit and outcome run in the caller's transaction; decide has no database. Each call is a fresh instance with the manifest's fuel and memory limits. Any failure is a CallError; none continues without the module's answer.

  • sandbox::install creates the module's role, schema and two executor functions and applies its migrations as that role. sandbox::Call wraps one call: a savepoint, the manifest's timeouts, then a reset of the session and a check for residue.

  • The contract is wit/canopy-extension.wit. The fixture modules are fixtures/extension-src/, committed built as fixtures/extensions//module.wasm; cargo xtask extension-fixtures holds the two together by a recorded source digest.

canopy-pack-check

The checks of a configuration layer's own content, as a library (#3401, #3402, #3403): cargo xtask rules check, policy audit, rules processing-days, canopy-rules and canopy config check call it, so the gate, the service and an author's check of a working copy apply one set of rules. It discovers no layer and prints nothing: each function takes the directory or files it reads and returns typed values, and the caller renders them.

  • compile_layer(dir) → Result<Vec<FileCompilation>, CheckError> — every *.json directly under a layer directory, in file-name order, compiled through zen-engine (GraphContent, then Decision), the path canopy-rules evaluates. Each file's FileOutcome is Compiled(CompiledDecision), ParameterFile (no top-level nodes array), Failed, NotJson or Unreadable, and misnamed_as carries the embedded name of a decision not named after its file. compile_source(path, raw) does the same for text already read.

  • replay_fixtures(&[CompiledDecision], fixture_dir) → Result<Vec<FixtureOutcome>, CheckError> — each fixture evaluated in-process against every compiled decision whose name is its ruleset (or only the layers its packs lists), its output read as canopy-rules serves it and held to its expect block. An outcome is Evaluated (with the failure, if any), Unmatched, Ignored, NotJson or Unreadable.

  • replay_pack_fixtures(&[CompiledDecision], fixture_dir, jurisdiction) — the same replay for one pack's fixtures over its stack: a fixture's packs is read against the jurisdiction, not a directory name, because a working copy is cloned under any name and an unreplaced decision sits in the federal directory. A fixture whose packs leaves no decision yields FixtureOutcome::Excluded, so no fixture is passed over without an outcome.

  • admit_replacement(name, earlier, later, overrides) → Result<(), OverrideRefusal> — whether a decision may replace a lower layer's of the same name: only from another directory, and only when the replacing layer's manifest lists the name under overrides. canopy-rules calls it as it loads a stack (NamedFilesystemLoader::from_files).

  • audit_pack_citations(pack_dir, slug, max_staleness_days) → Result<PackCitationAudit, CitationError> — the canopy_policy::citation audit of a pack's jurisdiction.toml against its citations.toml, including the election citations against the federal option keys. A PackCitationAudit carries the manifest, the pack's key count and every ValidationIssue; findings() is its error-severity issues (a staleness warning is not a finding). federal_option_keys() and orphan_allowlist(CitationFamily) are the two lists the audit consults, compiled in from compliance/federal-options/*.toml and compliance/adr-031-citation-orphan-allowlist.toml, so a binary enforces the lists of its own version; a test holds the compiled-in registry files to the directory. cargo xtask policy audit reads the federal family's allowlist from the same function.

  • restated_federal_constants(jurisdiction_toml) → Result<Vec<Finding>, CheckError> — canopy-common's refuse_pack_copies applied to a pack file for snap-procedure.json and tanf-time-limit.json: at most one finding per federal file, with the message a service refuses to boot with. canopy-common is declared without its sqlx feature, so the crate links no database driver.

  • medicaid_classes(federal_dir, pack_dir, jurisdiction) → Result<Vec<Finding>, CheckError> — what canopy-medicaid would refuse at boot or at a determination, found from the files (#655): a [[medicaid.classes]] catalogue that does not load (then the only finding); a class code the pack's cascade order, hierarchy, [medicaid.cooperation] exempt lists or [medicaid.adult_demonstration].class names that no row declares; and a reason code medicaid-denial-reasons.json can answer that no [[medicaid.denial_reasons]] row gives a sentence for. A pack that enables neither Medicaid nor CHIP has none.

  • appeal_windows(federal, pack) → Result<Vec<Finding>, CheckError> — what canopy-appeals and canopy-notices would refuse at boot (#3557): an enabled program with no [appeals.program.<p>] row, a filing_window_days outside its federal bound, or a printed appeal_deadline_days that differs from the window. A blank citation or office, an unknown key and the day-count range stay the services' own checks.

  • paired_clocks(jurisdiction_toml) → Result<Vec<Finding>, CheckError> — one finding per SNAP processing clock whose [snap.issuance] and [shared.application_processing] values differ or are set on one side only. clock_disagreements(issuance_doc, processing_doc) → Vec<ClockDisagreement> is the comparison over two parsed documents, which cargo xtask rules processing-days also calls for the two files a YAML tier selects; carries_clocks(doc) says whether a document sets any of the four keys.

  • undeclared_replacements(&[StackLayer]) → Result<Vec<Finding>, CheckError> — admit_replacement applied across a stack of layer directories, lowest first, each with the overrides its manifest declares. It returns a finding for every refusal, where the service stops at its first.

  • stack_decisions(layers) → Vec<CompiledDecision> — of the compilations of each layer, lowest first, the highest layer's compiled copy of each name: the decisions a stack evaluates.

  • check_pack(&PackStack) → Result<PackCheck, PackCheckError> — every check above on one pack over a federal layer, which is what canopy config check runs: the pack's compile and decision names, the override rule across federal then pack, the pack's own fixtures/rulesets/ (when present) replayed against stack_decisions, then the federal-constant, citation and paired-clock checks of its jurisdiction.toml. A PackCheck holds every Finding and the Note values that fail nothing (no fixture directory, a fixture ignored or unmatched, a stale citation). The replay blocks on a runtime of its own, so an async caller runs it on a blocking thread.

  • Finding { check, file, message } — one thing wrong, in the shape a caller serializes (check is a kebab-case Check); FileCompilation::findings(), FixtureOutcome::finding(), PackCitationAudit::findings() and the two pack-file checks produce them. CheckError is a check that could not run: a directory that cannot be listed, a pack file that cannot be read or is not TOML, or the evaluation runtime.

canopy-persons-client

Service-to-service HTTP client for canopy-persons — one shared definition of the read/write surface every service caller needs (ADR-001). Every call asks its source for a bearer and goes through send_with_retry (a receiver’s refusal of the bearer retried once); a 404 on a read resolves to Ok(None).

  • PersonsClient::new(http, base_url, source: Arc<dyn BearerSource>) — the client’s own source, a service’s sender for its shared client. calls() sends with that source (system origin); on(&dyn BearerSource) with another, a request’s outbound; with_source(source) is a copy whose calls() send with source, a request’s copy of the shared client.

  • Reads: get_person(id, as_of), person_core(id, as_of) (no SSN opened, #2706), household_for_person(id, as_of), get_household_full(id, as_of, projection) (the SSN opened only when projection names PersonSsn, #2705), list_addresses, and the bulk batch_get_persons / batch_get_households.

  • Writes (create/claim): create_person, create_household, claim_member, claim_income, claim_asset, claim_expense, claim_address — each takes an Option<&FinalizeStep> that tags the write for idempotent finalization (ADR-038); None is an ordinary write.

  • Finalize control surface (applications-only, ADR-038): register_finalize(op, gen), release_finalize(op, gen), cancel_finalize(op, gen), get_finalize_operation(op). finalize::StepKey is the per-step receipt-key grammar (person(i) / household() / member(i) / income(j) / asset(k) / expense(m)); finalize::FinalizeStep { operation_id, generation, step_key } is the tag threaded into the writes above.

canopy-validators

Cross-service referential-integrity validators (ADR-025): a write that carries an ID minted by another service cannot rely on a Postgres foreign key, so it validates over HTTP. The crate is the CrossServiceValidator trait plus the production implementation over reqwest and the service-class JWT machinery; wired per service in main.rs.

canopy-overpayments

Cross-program overpayment recovery (PAMMS 9000 / 7 CFR 273.18): the claim, repayment plan and recoupment ledger types, the canonical migrations, the store and the HTTP handlers. The code is shared; the data lives in each program service’s own database (ADR-001): the three tables (overpayment_claims, repayment_plans, recoupment_ledger) come from migrations/canonical.sql, stamped byte-identically into each consuming service’s migrations/. Later canonical migrations follow the same parity contract, among them CANONICAL_DISCOVERED_BY_ACTOR_MIGRATION_SQL (#1008), which makes overpayment_claims.discovered_by the mandatory discovered_by + discovered_by_service actor pair. OverpaymentClaim.discovered_by is an Actor, and CreateClaimRequest carries no actor (deny_unknown_fields): the shared post_claim records the bearer’s (canopy-snap’s own create handler does the same). Since #3567 a claim may record the benefit months it covers: CreateClaimRequest.period and OverpaymentClaim.period (Option<MonthPeriod>), stored by the canonical canonical_claim_period.sql; a program that requires one adds its own CHECK, as canopy-snap does.

  • store — the claim, repayment-plan, recoupment-ledger and adjustment queries (#1012). Each fn runs on the pool or executor its caller passes; the queries are runtime sqlx, so the crate compiles against no schema. Every writer takes the caller’s instant and binds each stamp it writes from it — no SQL now(), and CANONICAL_STAMPS_NO_DEFAULT_MIGRATION_SQL drops the stamp defaults (#2576) — so a program service passes its request’s or delivery’s instant from its decision clock. Callers are api and the three program services' own paths (their event subscribers, and canopy-snap’s recompute, IPV, claim-screen and manual-create paths).

  • api — the six handlers on five paths (list_claims, post_claim, get_claim, post_repayment_plan, post_recoupment, get_ledger), routes(list_admission, claims), which registers all five paths (#1012), layering the mounting service’s delegated constant for the list as a ListAdmission and its ClaimAdmissions for the others, and claim_routes(claims), which registers the four per-claim paths under /overpayments/{id} without /overpayments itself (#2242). canopy-tanf and canopy-medicaid each merge routes(…) into their api::routes() and name the six handlers in their ApiDoc. canopy-snap registers /overpayments with its own floor-screened create handler (services/canopy-snap/src/api/overpayments_handler.rs, which screens a claim against the pack’s claim floors before filing it) beside the shared list_claims, merges claim_routes(…), and names its own post_claim in its ApiDoc. to_api_error is public — the one OverpaymentError → HTTP mapping every claim handler uses, a service’s own create handler included. The routes sit under /v1 behind each service’s receiver: the per-claim reads admit a system caller or a CASEWORKER_OR_ABOVE_ROLES delegation, the writes a system caller or a CASEWORKER_WRITER_ROLES delegation (ClaimAdmissions::ANY_SYSTEM, which canopy-snap and canopy-medicaid pass; canopy-tanf passes its own, admitting canopy-reporting’s system token alone, #3322), and the list the mounting service’s delegated constant (SNAP_GET_OVERPAYMENTS and its siblings). The handlers take the Extension<PgPool> each service’s main.rs layers, so each service’s handlers reach only its own database; the writing handlers also take its Extension<DecisionClock> for their stamps (#2576).

canopy-policy

Policy traceability types (ADR-011): the citations.toml manifest schema and its validation, federal-citation validation against the federal layer’s *.json (ADR-031), the workflow-guidance template schema, and citation::DEFAULT_RULESET_AUTHORITIES (the authorities a fixtures/config/default row may carry — Rulesets). Used by cargo xtask policy, plus one runtime surface: wic_food_packages, the strict WIC food-package resolver canopy-wic loads at boot and canopy-seed uses at generation time. It also holds the two WIC engines a service and the seed generator must agree on: wic_food_packages (the food-package resolver) and wic_certification_periods (certification ends from anchor dates; Rulesets). canopy-wic runs both, and canopy-seed dates and packages its seeded WIC certifications through the same code.

canopy-composition and canopy-plugin-macros

The worker-portal composability runtime (ADR-021 + ADR-022; consumer: canopy-web). canopy-composition implements the five-layer resolver — user delta (RFC 6902, DB, keyed by the worker’s OidcSubject, 1008) over role override (RFC 6902, DB) over jurisdiction live (RFC 6902, DB) over jurisdiction baseline (RFC 7396 merge patch, the pack’s composition/) over compile-time system defaults — and CompileTimePluginSource, which reads the PluginRegistration slice the binary passes it. canopy-plugin-macros is the [canopy_plugin] proc-macro (ADR-021 Decision 2): from the slug and manifest arguments it emits a pub static REGISTRATION (a PluginRegistration) beside the handler; canopy-web lists each one in PLUGINS (services/canopy-web/src/plugins.rs, #855). TOML validation still happens on the first Plugin::manifest() call.

canopy-contracts-* (one crate per backend service, plus facts)

canopy-contracts-{appeals,applications,caps,eligibility,enrollment,medicaid,notices,persons,renewals,reporting,rules,security,snap,tanf,verification,wic} are the wire-shape contracts for that service’s HTTP API — pure data (serde types, paths.rs route constants), no axum, no sqlx, no service-local types — so a caller, a test and the OpenAPI snapshot in docs/modules/ROOT/openapi/ share one definition. There is no contracts crate for canopy-web, canopy-portal or canopy-exchange. canopy-contracts-facts (ADR-027) is the keystone of fact authoring: every eligibility-fact write is a Claim<T> — a value plus its author (Author::Worker carries the caseworker’s OidcSubject, #1008) and provenance — read and written by canopy-persons, canopy-applications, canopy-web and the determination input snapshot (ADR-028). Provenance is fully encapsulated: every build path yields only pairs in the ADR-027 author/status table (the infallible constructors by construction, Provenance::from_stored and Deserialize by a shared check), so an inconsistent provenance (a worker on a proposed lead, System outside an accepted backfill row) cannot be built or parsed; the checked paths refuse it with a typed ProvenanceError.

canopy-test-lib

Shared test helpers for the integration and E2E lanes (Testing).

  • clients::* — one typed client per service (SnapClient, TanfClient, MedicaidClient, AppealsClient, ReportingClient, RulesClient and the rest). No method returns serde_json::Value (quality budget B7, locked at zero, #3411): a JSON response is read into a typed struct, nearly always its canopy-contracts-* type, so a response that drifts from it fails the test's read. The CSV exports return their bytes. Two methods take any serializable request body, because this crate cannot name one type for it (#3408): ApplicationsClient::upsert_section, whose body is the payload struct of whichever section it names, or hand-written JSON for a body the handler must refuse, and TanfClient::evaluate_work_requirements, whose input type is canopy-tanf's own.

  • TestClient::new(base_url) — no auth (for 401 tests); .with_token(token) carries a bearer from tokens; .healthy_or_skip() — probes /livez and reports a miss itself through skip_or_panic by service name and URL, so a setup guard is if !client.healthy_or_skip().await { return None; } with no call after it (#2076, #2079); .test_clock_or_skip() — the same report for a missing /test/clock, the guard every clock-steering test takes (#3060, Testing); TestResponse — assert_status(code), json::<T>(), text().

  • TestConfig::from_env() — every service's URL from its CANOPY_TEST__*_URL variable, with .ports.env (found walking up from the working directory) loaded first and an explicit variable winning, else the compose default. TestConfig::from_lookup(lookup) builds the same from the values a lookup answers, so a unit test never reads a .ports.env an earlier run left in the checkout (#3337).

  • crash_armer::CrashArmer::arm(pool, table, n) — kills the database session that issues the nth write statement on one table of a test's own schema, before it writes, so a test leaves the residue a crashed worker leaves (#1597). It fires once; finish() removes it and fails when it never fired. It refuses any schema not named test_….

  • infrastructure_available() — TCP-probes Postgres and the rules canary; under CANOPY_TEST_INFRA=required or CANOPY_CI=true an unavailable stack PANICS instead of skipping (every cargo xtask lane arms the former — Testing › infra required); skip_or_panic(detail) is the dependency-level skip seam, and ok_or_skip(result, what) reports a failed setup step’s error through it and answers Option (#3132).

  • poll_until(description, timeout, interval, check) / poll_until_observed(…​) — wait on an observed condition instead of sleeping. poll_until's check answers Some(value) once the condition holds; a wait that times out panics naming what it waited for. poll_until_observed's check answers Ok(value), or Err(seen) while it waits, and its timeout panic also names the last seen, so a failed wait reports what was there (#3587). canopy-mq's fault tests read a queue's consumers this way.

  • identity_broker (ADR-049 Amendment 11; #2768) — canopy-identity tokens for tests through production grants only, the battery’s every token (Testing › the token broker). TokenBroker::new(BrokerConfig) (async: it reads the devstack upstream’s credentials and the devstack CA, every confidential client’s key from <keys_dir>/<client-id>.pem, and resolves the upstream’s address) or TokenBroker::from_env() over BrokerConfig::from_env(), which reads CANOPY_TESTIDENTITY_ISSUER, CANOPY_TESTSECURITY_URL, CANOPY_TESTUPSTREAM_CREDENTIALS, CANOPY_TESTUPSTREAM_CA, CANOPY_TESTUPSTREAM_ADDR, CANOPY_TESTIDENTITY_KEYS, CANOPY_TESTIDENTITY_BROKER_CACHE and CANOPY_TESTWEB_ADDR (.ports.env loaded first; a relative path resolves against the workspace root holding it). A person is a cast name (upstream::PERSONS; any other is BrokerError::UnknownPerson). session(person) → FederatedSession; delegation(person, CanopyService, &Narrowing) and stepped_up(person, CanopyService) (unnarrowed, from a sign-in at most 300 s old) return canopy-web’s delegation token; system(ConfidentialClient, CanopyService, scope) returns the client’s system token; cli(person, CanopyService) returns canopy-cli’s delegation from the person’s device session, which the broker logs in, approves (approve_device(person, &UserCode), as canopy-web approves a device) and keeps under the cache, replacing it by one login when it is gone, ended or stale (BrokerError::Device, BrokerError::IssuerClient); forget(person) drops a cached session but keeps its last sign-in. A browser sign-in’s steps (ADR-049 Amendment 24; #2856): upstream_sign_in(person) → UpstreamSession signs the person in at the upstream, and authorise_query(&UpstreamSession, query) → Authorization answers the upstream’s response to a relying party’s own authorization query for that person; upstream() → &Upstream names the upstream’s kind, origin, authorization_endpoint and scopes, canopy-web’s client_id and registered redirect_uris, and the CA as ca_pem, all public; ui_credentials(person) → UiCredentials answers the username, password and a TOTP code, zero-padded to the upstream’s digits, with at least 15 s left in its step (totp_valid_until, Unix seconds), stamped as a sign-in under the person’s spacing so no code is presented twice, its Debug showing neither secret. link_cast() → LinkReport links every cast person but LINKING_ADMIN to SeedPerson::realm_subject() through the admin routes where its pair does not already open as it, the devstack bring-up’s last step. BrokerError::is_unavailable names a 503 from any grant; a system-token call that shared a failed acquisition (SystemTokenError::SharedFailure) is retried as a 503 is, and the federation grant’s open and renewal are retried too. TOKEN_PATH, REVOKE_PATH and JWKS_PATH are canopy-security’s endpoint paths, held equal to its own by its federation test. upstream::UpstreamDriver (ADR-049 Amendment 26) drives whichever upstream a credentials file names: devstack() the devstack’s running one, new(credentials, client) over a client pinned elsewhere than the loopback publication from_credentials assumes; sign_in, sign_in_with, authorise, authorise_query and tokens_for sign in and authorise as a browser would, expire_account, restore_account and set_roles are the conformance cases' admin writes, and oidc() is the plain OIDC client (upstream::oidc::OidcClient: exchange, refresh, revoke, userinfo, discovery, JWKS). upstream::{Credentials, Secret, TotpSeed, UpstreamError} are vendor-neutral; Credentials::profile_yaml is the profile canopy-web would load for the server.

  • tokens — a test’s canopy-identity tokens through one process-wide TokenBroker, built from BrokerConfig::from_env() by the first helper called, each → Result<String, BrokerError>: worker(person, CanopyService) (canopy-web’s delegation), stepped_up(person, CanopyService), system(ConfidentialClient, CanopyService) (the purpose’s every scope), portal(CanopyService, Option<&str>) (canopy-portal’s system token, one scope or every scope) and cli(person, CanopyService) (canopy-cli’s delegation from a device session). tokens::or_skip holds the same five answering Option, a miss reported through skip_or_panic with the broker’s error before the None. cast(username) → &str maps a pre-switch test username to its cast person (the same name, but admin is canopy.admin); system_caller(CanopyService) → Option<ConfidentialClient> names the client a system() arm’s test mints for. bearer_sub(jwt) / bearer_iss(jwt) read a minted token’s sub / iss unverified, and mint_applicant_claim(application_id, household_id, person_id) signs the portal’s applicant ownership claim with the devstack key; all three are re-exported at the crate root (Testing › the token broker).

  • identity — canopy-identity receivers and senders for an in-process test router: offline_receiver(service) holds no key, so it refuses every token (token_rejected); devstack_receiver(service) verifies against the devstack’s canopy-identity from the keys the broker reads; devstack_sender(client) is a service’s real sender over the devstack, for a router whose requests call live peers; idle_sender(client) sends to an issuer nothing answers; FixedBearer and fixed_source(token) answer one fixed token for a stub receiver; test_principal builds the Principal a receiver would insert; and bearer_rejected() is a receiver’s 401 token_rejected, for a stub that scripts the sender’s one retry.

  • web_origin — web_client(), the client a test reaches canopy-web’s public origin with (CANOPY_TESTWEB_ORIGIN): it pins web.canopy.test to CANOPY_TESTWEB_ADDR, trusts the devstack CA alone and follows no redirect.

  • device_flow — stub partners for canopy-cli’s device flow, for tests of canopy-cli and the operator tools with no devstack: DeviceIssuer, a loopback canopy-identity that authorizes a device at once and answers every grant with a token no real receiver trusts, and StubReceiver, which answers its script and records each request’s method, path and bearer.

  • mock — in-process stand-ins for the services a test's subject calls, each answering the owning service's contract type (#3408). spawn_mock_applications_context() and its _with(rows), _kind(rows, kind) and _recert(rows, end) forms serve canopy-applications' DeterminationContextResponse over the DeterminationContextProgram rows given; context_program(program, status) is a row with no episode, to extend with struct update syntax. spawn_mock_persons() serves canopy-persons' HouseholdWithMembers and HouseholdFull (one self member), Person, and empty income, asset and expense lists, under fresh ids on every read. spawn_mock_enrollment_state() serves the not-enrolled household: no live enrollment, and no certification (404). spawn_router(router) binds any router to an ephemeral port and returns a MockHandle whose drop aborts the server.

  • mock_issuer — MockIssuer, the mock upstream OIDC issuer: discovery, a JWKS of the fixture keys (MockKey), a scripted userinfo endpoint, and minting (mint, mint_raw, mint_template); no token or introspection endpoint (Testing › the mock upstream issuer).

  • config::pack_snapshot(jurisdiction) / config::pack_layer_dir(name) / config::is_real_layer(name) (#3365) — the real federal layer and a real jurisdiction's pack, for a pack_infra_tests module; refused in the unit lane (CANOPY_TEST_REAL_LAYERS=forbidden). See unit tests read fixture packs only.

  • config::snapshot(jurisdiction) / config::layer_dir(name) (ADR-051; a fixture pack stacks on the synthetic test-federal layer, #3365) — the configuration a service of georgia, default, test-min or test-max boots on, as unverified working copies of this checkout (federal, then notices-neutral beneath a fixture pack, then the pack), and one layer’s directory; an unknown name panics naming the known ones (crates/canopy-test-lib/src/config/layers.rs).

  • EphemeralSchema — the per-test schema with runtime-loaded migrations (Testing › ephemeral schemas).

  • legal_day (#2523) — the services' legal day in the loaded pack’s timezone: legal_timezone() ([jurisdiction].timezone of the CANOPY_TEST__JURISDICTION pack, through canopy_common::settings::load_jurisdiction_timezone over config::snapshot), legal_today() (the decision clock’s instant as a date in that zone, the funnel the services stamp legal dates through), legal_date_at(instant) (for an instant read back from a service’s gated clock), legal_instant(day, time), legal_noon(day) and legal_rfc3339(day, time) (a local time of day on a date in that zone, as an instant or as RFC 3339 with the zone’s offset; noon is the mid-day seed a fixture receipt uses) month_boundary_instant(month_start, tz) (an instant at which the zone’s month and the UTC month differ, to pin a gated clock at) and day_split_instant(day, tz) (an instant whose date in the zone is day while its UTC date is not — 23:30 local west of UTC, 00:30 east of it — to pin a decision clock at when proving a legal date, #2241). A test never takes "today" from the UTC date or names a zone (Testing › Time).

  • chaos — the in-process production fixtures of ADR-020: spawn_outbox_drainer_for_chaos(pool, broker_url) → Result<ChaosOutboxHandle, anyhow::Error> (a drainer against a REAL devstack broker URL). Chaos tests using them MUST be #[tokio::test(flavor = "current_thread")] — SpanCapture uses a thread-local subscriber; the pattern and how to add a contract are the chaos runbook.

Devstack test users are the cast (upstream::PERSONS; Kanidm declares it in devstack/kanidm/migrations/00-canopy.hjson, and provisioning creates it at Keycloak and ZITADEL), each person’s random password and TOTP secret in the upstream’s credentials file, .devstack/idp/kanidm.json, keycloak.json or zitadel.json (Local Development › The devstack’s upstream). A test takes a person’s token through tokens, never a password.

Edit this page · default