Shared Crates Reference
- canopy-common
- canopy-types
- canopy-auth
- canopy-api
- canopy-config
- canopy-db
- canopy-mq
- canopy-chain
- canopy-crypto-shred
- canopy-secrets
- canopy-store
- canopy-scanner-clamd
- canopy-reference
- canopy-signing
- canopy-typst
- canopy-rules-client
- canopy-extension-host
- canopy-pack-check
- canopy-persons-client
- canopy-validators
- canopy-overpayments
- canopy-policy
- canopy-composition and canopy-plugin-macros
- canopy-contracts-* (one crate per backend service, plus facts)
- canopy-test-lib
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 includeBadRequest,Unauthorized,Forbidden,NotFound,Conflict,Gone,UnprocessableEntity,PayloadTooLarge,NotImplemented,ServiceUnavailable,BadGateway,CodedandInternal; the handler return type, rendered as RFC 9457 Problem Details JSON viaIntoResponse.ApiError::database(context, err)(andFrom<sqlx::Error>, which calls it) maps a database failure whose constraints client input can trip: pool exhaustion → 503, anerror::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
sqlxfeature — off by default, and the only thing that makes sqlx a dependency of the crate. It addsFrom<sqlx::Error> for ApiError,ApiError::database,ApiError::internal_databaseanderror::ConstraintViolation, and switches oncanopy-types/sqlxwith 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 normalsqlxdependency declarescanopy-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 shippedcanopybinary 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 stagedcanopythat links the driver (The devstack's binaries, #3414).cargo xtask feature-buildscompiles canopy-common with the feature off. -
settings::ServiceSettings— the shared baseline every service boots on (port, database/broker URLs, the canopy-identity issuer pairidentity_issuer/identity_internal_url, the configuration sourceconfig_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 overlayCANOPY_ENVnames (dev.yamlfor development,prod.yamlfor production,<value>.yamlotherwise, none when unset), then the whole-stackCANOPY_CONFIG_SOURCE,CANOPY_POLICY_ROOTandCANOPY_CONFIG_ALLOW_UNVERIFIED, thenCANOPY_{SERVICE}__*env — and partitions it byServiceSettings::FIELDSinto the baseline and the caller’s<Svc>Config.LoadOptions::reserved_keysdrops keys read elsewhere on purpose (secrets viacanopy-secrets, overrides via their own strict recognizers) before serde sees them;mirrored_keyscopies a key both structs declare (such as canopy-security’sidentity_issuerandidentity_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 noconfig_source, namingCANOPY_CONFIG_SOURCEand 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 whenLoadOptions::config_rootisNone, 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 incanopy-api'sbootstrap_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 fromCANOPY_ENCRYPTION_KEY(base64). -
http::data_path_client()— the single blessedreqwest::Clientbuilder 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), andblocking_data_path_client_builder(connect, total)is its blocking twin behind theblockingfeature, whichotelturns 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-buildersrefuses a client constructor anywhere else outside canopy-test-lib, unlesscompliance/client-builder-allowlist.tomlgives the reason. A client built any other way must still state its ownconnect_timeoutand whole-requesttimeout:cargo xtask http-clients audit-timeoutsrefuses one that does not, a barereqwest::Client::new()included, and a per-readread_timeoutstands in for thetimeoutonly 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 beginninghttp::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 throughhttp::egressinstead. -
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 directory0700(narrowing a looser existing one), stages the contents in a fresh0600sibling (O_EXCL, so no planted file or link is followed), fsyncs it and renames it overpath; 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 aLeftover, returned for the caller to report (inStored::leftovers, or inOwnerOnlyError::Storebeside 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 it0600; 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()readsCANOPY_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, andDefaulttrusts 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 leftmostX-Forwarded-Forhop 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’sX-Forwarded-Foris 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; everycanopy_apiservice’sApiServer::serveand the applicant portal share it. -
Modules shared by more than one service:
workdays(onlyload_from_jurisdiction_doc, which reads the pack's[jurisdiction.holidays]into acanopy_types::workdays::WorkdayCalendarand 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_textrenders an error with its source chain; the excerpt that bounds it iscanopy_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'ssnap.issuance.cycle_granularity(benefit_monthonly):next_cycle_startdates canopy-appeals' cessation of continued benefits andcycle_endcloses 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_secretread through aSecretProvider, andDevKeyFilesis the.keys/fallback, which onlyfrom_process_envin aCANOPY_ENV=developmentprocess opens. The rules and thesecret-loadsgate: 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— thedefine_id!macro generates typed newtype UUID wrappers (PersonId,HouseholdId,ApplicationId, …) that prevent compile-time ID mixing; all UUID v7 (Uuid::now_v7()).canopy_types::Idis the rawUuidalias. -
identity— who performed an act (#1008, ADR-043 Amendment 1).OidcSubjectis an OIDCsub: opaque, 1–255 ASCII bytes with no control character, compared byte for byte and never trimmed, case-folded or parsed as a UUID.ServicePrincipalis a service’s name (a system caller’s client id) under the same rule. Both are built only through validating constructors (TryFrom<String>/FromStr, serdetry_from), and their PostgresDecode(under thesqlxfeature) re-validates, so a malformed stored value is a decode error.ActorisHuman { subject } | Service { service }, internally tagged onactor_typeon the wire; in Postgres it is a<col>+<col>_servicecolumn pair, read withActor::from_columns(both set is refused, neither is no actor) or, for a mandatory act,Actor::from_mandatory_columns(both or neither is aMandatoryActorColumnsError, which a reader may map to its own error naming its column or row; #2341), and bound withActor::columns(). Deliberately separate fromid: 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 (notnum_days() / 365). -
month_period::MonthPeriod— an inclusive span of whole calendar months,first_monthtolast_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 beforeon, under chrono’s month clamp (a 29 February birth reaches 12 months on 28 February);Nonebefore 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/ParamsDigest64-hex newtypes, the half-openEffectivePeriod,PolicyTarget,ParamsProvenance, and the request-sidePolicyTargetRefa dry-run caller names a target policy with; ADR-028 Amendment 6);trigger::DeterminationTriggeris the ADR-002 Amendment 1 provenance classifier. -
text::bounded_excerpt(body)— truncates upstream-derived text totext::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 anApiErroror 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::newtakes the holiday dates and coverage years as given; a service builds one from a pack throughcanopy_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, andhex(panic-free lowercase hex encoding). -
The
sqlxfeature — off by default. It addssqlx::Typeto everydefine_id!type and the PostgresType/Encode/Decodeimpls toOidcSubjectandServicePrincipal, 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 normalsqlxdependency declarescanopy-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'ssqlxfeature follows the same rule, and canopy-common itself, whose sqlx is optional, reaches this feature through its own. The xtask testevery_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_optionalkeeps canopy-common's dependency optional, andcargo xtask feature-buildscompiles 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_VOCABULARYis every role name canopy authorizes on, sorted: the union of the bar constants, the inline role literals the routes' admissions name, and canopy-web’sWorkerRolenames; 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 minusquality_control, which every write route takes;CITATION_RENDER_ROLES;DETERMINATION_OPERATOR_ROLES, the writers abovecaseworker, which canopy-eligibility’s quarantine routes admit, #2061; and the delegated routes'CASE_READER_ROLES,WORKER_READER_ROLES,AUDIT_READER_ROLESandSUPERVISOR_VIEW_ROLES, #2801) are the slicesAdmission::user_rolesand 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 fromenv_keythrough the auditedSecretProvider, else, in development only,.keys/portal-applicant-public.pemplus a stagedportal-applicant-public-next.pem; each concatenated PEM block registers under its own derived kid (#1569).ApplicantVerifierAdapteris the productionApplicantClaimVerifier, over canopy-signing’s claim verification. -
CanopyRequestBuilderExt— the outboundreqwest::RequestBuilderdecoratorwith_finalize_step(Option<FinalizeStepHeaders>); thex-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_HEADERis the retiredX-Canopy-Actor, which a receiver refuses with 400actor_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:ConfidentialClientis a client that authenticates withprivate_key_jwt, its 15 variantscanopy-web,canopy-portaland the 13 services that call another service;NativeClientis a public client bound by DPoP, its one variantcanopy-cli;ClientisConfidential()orNative(), andClient::all()yields all 16 identities;CanopyServiceis one of the 16 services that serve another canopy caller. Each is serialized as its id (as_str), and itsFromStrand 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 (Nonefor the two portals);CanopyService::audience()is its audience URI andCanopyService::from_audiencethe exact inverse.purposes()is the compiled purpose registry: eachSystemPurpose { name, client, audience, scopes }is named<client-id>/<audience-service>, andpurpose_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’sTarget::op_scopes, which a canopy-portal test holds equal. Every other confidential client has one purpose for each of itsSystemorBothedges (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;jtia UUID,scopespace-separated, split byscopes()) andClientAssertionClaims(iss sub aud exp iat jti) name their client as aConfidentialClient, so a native client’s id parses in neither, and aredeny_unknown_fields, so a payload carrying a user claim (sid,roles,programs,act,auth_time) or any other unknown claim does not deserialize;audis a single string. Validating them is the issuer’s and the receivers' job. The call graph (Amendment 4, #2643):edges()yields oneEdge { caller: Client, target: CanopyService, kind: EdgeKind }per pair a compiled client calls, eachDelegation,SystemorBoth;edge(caller, target)is a pair’s kind,may_delegatereads the delegation edges (Delegation,Both),may_hold_system_token(ConfidentialClient, target)the pairs a purpose may name (System,Both), anddelegators_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.EdgeKindis writtendelegation,systemorboth(as_str,Display);FromStrrefuses any other string withUnknownEdgeKind, which does not echo it. The delegation token layout (#2645), which canopy-identity mints andidentity_token'svalidate_delegationvalidates:DelegationTokenClaimsisiss sub aud exp iat nbf jti client_id sid roles programs act auth_timeunder the headerACCESS_TOKEN_TYP(at+jwt, which a system token carries too),deny_unknown_fields, sopurpose,scope,cnfor any other claim refuses the payload and neither access token parses as the other.subis aSubjectIdandsidaSessionId, each a UUID of any version;mint()makes a new one as a UUID v7 (#2712),Displaywrites the hyphenated lowercase UUID, andFromStrreads any formUuid::try_parsedoes, refusing anything else asInvalidSubjectIdorInvalidSessionId, which quote nothing.rolesis aRoleSetofRoleNames (^[a-z_]{1,64}$; the issuer holds the vocabulary), non-empty, sorted in byte order and duplicate-free;programsis aProgramSetofcanopy_reference::Program, non-empty, duplicate-free and sorted by wire id (caps,chip,medicaid,snap,tanf,wic).actis anActorChain, current actor first, which serializes as RFC 8693’s nested{"sub": …, "act": {…}}; the innermost object has noactmember, and an explicit"act": nullrefuses. 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::newreturnsActorChainError,RoleSetandProgramSet::try_fromreturnClaimSetError,RoleName::from_strreturnsInvalidRoleName): the chain’s innermost actor opens sessions, every other actor is a confidential client that runs as a service, no actor repeats and at mostMAX_ACT_DEPTHactors stand;client_idis the current actor andnbfequalsiat, which are not stored but derived (client_id(),nbf()), so no value disagrees with them. For the delegation mint (#2720):RoleSet::intersectandProgramSet::intersectanswer the values both sets hold in this set’s wire order,Nonewhen they share none, andis_subsetwhether another set holds every value;ActorChain::extended_by(actor)is the chain an onward mint givesactor, every actor moving one place inward, refused throughActorChainError, innew's order, when the chain would passMAX_ACT_DEPTH(TooLong),actorruns as no service (ActorNotAService) oractoralready stands in the chain (ActorRepeats), so a full chain refuses even a repeat as too long. The lifetime (1 toDELEGATION_TOKEN_MAX_LIFETIME_SECS, 300 s),iss,audand 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, andROLE_VOCABULARYholdssecurity_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 exactlyalg,kidand an optionaltyp(each a string, each once;crit,b64,jwk,jku,x5c,x5uandctyare refused, so no JOSE extension is honoured), analgother thanES256, akidthat is not aKid, and a signature that is not a 64-byter‖spair (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 optionalapplication/prefix, case-insensitive).identity_policyholds the client assertion’sCLIENT_ASSERTION_TYP(client-authentication+jwt) andCLIENT_ASSERTION_MAX_LIFETIME_SECS(60). -
jws_corpus(featuretest-helpers, #2553) — the evil-JWS corpus every canopy-identity token parser is held to. A target describes the token it accepts (CorpusInputs: the trustedKeySigner,typ, payload and size cap), and eachEvilCase(alg: none, HS256 confusion, an embeddedjwk, a signed unknowncrit, a signedb64: 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-buildscovers 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 compiledCanopyService, its audience the receiver’s audience URI.validate_system(token, request_start) → Result<SystemTokenClaims, IdentityTokenError>,validate_delegation(…) → Result<VerifiedDelegation, IdentityTokenError>andvalidate(…) → 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); atypnamingat+jwt(at+jwtorapplication/at+jwt, case-insensitive, RFC 9068 §4); akidthe key source holds and an ES256 signature under it; exactly one layout,SystemTokenClaimswithsub=client_idorDelegationTokenClaims, any other claim refusing asRejection::Claims;issandaudexact;exp − iatof 1 to 600 s for a system token and 1 to 300 s for a delegation token,iatandnbfat most 60 s past the request’s start, and the request beforeexp+ 60 s; and the last hop: a delegation token’s current actor has a delegation edge to the receiver (may_delegate, elseRejection::LastHop), and a system token’s client a system edge (may_hold_system_token, elseRejection::SystemEdge), so no purpose could have named a refused pair.VerifiedDelegationholds theclaims()and the token as presented, kept for the onward delegation sender; the token zeroizes, itsDebugprints only the token’s length, and it isClonefor axum’sExtension.VerifiedBearerisSystem(SystemTokenClaims)orDelegation(VerifiedDelegation).IdentityTokenErrorseparatesRejected(Rejection)fromKeysUnavailable, which fails closed and judges no token.IdentityKeySource([async_trait],key(kid, request_start) → Result<Option<VerifyingKey>, KeysUnavailable>,VerifyingKeyre-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 unknownkid, 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 itsAge, and past 720 s (STALE_AFTER) at the request’s start the source answersKeysUnavailable, 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;truewhen 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 isidentity::key_source::MemoKeySourceover 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.Principalis the caller a validated bearer names, builtFrom<VerifiedBearer>:User(UserPrincipal)from a delegation token orSystem(SystemPrincipal)from a system token, the portal among the latter.UserPrincipalholds theVerifiedDelegation, the token kept for the onward sender (delegation()), and answerssubject(),session(),roles(),programs(),actor_chain(),current_actor(),auth_time(),jti(),exp()andoidc_subject()(the canopy subject as anOidcSubject);SystemPrincipalanswersclient(),purpose(),scopes(),has_scope(scope)(never for an empty scope),jti()andexp().Principal::user()andsystem()areOptions;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>isActor::Humannamed by the canopy subject’s hyphenated form (equal, through the seed links, to the subjects rows already hold) orActor::Servicenamed by the client id;attribution_sub() → Stringis the same name as a string, for records that store one (a system token’ssubis its client id).Admissionis a route’s admission:const, never empty, built from arms — startsAdmission::system(),system_from(&[ConfidentialClient]),portal(scope),user_roles(roles)anduser_roles_via(&[Client], roles), andand_system(),and_portal(scope),and_user_roles(roles)andand_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 whosecodeis the firstReceiverDenialin 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_onlywhere a user arm exists, elseportal_only_route) or off its list (service_not_allowlisted); a user without a user arm (system_caller_requiredwhere a system arm exists, elseportal_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_householdandrequire_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 publicSystemArm—None,AnyorFrom(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 aDelegatedRoute { 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 incanopy_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 withoutv1, braces and separators, camelCase split, uppercase) and recorded as the row’sname; its tests hold every row’snameto 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) isidentity_receiver_middleware, installed with axum’sfrom_fn_with_stateand anIdentityReceiverstate:IdentityReceiver::new(validator)over anyIdentityKeySource(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 oneAuthorizationheader whose scheme isBearer, compared case-insensitively, followed by one RFC 6750b64token, else 401token_missingwith the challengeBearer; carries noX-Canopy-Actor, else 400actor_header_retired, before any key is looked up; holds a token the validator accepts at the wall clock withinRECEIVER_KEY_BUDGET(2 s), else 401token_rejectedwithBearer error="invalid_token", or 503keys_unavailablewhen no trustworthy key set answered in time; and carries anX-Canopy-Applicantclaim only from the portal, verified once, else 403applicant_claim_not_portal,applicant_claim_unverifiable(no verifier) orapplicant_claim_invalid(a refused or repeated claim). An admitted request gains thePrincipaland, from the portal, theApplicantOwnershipas 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 anHttpJwksKeySourceat 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) andADMIN_BODY_LIMIT(4096 bytes). The request bodies (ReasonBody,CreateSubjectBody,LinkBody, eachdeny_unknown_fields) keepStringfields, so the server answers each field’s own 400 code in its order; the lookup queryUpstreamPairignores 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, refusingMalformedorNil) andAdminKid::parse(an RFC 7638 thumbprint whose last character carries zero padding bits); each refusal’sDisplayis the server’s message, andAdminReason's andCheckedPair'sDebugprint no reason and no upstream subject. The answers carry ids as their newtypes (SubjectId,SessionId, andActionIdfor an action row), absent options asnulland times as RFC 3339:SubjectRef,SubjectViewwithLinkViewandSessionView(itsopenertext),Recorded { action_id, changed },KeyListofKeyView,ClientListofClientView(itsclienttext, itskindaClientKind,ClientKind::of(Client)).AdminProblem::read(body)is the problem body’scode, 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 underadmin_url(), one method per route over the request’sWebOutbound(lookup_subject(&CheckedPair),subject(SubjectId),create_subject(NewSubjectId, &AdminReason),suspend,lift,revoke_session(SessionId, …),link(&CheckedPair, SubjectId, …),keys(),revoke_key(&AdminKid, …),clients(),disable_clientandenable_client(Client, …)), its bearer a delegation for canopy-security on canopy-web’sBothedge, taking only checked inputs. A write whose JSON is overADMIN_BODY_LIMITisBodyTooLargebefore a bearer is had or anything sent. Each attempt is bounded by the lesser ofADMIN_CALL_TIMEOUT(6 s: the server’s 5 s budget and a second of transport) and what remains of the request. A 401 whoseWWW-Authenticatechallenge or problem code isinsufficient_user_authentication(RFC 9470) isStepUpRequired { max_age }, the challenge’smax_ageelse 600 s, never retried; the guard’s refusal of the bearer (refuses_the_bearer: a 401 whoseBearerchallenge names no error orinvalid_token) callsrejected(Security)and retries once with a new bearer, unless less thanRETRY_FLOOR(1 s) remains, and a 401 under noBearerchallenge is final at once, its token kept; a final 401 isSessionEnded(session_ended,session_refused),ClientDisabledorUnauthorized(code). Otherwise 403Forbidden, 400Invalid(code), 404NotFound(code), 409Conflict, 413TooLarge, 429Limited(never retried), 503Unavailable(code), any other statusStatus(u16),Timeout,Transport(its URL dropped, as the lookup’s carries an upstream subject),Malformedfor a success that is not its view, andSend(WebSendError); a problem body that is not JSON gives no code.step_up_options()asks formax_ageSTEP_UP_MAX_AGE(300 s) withoutprompt=login: with the relying party’s 60 s leeway a stepped-up session is at most 360 s old, which aconstassertion holds under the server’s 600 s, leaving 240 s of administration; the session it replaces ends throughWebSessionEngine::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 fromServiceSettings' requiredidentity_issuerandidentity_internal_url.IdentitySettings::new(issuer, internal_url, development)holds each URL toidentity_url's rules, a defect naming its setting (ISSUER_SETTING,identity_issuer;INTERNAL_URL_SETTING,identity_internal_url, theServiceSettingsfields' names).issuer()is the identifier exactly as written andissuer_url()the same as a URL, a client assertion’saud;jwks_uri(),token_endpoint(),revocation_endpoint(),device_verification_endpoint()(Amendment 21; #2836) andadmin_url()(Amendment 20; #2831) are thejwks,token,revoke,device_verificationandadminendpoints under the internal URL, the last atADMIN_PATH.device_authorization_endpoint()is thedevice_authorizationendpoint under the internal URL, andmetadata_url()the issuer’s RFC 8414 metadata atMETADATA_PATHon 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)andfrom_secrets(&IdentitySettings, ConfidentialClient, &dyn SecretProvider, IdentityHttpClient)build a service’s one sender: its key, and oneSystemTokenSourceand oneDelegationTokenSourceover it.from_secretsreads the key through the provider alone underclient_key_secret(client)(CANOPY_<SERVICE>__IDENTITY_CLIENT_PRIVATE_KEY);over_httpsigns with a signer its caller built. A client that runs as no service (canopy-web, canopy-portal) isSenderError::NotAService, before any key is read, and a key that cannot be loadedSenderError::Key.calls(Origin)opens one request’sOutboundwith its delegation cache;Origin::of(&Principal)isUser(&VerifiedDelegation)for a user andSystemfor a system caller, the portal included, and a detached or background task, a durable retry or boot usesOrigin::System.Outbound::bearer(target)takes the token from the compiled edge and the origin: no edge isSendError::NoEdge; aSystemedge takes a system token whatever the origin; aDelegationedge delegates the user onward, never narrowed, and refuses a system origin (SystemOrigin); aBothedge goes by origin.system_bearer(target)asks for a system token on aSystemorBothedge (NoSystemEdgeon a delegation-only one). A local refusal sends nothing, and system tokens are asked for with noscope. Each acquisition is bounded bySENDER_BUDGET(6.5 s,DELEGATION_BUDGETplus a second), elseSendError::Timeout; the other errors wrapSystemTokenErrorandDelegationError.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. ABeareris read throughexpose_for_call(),is_delegation()names its kind and itsDebugprints nothing more;owned()is anOwnedBearer, which zeroizes and has noClone,DebugorDisplay, 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’sWebOutbound.WebSender::over_http(engine, &IdentitySettings, Arc<dyn KeySigner>, IdentityHttpClient)andfrom_secrets(engine, &IdentitySettings, &dyn SecretProvider, IdentityHttpClient)(the key underclient_key_secret(ConfidentialClient::Web),CANOPY_WEB__IDENTITY_CLIENT_PRIVATE_KEY, no file fallback) build canopy-web’s one sender over the session engine: a cheapCloneholding aDelegationTokenSourceand aSystemTokenSourceover canopy-web’s key.calls(key, LiveSession, deadline)opens one request’sWebOutboundover the record atkey, which owns what it holds (Send + Sync + 'static, so canopy-web can share it through anArc).bearer(target)takes the bearer from canopy-web’s compiled edge: aDelegationorBothedge mints from the session, never narrowed (canopy-web’s narrowing would cap every onward hop); aSystemedge takes a system token; no edge isWebSendError::NoEdgeand sends nothing.system_bearer(target), on the outbound for an in-request system call and on the sender for a detached task, works onSystemandBothedges 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, answerSharedFailureinstead 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, zeroizingOwnedBearer, and each mint attempt is bounded by the lesser ofSENDER_BUDGETand what remains of the request’s deadline (Timeout), a stale call’s renewal by what remains less one second.WebSendErrorisNoEdge,NoSystemEdge,Timeout,SharedFailure,System,Delegation,SessionEnded,RenewalPendingorStore; none carries a token or credential. The sender never fails open. For its renewal (#2827), a mint refusedsession_stalerenews the session once per request, throughWebSessionEngine::maintain_nowat 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 secondsession_stalebeingDelegation. A renewal that does not advancefresh_until, or too little time to try, isRenewalPendingwith no retry.session_endedandsubject_suspendedend the record throughend_refusedand answerSessionEnded; 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 asyncrejected(target)) is where a call’s bearer comes from: a service’sIdentitySenderfor system-origin work, a request’sRequestOutboundorSharedOutbound, canopy-web’sWebOutbound, thePortalSenderand canopy-cli’sDeviceClient.request_outbound_middleware, installed inside the receiver layer with the service’s sender, inserts each request’sRequestOutbound(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 aPrincipalfails 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 whoseBearerchallenge names no error orinvalid_token), drops the target’s tokens and sends once more whileRETRY_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.CallErrorcarries no token and no URL.FixedBearer(featuretest-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)andfrom_secrets(&IdentitySettings, &dyn SecretProvider, IdentityHttpClient)(the key underclient_key_secret(ConfidentialClient::Portal),CANOPY_PORTAL__IDENTITY_CLIENT_PRIVATE_KEY, no file fallback; a missing key isSenderError::Key) build the portal’s one sender: aSystemTokenSourceover its key.bearer(target) → Result<OwnedBearer, SendError>asks for the portal’s system token fortarget, with noscope, so it carries every scope of its purpose, withinSENDER_BUDGET(SendError::Timeout), as an owned, zeroizing copy; a target off the portal’s nine compiledSystemedges isSendError::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’sPgWebSessionStore. AWebSessionRecordis a worker’s web session as canopy-web keeps it: theFederatedSession, theUpstreamBinding(the profile’sissuerandclient_idas written at sign-in), the optionalUpstreamRefreshToken, the latest upstream id_token (for logout’s hint) andmaintain_at; its fields are public so a store restores it from its own columns, and it has noDebug,CloneorSerialize.WebSessionStore([async_trait],Send + Sync + 'static, its ownKey) is the contract canopy-web’s refresh claim (#2224) states, each call bounded by itswithinand answeringStoreFault::{Timeout, Unavailable}:view(aSessionRow:RecordVersion,ClaimState::{Free, Live, Lapsed}, and the record,Nonefor 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, answeringClaimed::{Record, Undecodable, Nothing});commit(only under the claim, live or lapsed, stepping the version and freeing the row);release(only a live claim);end_claimedandend_lapsed(only under the claim, the latter once lapsed, asRefreshLost);end(key, reason)(unconditional, answering the record it ended in the same step); andend_reason. Every write steps the version, an ended key is never live again, and a lapsed claim is never cleared.WebSessionEndReasonspells the engine’ssigned_out,expired,identity_refused,upstream_ended,upstream_changedandrefresh_lost, and canopy-web’s ownsuperseded,idleandoperator(as_str,parse). Featuretest-helpersaddsidentity_web_session::contract::check(store, seed, corrupt) → Result<(), ContractViolation>, the contract as a suite any store runs (canopy-web’sPgWebSessionStoreruns it, and itsPgNativeStoreruns it andcheck_due), withsample_record(now), andmemory::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 cheapClonethat each leader it spawns shares;store()andrelying_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 ofSTORE_OP_TIMEOUT(2 s) and what remains: a session bound to another upstream endsUpstreamChangedbefore anything is presented; a lapsed claim ends itRefreshLost; a fresh one (fresh forSERVE_MARGIN, 15 s, more) is served, and when due a detached leader maintains it; a stale one with no refresh token or withinSERVE_MARGINof its end endsExpired; a stale, due one is led, or waited on while another leader’s claim is live; otherwise, or past the deadline,Unserved::Pending.LiveSessionholds the version and theFederatedSession, never an upstream token;UnservedisNoSession,Ended(WebSessionEndReason),PendingorStore(StoreFault). A leader claims withCLAIM_LEASE(60 s, outlasting every store write it makes), refreshes upstream withinUPSTREAM_TOKEN_TIMEOUT, and renews by the profile’srenewal()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 whenfresh_untilis withinFRESHNESS_LEAD(120 s); canopy-identity’ssession_ended,upstream_refused, projection andsubject_suspendedrefusals end the sessionIdentityRefused, and an upstream refusal ends itUpstreamEnded; anything else keeps the session, retried afterMAINTENANCE_RETRY(30 s). The next maintenance is the earliest of the grant’srefresh_due(),fresh_untillessFRESHNESS_LEADandVALIDATION_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 aSignedOutorOperatorend, and a row found live at the claimed version without the claim after a presented token endsRefreshLost. Every end a request or leader writes and sees acknowledged, butIdentityRefused, revokes canopy-identity’s session in a detached task within 2 s; sign-out revokes it inline, andend_refused(below) revokes only for a suspended subject.UpstreamRelyingParty::renewal()andbinding()(the profile’sissuerandclient_idas 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;SignInErrorisRelyingParty(RelyingPartyError)orFederation(FederationError)(AuthTimeTooOldis the cue forprompt=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,UpstreamSignOutbeingEndSession(Url),Revoked,RevocationFailedorPromptLogin(every variant butEndSessionleaving canopy-web to sendprompt=loginnext); itsDebugnever 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 versionseenwhatever the local freshness, since canopy-identity found the session stale: single-flight through the claim at the version, served ascurrentwould once another leader moved pastseen, 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 recordIdentityRefusedafter canopy-identity refused a mint, revoking canopy-identity’s session only forSubjectSuspended, 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, andNativeSessionsholds one of kind native, whose renewals present the native-revalidation type both ways and scheduleNATIVE_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,UpstreamEndedincluded, 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 asSupersededand 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) addsdue(now, limit, within)for the native sweep: the live rows whosemaintain_atis at or beforenow, earliest first, at mostlimit, whatever their claim and whether or not their rows still decode; a web store needs none of it. The memory store implements it, and featuretest-helpersaddscontract::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_PATHandMETADATA_PATH(/.well-known/oauth-authorization-server/identity, RFC 8414 §3.1), andMAX_FORM_BYTES(64 KiB), the longest form body canopy-identity reads.identity_url(name, value, development)accepts an absolutehttpsURL (httptoo under development) with no userinfo, query or fragment, whose path is exactlyIDENTITY_PATH, written in canonical form so its string is exactlyvalue; else the firstIdentityUrlError(Unparseable,Userinfo,Scheme,Query,Fragment,Path,NotCanonical), each naming the setting; none quotes the value, andNotCanonicalgives only its canonical spelling, which holds no userinfo.identity_endpoint(name, base, segment)builds an endpoint under a mount by path segment. canopy-security’sIssuerConfigconverts each defect one for one into its ownIssuerConfigError. -
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.UpstreamProfileis the deployment’s one upstream profile,<config root>/identity-upstream.yaml(UPSTREAM_PROFILE_FILE, Configuration reference).UpstreamProfile::load(config_root, development)andload_from(path, development)returnResult<Option<UpstreamProfile>, UpstreamProfileError>,Nonewhen 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 byprofile(kanidm,keycloak,zitadeloroidc-generic; ADR-049 Amendment 26), each variant refusing a field its file may not state, so that every refusal names its field:UpstreamProfileErrorisRead,NotAMap,UnknownProfile,Missing,PresetField(a vendor file stating a preset field),UnknownFieldorInvalid { field, fault: UpstreamFieldFault }, and never quotes a value. The resolved profile, its vendor’s presets filled in (azitadelprofile’sZitadelIdstoo, its project and organisation), holdskind()(ProfileKind);issuer()(UpstreamIssuer:as_str()exactly as written, the stringissis compared with, andurl()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 aClient);algorithms()(UpstreamAlgorithms, a non-empty set ofUpstreamAlgorithm:ES256,ES384,RS256,PS256andEdDSA, each binding oneUpstreamKeyTypethroughkey_type(): P-256, P-384, RSA of at leastMIN_RSA_MODULUS_BITS(2048) bits, Ed25519);claims_from()(ClaimsFrom);refresh()(RefreshRenewal, whoserenews(claims_from)says whether it reads the claims from that source), the two naming one source (id_tokenwithreissues_id_token,userinfowithuserinfo) or the file is refused asInvalid { field: "refresh", fault: MixedSources };client_auth_method()(UpstreamClientAuth:client_secret_basicorclient_secret_post);claims()(ClaimPointers, theroles,programsandusernameJsonPointers: RFC 6901 pointers, validated at parse,JsonPointerErrornaming a pointer that is not rooted or holds a bad~escape; andshape(), the roles' and programs'ClaimShape:Array, orObjectKeys { organization }, which only thezitadelpreset sets and no file can state); and the optionaljwks_uri()anduserinfo_endpoint()(url::Url: https unless development, no userinfo or fragment, a query allowed) andtls_trust_anchors()(TrustAnchorFile, one bare file name,resolve_in(config_root)).TlsTrustAnchors::load(file, config_root)reads the bundle aTrustAnchorFilenames, at mostMAX_TLS_BUNDLE_BYTES(1 MiB), with the PEM parser of rustls' pki-types, and refuses it (TlsTrustAnchorsError:Read,TooLarge, orInvalid { 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-----BEGINmarker anywhere that yielded no section (UnreadBlock: the parser silently skips a label it does not know, such asENCRYPTED PRIVATE KEYorOPENSSH 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 givecount(),iter()overTlsTrustAnchor(der(),fingerprint()) andfingerprints()(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,httpsonly 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. Featuretest-helpersaddsresolving(anchors, development, host, address), the same client resolving one host to a fixed address (the Kanidm lane).get(url, headers)answers anUpstreamResponseonce the status and headers arrive (status(),headers()); the caller judges the status, then readsbody(limit)throughread_capped_body.UpstreamRequestErrorisUrlRefused,Connect,TlsorConnectTimeout(no request sent),TimeoutorConnectionLost(the upstream may have received it), orTooLarge, and carries neither the URL nor any of the response;UpstreamClientErroris a TLS backend that could not be built.UpstreamKeySource::new(profile, http, development)(orwith_clock(…, clock), anIdentityClock) holds the upstream’s discovery and keys, fetched on first use, never at boot, under the rulesidentity_token'sHttpJwksKeySourcefollows, through the crate-private key cache both instantiate: refreshed once 300 s old, an unknownkidrefetching at most once per 30 s, concurrent lookups sharing one fetch, and a set 720 s stale at the request’s start answeringUpstreamKeysUnavailable, 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 sendingCache-Control: no-cacheand each body capped atUPSTREAM_DOCUMENT_CAP(64 KiB); anything but a 200 fails the fetch. Discovery must be a JSON object whoseissueris a string equal to the profile’s exactly and whosejwks_urianduserinfo_endpointare each absent or a string (nullis malformed, not absent), none of the three repeated; the profile’sjwks_urianduserinfo_endpointwin over discovery’s, and a discovered one must pass the endpoint rule and share the issuer’s origin;jwks_uriis 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 holdingkeysonce, 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 (nullincluded) or appears twice, when itsuseis present and notsig, when it has nokid, or when its key type fits none of the profile’s algorithms, a declaredalgbinding it to that one alone, which must be the profile’s; two kept keys under onekidrefuse the set.key(kid, request_start)answers theUpstreamKeyunder anUpstreamKid(opaque, compared exactly):decoding_key()(jsonwebtoken’sDecodingKey),permits(alg)andalgorithms().userinfo_endpoint(request_start)answers the profile’s or discovery’s userinfo endpoint, read without a kid.UpstreamIdTokenValidator::new(profile)andvalidate(token, keys, now) → Result<VerifiedUpstreamIdToken, UpstreamIdTokenError>verify an upstream id_token, withnowinjected (production passeschrono::Utc::now()) andkeysanUpstreamKeys([async_trait],key(kid, request_start)), whichUpstreamKeySourceimplements. A header pre-check runs before any key is looked up: at mostMAX_UPSTREAM_ID_TOKEN_BYTES(16 KiB) and three segments; a canonical base64url header holdingalg,kid, an optionaltypand the ignoredx5tandx5t#S256, each a string and each once, and no other member (critincluded);algamong the profile’s; and atypnamingapplication/jwt(typ_names, soat+jwtrefuses). Thekid's key must permitalg; jsonwebtoken then checks the signature and judges no claim’s value (no claim required, itsexp,nbfandaudchecks 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 objectsub, or a non-empty array or objectexpornbf. The validator judges every claim itself:issbyte for byte;audexactly the client (the string, or an array of it alone, so another audience refuses whateverazpsays);azp, when present, the client;subanOidcSubject;exp,iatandauth_timepresent and every time claim aNumericDate(a finite JSON number truncated to whole seconds withini64);expafternow− 60 s,nbfno later thannow+ 60 s,iatat most 300 s old and 60 s ahead,auth_timeno later thaniat+ 60 s ornow+ 60 s; anoncea string, returned unjudged;amrandacrnever read.VerifiedUpstreamIdTokenholds theUpstreamAnchor(iss(),sub(),auth_time()as aNumericDate,nonce()),issued_at()(itsiat, aNumericDate) and the wholepayload(), which itsDebugomits; the anchor’sDebugprints only the lengths of the subject and the nonce.UpstreamIdTokenErrorseparatesRefused(UpstreamIdTokenRefusal), naming the broken rule (with aTimeClaimfor a missing or malformed time claim) and none of the token, fromKeysUnavailable.UpstreamUserinfo::new(profile, http)andfetch(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 aZeroizing<String>,expected_subanOidcSubject,keysthe same profile’sUpstreamKeySourceandnowinjected. The endpoint is the profile’suserinfo_endpoint, called without consulting discovery, else the one discovery advertises. The request is one GET withAccept: application/jsonandAuthorization: Bearer <token>, its value marked sensitive so reqwest and hyper never print it; a token longer thanMAX_UPSTREAM_ACCESS_TOKEN_BYTES(8 KiB) or not an RFC 6750b64tokenis never sent, refused before the endpoint is looked up. Only a 200 is read, with exactly oneContent-Typewhose essence isapplication/json(any case, parameters such as; charset=utf-8tolerated, so a signedapplication/jwtanswer refuses), a body of at mostUPSTREAM_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 asubthat is a string equal toexpected_subbyte for byte.UpstreamUserinfoClaimsholds every claim answered (claims(),into_claims()), which itsDebugomits.UpstreamUserinfoErroris the userinfo call’s three outcomes, none carrying the token, nor anything of the answer but its status:Unavailable(UpstreamUserinfoUnavailable)(Requestfor aConnect,Tls,ConnectTimeout,TimeoutorConnectionLost, a body cut short included;Statusfor 408, 425, 429 or a 5xx;Discoverywhen 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; andInvalid(UpstreamUserinfoInvalid)(AccessToken,NoEndpointwhen neither the profile nor discovery names one,UrlRefused,Statusfor 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: aProjectionAnchor(the issuer, subject and authentication time, builtFrom<&UpstreamAnchor>, which only the validator builds, so the validator stays the one route from token bytes to an anchor, orFrom<&StoredAnchor>, a caller contract the type cannot enforce:StoredAnchor::newchecks 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’sclaims_from()names, the verified id_token’spayload()or userinfo’sclaims(), read through the profile’sClaimPointers. Roles are the names at the roles pointer, which must be an array of strings (underObjectKeys, an object, whose keys count only when their value is an object naming the organisation, and whose counted keys are the names), thatROLE_VOCABULARYholds, a name withSERVICE_ROLE_PREFIXnever granting and any other name ignored; programs are thecanopy_reference::Programwire ids at the programs pointer (chipandmedicaiddistinct; underObjectKeys, the counted keys' remainders afterPROGRAM_KEY_PREFIX,program_); each list is sorted and deduplicated intoidentity_policy'sRoleSetandProgramSet. The username at its pointer is a string of 1 toMAX_UPSTREAM_USERNAME_BYTES(256) bytes with no control character (UnicodeCc; format characters such as the zero-width non-joiner are kept), held as anUpstreamUsername(as_str()), whoseDebugprints only its length.FederatedIdentityholdsiss()(the issuer exactly as written, a&str),sub()andauth_time()from the anchor,roles(),programs()andusername(); itsDebugprints only the lengths of the subject and the username.ProjectionRefusal, carrying nothing of the claims, is the first ofNoRole(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,nullincluded, or an element that is not a program’s wire id) andNoUsername(no_username: missing, not a string, or out of bounds);code()answers the code. A web session’s renewal judges againstStoredAnchor::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 upstreamsub(OidcSubject), the originalauth_time,nonce_digest(nonce)of the original nonce, and theiatandid_token_digest(token)of the latest id_token recorded, eachOption; the two digests are SHA-256 of the nonce’s bytes and of the compact id_token as presented, and itsDebugomits 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, thenClient).upstream::check_refreshed(&stored, &verified, presented_digest) → Result<Refreshed, RefreshMismatch>matches a refreshed id_token the validator accepted (so itsaudis exactly the profile’s client): itsiss,subandauth_timethe stored ones, its nonce the original’s or none (a nonce where the original had none mismatches); thenReplaywhen the presented digest is the latest recorded,Newerwhen itsiatis after the latest recorded, elseNotNewer, a session with no recordediatrefusing asNotNewer.RefreshMismatch(Issuer,Subject,AuthTime,Nonce,NotNewer) andBindingMismatchname the rule, never a value.RenewalVerdictisRevoke(RevokeReason)(UpstreamRefused,ProjectionRefused,UpstreamChanged),GraceorLapse(LapseReason)(Presentation,Deployment), its classifiers matching every variant by name:classify_userinfo(everyUnavailable,Discoveryincluded, isGrace;Refusedrevokes;Invalid::AccessTokenlapses as a presentation defect,NoEndpointandUrlRefusedas a deployment defect, every otherInvalidrevokes),classify_keys_unavailable()(Grace),classify_id_token(a refreshed id_token the validator refused lapses as a presentation defect;KeysUnavailableisclassify_keys_unavailable()'s grace),classify_projection(revokes),classify_mismatch(lapses as a presentation defect) andclassify_binding(revokes asUpstreamChanged). 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 holdsscopes()(UpstreamScopes: RFC 6749 scope tokens holdingopenid, each once;iter(),joined()space-separated; thekanidmpresetopenid profile, which akanidmfile may not state; anoidc-genericfile must state it) andendpoint_overrides()(UpstreamEndpointOverrides: the optionalauthorization,token,revocationandend_sessionURLs, held to the endpoint rule and not to the issuer’s origin).UpstreamKeySource::endpoints(request_start)answersUpstreamEndpoints, each member aResult<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, elseEndpointFault(Null,NotAString,Repeated,Refused(UpstreamFieldFault),CrossOrigin,Unreadable).UpstreamHttpClient::post_form(url, form, auth, timeout)posts a form-urlencoded body withAccept: application/json, authenticated byClientAuth::{Basic, Post}over aServiceCredentials(the client id and a zeroizing secret,Debugredacting it;basic_authorization()form-urlencodes both before the Basic encoding, RFC 6749 §2.3.1, andauthenticate(request)sets that header marked sensitive, the one encoder the operator tools send client credentials through, #2427) (ClientAuth::of(method, credentials)follows the profile’sclient_auth_method: Basic sendsServiceCredentials::authenticate's header, Post addsclient_idandclient_secret, throughServiceCredentials::client_secret_for_body(), to the form),timeoutreplacing 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 byUpstreamClientSecret::from_secrets(&dyn SecretProvider)underUPSTREAM_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’sscope, a fresh 256-bitstateandnonce, an S256code_challenge, the essentialauth_timeclaim on every request, andprompt=loginandmax_ageonly when asked) and thePendingAuthorization, whoseexpose_for_store()gives thestate,nonce, verifier andmax_age(StoredAuthorization) and whoserestore(state, nonce, verifier, max_age)refuses a malformed value (MalformedAuthorization).redeem(pending, returned_state, code, redirect_uri)refuses a foreignstatebefore any request (StateMismatch), then within oneUPSTREAM_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 itsnonce(NonceMissing,NonceMismatch) and, undermax_age, itsauth_time(AuthTimeTooOld); a non-200 isRefused { status, error: TokenEndpointError }. TheUpstreamGrantanswersid_token(),access_token(),take_refresh_token()(UpstreamRefreshToken,restoreandexpose_for_store, at mostMAX_REFRESH_TOKEN_BYTES),expires_in(),received_at()and theverified()id_token. The secret, the pending authorization, the refresh token and the grant’s tokens zeroize, and those four types have noDebug,Display,SerializeorClone; noRelyingPartyErrorcarries a token, code, secret,stateornonce. The session (#2816):refresh(&UpstreamRefreshToken, within)posts therefresh_tokengrant within one deadline, the lesser ofwithinandUPSTREAM_TOKEN_TIMEOUT, covering discovery, and sorts every outcome by Amendment 2 intoRefreshFailure::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) orRefreshFailure::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,Ambiguousotherwise); 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), andend_session(id_token_hint, post_logout_redirect_uri)answers the end-session URL withpost_logout_redirect_uri,client_idand the hint when given, orNonewhen no endpoint is advertised; each runs withinUPSTREAM_LOGOUT_TIMEOUT(2 s), discovery included.UpstreamGrant::refresh_due()isRefreshDue::At(receipt + lifetime − lead), the lead a quarter of the lifetime clamped toMIN_REFRESH_LEAD(30 s) andMAX_REFRESH_LEAD(300 s), always after receipt, orRefreshDue::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.SessionCredentialis a web session’s credential:mint()draws 32 bytes from the thread CSPRNG;parse(presented)accepts exactlySESSION_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) asMalformedSessionCredential, which quotes nothing;hash()is theSessionCredentialHash(as_bytes()), the SHA-256 of the 32 bytes and all the session store holds; andexpose_for_wire()is the one way to read it, aZeroizing<String>. The bytes zeroize on drop, and the type has noDebug,Display,SerializeorClone, 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 parametersUPSTREAM_ACCESS_TOKEN_PARAM,UPSTREAM_ID_TOKEN_PARAMandUPSTREAM_OUTCOME_PARAM, andNOT_PROCESSED,upstream_outcome's one value.CanopyRefusalis 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), anduser_code_invalid(a user code naming no device awaiting a decision, #2740) andapprover_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,Nonefor any other. A session’s terms are pure functions of injected times, every instant a whole-secondNumericDate(NumericDate::from_secondsbuilds one).SessionLimits::new(web_session_max_seconds, grace_seconds)holds the two settings, refusing a maximum outsideMIN_WEB_SESSION_MAX_SECONDS..=MAX_WEB_SESSION_MAX_SECONDS(1800 to 86400) or a grace outside 0..=MAX_SESSION_GRACE_SECONDS(3600) asSessionLimitsError(WebSessionMax,Grace), naming the setting and never its value; the defaults areDEFAULT_WEB_SESSION_MAX_SECONDS(43200) andDEFAULT_SESSION_GRACE_SECONDS(1800).with_native_session_max(seconds)sets the native session’s maximum, refusing one outsideMIN_NATIVE_SESSION_MAX_SECONDS..=MAX_NATIVE_SESSION_MAX_SECONDS(1800 to 86400) asNativeSessionMax; it isDEFAULT_NATIVE_SESSION_MAX_SECONDS(28800) until set, andsession_max_seconds(kind)reads aSessionKind's (Web,Native;as_str()the store’skind).SessionTerms::open(kind, auth_time, validated_at, now, &limits) → Result<SessionTerms, OpenRefusal>gives a new session’ssession_ends_at()(auth_timeplus the kind’s maximum) andfresh_until(), judgingnow(achrono::DateTime<Utc>, production passingUtc::now()) in whole seconds as the id_token validator does: an end underFRESHNESS_SECONDS(900) afternowisOpenRefusal::AuthTimeTooOld, and one past the lastNumericDateisEndOutOfRange.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) isTOKEN_EXCHANGE_FIRST_PHASE(2.5 s: the form, authentication and a renewal’s session read) plusTOKEN_EXCHANGE_UPSTREAM_BOUND(7.5 s:TOKEN_EXCHANGE_UPSTREAM_CALLS, 3, each bounded byUPSTREAM_REQUEST_TIMEOUT) plusTOKEN_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 whoseauth_timeis 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, behindcanopy login,canopy logoutand 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; noDebug,DisplayorClone) andcomplete_login(pending, resource) → NativeTokenfollow RFC 8628: an absent interval is 5 s, eachslow_downadds 5 s, a failed connection doubles the interval, a 429 waits the larger of itsRetry-Afterand 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 andresource, holds the 200 to the delegation client’s checks (Bearer, a lifetime within 300 s, the target asaud, canopy-cli as the current actor;AnswerDefectnames the first failed), and stores the successor before answering, even when the token fails a check;session_staleisStaleandsubject_suspendedSuspended, both keeping the credential, any otherinvalid_grantisLoginRequired, the session removed, and any other refusal isRefused, the session kept.logout()revokes as a public client and removes the session on a 200.NoEdge, andLoginRequiredfor a missing session or another issuer’s, send nothing. Each call is bounded byDEVICE_CALL_TIMEOUT(10 s), aconstassertion 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.NativeTokenzeroizes and offersexpose_for_call()andexpires_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::parserefuses an empty or overlong name,.,.., and any/,\, NUL or:).session.jsonholds 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 bycanopy_common::owner_only's durable rename.session.lockis never removed; its exclusive lock (stdFile::try_lock, retried forDEVICE_LOCK_BOUND, 15 s, thenStoreError::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, isStoreError::Malformedand 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 asStoreError::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 mostMAX_DPOP_PROOF_BYTES(2048) as three segments of canonical unpadded base64url, decoding all three, then refuses, first that holds: a header other than exactlytyp(DPOP_PROOF_TYP,dpop+jwt),alg(ES256) andjwk, each once, the key a JSON object of exactlyktyEC,crvP-256,xandyon the curve (so a privated, akid, any other member or an array spelling refuses); claims other than exactlyjti,htm,htuand an integeriat(ath,nonceandexprefuse); a signature that does not verify under the embedded key; anhtmother than the request’s method; anhtuother 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; aniatmore thanDPOP_IAT_TOLERANCE_SECONDS(60) fromnow; and ajtiempty, over 128 characters or holding a control character. Each refusal is aDpopRefusalwhosereason()is adpop_*code and which quotes nothing. The answer,VerifiedDpop, gives the key’s RFC 7638thumbprint()(the binding a native session holds), thejti()the caller spends once per thumbprint, andretain_until()(iatplusDPOP_JTI_RETENTION_SECONDS, 120).single_proof(values)takes a request’sDPOP_HEADERvalues, 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) andRefreshCredential(the native session’s rotating refresh credential) are opaque bearers spelled exactly asSessionCredentialis: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), andexpose_for_wire()is the one way to read one; each zeroizes on drop and has noDebug,Display,SerializeorClone.UserCodeis the code a worker types:mint()drawsUSER_CODE_SYMBOLS(8) symbols uniformly fromUSER_CODE_ALPHABET(the 20 consonantsBCDFGHJKLMNPQRSTVWXZ, about 34.6 bits, RFC 8628 §6.1);expose_for_display()showsXXXX-XXXX;parse(typed)reads it case-insensitively, ignoring-and spaces, and refuses anything else (another character, other than eight symbols, more than 32 bytes) asMalformedUserCode;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 parametersDEVICE_CODE_PARAM,USER_CODE_PARAM,WEB_SESSION_PARAM(the approving worker’s web-session credential, at code entry and, since Amendment 21, at approval) andREFRESH_TOKEN_PARAM; the flow’s times:DEVICE_CODE_LIFETIME_SECONDS(600) andDEVICE_POLL_INTERVAL_SECONDS(5); andNATIVE_BUDGET, a redemption’s or refresh’s budget, equal toDELEGATION_BUDGET. -
identity_native_session(ADR-049 §7; Amendment 21; #2837, #2838) — canopy-web’s native sessions, over canopy-web’sPgNativeStore.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)anddeny(…)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_age300 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, scheduledNATIVE_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 itsfresh_until.ApprovalErrorisRelyingParty,NoRefreshToken,Federation(AuthTimeTooOld,UserCodeInvalid,ApproverMismatch) orOtherPerson, 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 endedSignedOut, 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 aDueSessions, andsweep(budget) → Sweptis one pass of the sweep canopy-web runs everySWEEP_INTERVAL(30 s): within one absolute deadline, which bounds theduelisting too, it takes at mostSWEEP_BATCH(256) due rows, earliest first, and runs each row’s step (read, decide, act) in a spawned task holding one ofSWEEP_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’sRefreshLost), ends a row it cannot readRefreshLost(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,unfinishedcounting 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. Aconstassertion 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: POSTTOKEN_PATH,REVOKE_PATHandDEVICE_AUTHORIZATION_PATH, and GETJWKS_PATHandMETADATA_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 mostMAX_FORM_BYTES, read withinEDGE_BODY_READ_TIMEOUT, 2 s, into a buffer wiped once sent), itsContent-Type, everyDPoPvalue in order, and anX-Forwarded-Foroverwritten with the one client the shared client-IP rule resolves under canopy-web’s own trusted proxies; a body past the cap answers 400invalid_request, a slow one 503, and a request with noConnectInfo503, never forwarded under a made-up address. An answer keeps its status, its body (at most 64 KiB) and onlyContent-Type,Cache-Control,Pragma,Retry-AfterandAge; a call with no complete answer withinEDGE_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 503temporarily_unavailablewith no-store, so noLocationreaches 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’srequested_token_type, an onward request’ssubject_token_typeand the answer’sissued_token_type), and the parametersREQUESTED_ROLES_PARAMandREQUESTED_PROGRAMS_PARAM.Narrowingis what a request asks a token’s roles and programs to narrow to, each a canonical set orNonefor 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 asNarrowingError(NarrowedSet), naming the parameter and never a value;roles_param()andprograms_param()render the canonical valuesparsereads 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) asScopeRefusal::Exhaustedand a wider request asScopeRefusal::Widened, roles before programs.delegation_expiry(iat, subject_exp, session_end)is a token’sexpin NumericDate seconds, the least ofiat+ 300 s, the onward subject’sexpand the session’s end, refused underDELEGATION_MIN_LIFETIME(5 s) asExpiryRefusal::SessionEnding(judged first) orSubjectExpiring; an end afteriatwhose distance overflowsi64lasts. The mint’s budget, checked at compile time:DELEGATION_BUDGET(5.5 s, exported for senders) isTOKEN_EXCHANGE_FIRST_PHASE(2.5 s) plusDELEGATION_AUDIT_RESERVE(3 s), and the 5 s floor leaves a second beyond a whole-secondiatand 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)andmint()sign aprivate_key_jwtassertion:iss=sub= the client,audthe issuer identifier,exp=iat+ 60 s, a fresh v7jti,typ: client-authentication+jwt.SystemTokenSource::new(minter, token_endpoint: Url, IdentityHttpClient)andtoken(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) andexpires_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.SystemTokenErrorisMint,Transport,Body(the 64 KiB answer cap),Refused { status, error: TokenEndpointError }(the RFC 6749 / RFC 8707 code, typed; an unlisted code isUnrecognizedand not kept),MalformedorSharedFailure; 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 oneCanopyService, with a fresh assertion each time, byfrom_session(cache, &FederatedSession, target, &Narrowing)(canopy-web, from a web session, its token held to the session’ssub,sidand end: ADR-049 Amendment 19) ordelegate(cache, &VerifiedDelegation, target, &Narrowing)(a service, onward from the token it received), each returningResult<&DelegationToken, DelegationError>. Tokens are reused within one request: the caller makes aDelegationCacheper request withrequest_cache(), and only its source serves it (another source’s isForeignCache, 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 itsexpis more than 5 s ahead of the local clock. A 200 must carry the access-token type,Bearer, anexpires_inof 1 to 300 s, and a token whose payload, read unverified, names the target asaud, this client asclient_idand a lifetime of 1 to 300 s, and onward the subject token’ssubandsidand anexpno later than its own, a comparison of two issuer-clock times (AnswerDefectnames the first broken).DelegationErrorisForeignCache,Mint,Transport,Body,Refused { status, error, refusal: Option<CanopyRefusal> }orMalformed(AnswerDefect).DelegationTokenzeroizes and has noDebug,Display,SerializeorClone;expose_for_call()reads it,expires_at()itsexp.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), thenopen(id_token, upstream_access_token: Option<&str>),renew(&SessionCredential, SessionKind, RenewalEvidence)(IdToken,UpstreamAccessTokenorNotProcessed, which asks for grace; the kind’s token type presented both ways, a web session’s or a native session’s revalidation credential) andrevoke(&SessionCredential)(RFC 7009, a web or native session’s credential), each with a fresh assertion and each request bound byFEDERATION_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 }anddeny_device(&web, &UserCode)post code entry with the worker’s web-session credential, each withinDEVICE_VERIFICATION_TIMEOUT(6 s), andapprove(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 isSessionDefect::Device. The user code is sent as the worker reads it,XXXX-XXXX. An open or renewal returns aFederatedSession: the credential,sid,sub,auth_time,session_ends_at,fresh_until, the role and program sets and the username (anUpstreamUsername), after checking the answer’s types, the credential (a renewal must echo the one it presented), the times' order, canonical sets and the username (SessionDefectnames the first broken).FederationErroris classified from the answer’s status and body, since the endpoint answers every OAuth error buttemporarily_unavailablewith 400:Refused(CanopyRefusal)when the body names one,ClientRejectedforinvalid_client,InvalidRequest(TokenEndpointError)otherwise,Limited { retry_after }(429, the wait itsRetry-Afternames in seconds, as the device flow’s attempts budget names one),Unavailable(503) orStatus, besideMint,Transport,BodyandMalformed; 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:ApiServermounts/v1only 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;ServerOptionscarriesservice_name(theservicelabel of the idempotency lease-renewal pool’s gauges, #2541, and/version'sservice),config(the bootArc<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 noDefault./version's body iscanopy_config::VersionInfo,{ service, build, config: ConfigStamp, verified }(re-exported here), built once per router (VersionInfo::of(service, &snapshot);buildisCANOPY_BUILD_DESCRIBEat 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 orNone; theconfigarm (Extension<Arc<ConfigSnapshot>>, layered byApiServer::routerand canopy-web) gates readiness while any layer is stale (Deployment Guide › Health).public_routes(aRoutercarrying 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 passesRouter::new()except canopy-security, whose public route is the canopy-identity JWKS,GET /identity/jwks(#2500), and anoop-adapterscanopy-verification, whose public routes are its/internal/v1API-key adapter routes (#2510). -
outer_stack(router, &options)— the layersApiServer::routerputs 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 withCorsWildcardRefused(#2755: the identity capacity harness’s replicas). -
API_PREFIX(/v1) is the mountApiServer::routernests the protected routes under. A service registers each route asv1_route!(paths::X): the macro strips the prefix from thecanopy-contracts-*constant in aconstitem through theconst fnv1_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 misspelledCANOPY_<SVC>__*key fails boot by name. The two consts live in the service’ssrc/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 suppliedsqlx::migrate::Migratorover a dedicated migration connection (callers passsqlx::migrate!("./migrations")so the path resolves at their crate), then connect the app pool before theOutboxDrainerspawns, 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 theirCANOPY_ENCRYPTION_KEYread, so a KEK-premised migration never runs keyless and the read is logged through the redacting subscriber. -
run_to_completion(what, run)(#3202, #3242) — awaitsrunon its own task, so a handler's multi-step work outlives a caller that disconnects; a panic in the task answers 500 withwhatas its context. When a handler uses it: Framework patterns. -
determination_redaction::publish_determination_redacted(tx, publisher, source_service, &DeterminationRedacted { .. })— stages the ADR-036determination.redactedaudit event in the redact endpoint’s transaction for all five program services: the id, the steward’sauthor, the reason and timestamp, no plaintext, stamped with the publishing program (#1519). -
admin::AdminRoutes— the per-service/v1/admin/*family;.with_replay(pool, manager)enablesPOST /v1/admin/events/replaybehind the mounting service’s receiver, admitted byADMIN_HUMAN(Admission::user_roles(&["admin"]): a user holdingadminthrough any actor, no system arm). -
extract::required_extension(parts, name)— clones one boot-registered request extension out of the request parts for a service’sFromRequestPartsdependency bundle; absence is a wiring fault answered as a 500 (ApiError::Internal, logged undername), the status axum’s ownExtensionrejection 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 clamplimitthroughclamp_limit; the canopy-reporting universe drains request pages atMAX_LIMIT. A per-endpoint deviation carries a justification comment at the deviating site. -
retry— a bounded exponential-backoff retry layer for outboundreqwestcalls that coordinates with the server-side single-flight idempotency middleware: a retried request resends the sameIdempotency-Keyand body, so a completed request replays its stored response, one still in flight elsewhere returns a retryable503withRetry-After, and a reused key with a changed body returns409.RetryPolicy::default_http()pluswith_*setters (with_overall_timeoutis a hardtokio::time::timeoutwrap);RetryRequest::{get, head, delete, post_with_idempotency_key, idempotent_put, post_read}—try_newrefuses a keyless POST, and the only keyless POST descriptor is the caller-assertedpost_read, for an AIP-231:batchGetread, which canopy-web builds only behindInternalClient::post_read's:batchGetshape guard (#2680);retry_request(&policy, &request, make_req)builds a freshRequestBuilderper attempt and logstracing::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 sendingIdempotency-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 statesRetry-Afterin 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) — theCANOPY_CONFIG_SOURCElist, lowest precedence first, ofSource { name: LayerName, location: Location }.LocationisPath(dir)orGit(GitSource { url, reference: GitRef, verify: VerifyMode, pin: Option<CommitSha> });GitRefisBranchorTag(full_name()is itsrefs/heads/…orrefs/tags/…);VerifyModeisHead,TagorTagAndHead(default_for(&reference));CommitShais 40 lowercase hex, the&sha=pincanopy-config-fetch resolvewrites. Parsing refuses an empty list, a bad or repeatedLayerName([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’scanopy-config.toml(MANIFEST_FILE):schema(onlySCHEMA= 1 reads),layer(LayerKind::{Base, Jurisdiction, Deployment}), andjurisdiction, 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: apath:source read where it stands (stampedpath, loaded only when every source ispath:andallow_unverified), a git source from<policy_root>/<name>/currentresolved once to its<sha>/directory, itsstatus.json(SyncStatus,STATUS_FILE) read beside it.resolve(rel)returnsrelfrom the highest layer holding it (resolve_layeralso returns theLayer);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) andstamp().from_path_layers(&[(name, dir)])builds an unverified snapshot for tests, behind thetest-helpersfeature, so no production build can reach it (thecanopy-configfeature-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 },Displayasname@sha,name@sha.ConfigShais 40 lowercase hex or the literalpath. -
VersionInfo::of(service, &snapshot)—GET /version's body,{ service, build, config, verified }, which every server mounts: the canopy-api services throughcanopy_api::version_route, canopy-web on its own router, the portal beside/healthz.version::BUILDisCANOPY_BUILD_DESCRIBEat 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), andCURRENT(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— wrapssqlx::PgPool:DbPool::connect_with(url, opts);db.inner()returns&PgPool;db.register_metrics(service, pool, max)registers thecanopy_db_pool_{size,idle,max}gauges labelledserviceandpool, a closedPoolName(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 rawPgPoola service builds beside its main one, reading the maximum from the pool’s own options.DbPoolOpts—max_connections,idle_timeout,application_name,session_settings, andacquire_test:AcquireTest::Always(the default; sqlx’stest_before_acquire) orAcquireTest::IdleFor(d), which pings a connection before lending it only once it has idledd(needs_ping), throughbefore_acquire, saving a round trip a lend at the cost of lending a connection the server dropped withind(ADR-049 Amendment 13; the issuer pool uses 1 s).opts.to_pool_options()returns thePgPoolOptionsconnect_withuses, release check included, for a caller holding connect options rather than a URL. Outside development the URL must carrysslmode=verify-caorverify-full;requireis refused, since it accepts any server certificate (#3646). -
pool_options()— thePgPoolOptionsevery production pool starts from:DbPool::connect_withand each raw pool a service builds beside its main one (#2538). Itsafter_releasecheck probes each returning connection withbegin_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 rawBEGINnever ended, which sqlx pools as it is, or a request future dropped with itsBEGINin flight, which sqlx left open until 0.9.1. Each rollback logs aWARN(a pooled connection came back inside a transaction block, fieldblock=openorfailed). The check costs one round trip per release, off the request path. A pool built fromPgPoolOptions::new()goes without it, and so does one whose builder callsafter_releaseagain, which replaces the hook. Thecargo xtask db-poolsgate (avalidatestage) refusesPgPoolOptions::new/::default,PoolOptions::new/::default,PgPool::connect…/Pool::connect…and anyafter_releasecall 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 frompool_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 aBEGINin flight. The decision record (the alternatives weighed, the probe, the cost) is thecanopy_db::pool_releasemodule doc. -
StatementBudget— PostgreSQL'sstatement_timeoutas a type (ADR-053): whole milliseconds, never zero, with the class ceilingsREQUEST(30 s),IDENTITY_ISSUER(5 s) andBATCH(300 s).DbPoolOpts::statement_budgetsends 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-writtenSETstring. -
commit(tx)— the one way production code commits (ADR-053). It returnsCommitError::Refusedwhen the server answered the commit with an error andCommitError::OutcomeUnknownwhen no answer was read, whichApiErroranswers as the coded 500db_commit_outcome_unknown. Converted to asqlx::Error, the unknown case carries canopy-common'sCommitOutcomeUnknownmarker, so a store function that returnssqlx::Errordoes not lose it. -
validate_database_name(url, service_name)— the ADR-001 guard: aDATABASE_URLwhose database is not the service’s own is fatal outsideCANOPY_ENV=development. -
advisory::run_with_advisory_lock(pool, lock_name, f)— tick-level leader election onpg_try_advisory_xact_lock; returnsSchedulerOutcome::{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)inpublic,SHA-256("<schema>/<name>")in any other schema, so an ephemeral test schema never contends with a live service.advisory_lock_id_forreadscurrent_schema()on the connection that takes the lock. -
fti_audit— FTI audit logging per IRS Publication 1075: thefti_audit_logentry and purpose-code types, the hash-chained locked insert, the retention sweeps, andscrub_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 frompg_auth_membersandpg_databaseunder the statement’s snapshot:member_of(pg_has_role(…, 'MEMBER')'s reach, SET-only grants and the database owner’spg_database_ownerincluded) andprivs(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 opensWITH RECURSIVEand definesme (oid, rolsuper)first; the module doc iscanopy_db::role_reach. -
window_fence::run_daily_fenced(pool, job_name, f)— wall-clock window fence for daily schedulers: anINSERT .. ON CONFLICT DO NOTHINGelection on the service-localscheduler_runstable 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, andrun_window_fenced_until_complete(…, incomplete)also releases the window whenincompletejudges the tick’s value unfinished, reporting it asRan(#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 bycargo xtask outbox-migrations. -
ensure_idempotency_schema(pool)— the fleetidempotency_keysDDL, advisory-lock-serialised and idempotent, owned by the migration path (canopy_api::bootstrap's in-process run andcanopy-manage migrate apply) — never by the runtime, so a least-privilege runtime role needs noCREATE. Deliberately raw DDL, notsqlx::migrate!, so a second migrator never fights the service’s own_sqlx_migrations. -
redaction::PgRedactionKeyStore(ADR-036) — the sharedredaction_keysstore of the five program services and canopy-persons:mint_unpersisted(kek, kind, id, created_at)thenpersist_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 thecanopy_crypto_shred::RedactionKeyStoreimpl. Every write is stamped with the caller’s instant, never SQLnow()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 extendUPDATEevery period, stops and flags on a fence miss, fails toward losing the lease on transient errors; returns an abort-on-dropHeartbeatGuardwithlease_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 W3Ctrace_context,schema_version, optionalprograms. -
Publisher— validates the payload before staging: any key in theRESTRICTED_FIELDSlist (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 backgroundOutboxDrainerflushes it. Event hold (ADR-039):publish_tx_held(tx, envelope, EventHold { operation_id, generation })stages an event the drainer skips;release_held/drop_heldclear 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 aPublisher.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 anasync fn(EventEnvelope) → Result<(), anyhow::Error>callback. A handler that cannot INTERPRET a delivery returnsErr(ParkEvent::…): the delivery is durably parked inevent_inbox(broker acked, handler tx rolled back) and the per-subscriber unpark scanner (run_unpark_passon 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 atmax_batch; the consumer’s prefetch is raised to at least2 × max_batch, so the next batch buffers while one commits — a delivery stays unacked until its batch commits); a lone delivery runshandlerexactly assubscribe_rawwould, while two or more share ONE transaction — inbox dedupe for all of them (a same-batch repeat of an id runs once),batch_handlerover 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 throughhandler, so retries, the DLQ and parking are unchanged.process_batchis the on-demand surface (therun_unpark_passprecedent): it returns each delivery’sDeliveryOutcome, 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: oneHeldOperation { hold, held_since, rows }per(hold_operation_id, hold_generation)whose oldest unpublished row was enqueued beforecutoff, ordered by(held_since, operation_id)and keyset-paged afterafter, on the ADR-039 partial indexevent_outbox_held_idx;operationnarrows 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-determinationsreads it. -
OutboxDrainer::spawn(pool, manager, &tuning)— lease-based three-phase drainer: claim with aFOR UPDATE SKIP LOCKEDCTE (skipping held rows), publish outside any DB tx with publisher confirms, mark in short transactions guarded byclaimed_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 throughlistenonce its first hour ends, and it deletes processedevent_inboxrows past the service’sinbox_retention_daysin 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 bycargo xtask outbox-migrations --writeand parity-gated by--checkin 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 intoMqTuning(crates/canopy-mq/src/tuning.rs, #2578), whoseDefaultholds the defaults. canopy-api’s bootstrap builds it and hands it toOutboxDrainer::spawnandSubscriber::from_manager, so a malformed value refuses the boot, and returns it asBootstrapResult::mq_tuningfor a service to layer as anExtension. 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 theobject_storecrate: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, andput_prevalidated(path, bytes, &ValidatedUpload)writes bytes thatvalidate_uploadalready passed, refusing a proof issued for other bytes (the applications quarantine flow, which scans after the write). Onlyvalidate_uploadcan build aValidatedUpload, 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 thetest-fixturesfeature, which a[dev-dependencies]entry alone may enable (a canopy-store test fails otherwise). -
ObjectStoreConfig— loaded fromCANOPY_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 unlessCANOPY_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:inferaccepts 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). -
Scannertrait +ScanReport/ScanResult/ScanError— the pluggable AV seam;NoopScannerships 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’styp: canopy-notices signs documents underDOCUMENT_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 whosealgis not ES256 or whosetypis notDETERMINATION_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 beingderive_kidover 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, fromCANOPY_VERIFY_KEY_<PROGRAM>or, in development only,.keys/<program>-public.pem(no_PREVslot);rotation_status()reportsRotationState::{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) → SignatureCheckis the production determination path (#2061): an empty or unparseable detached JWS, one whose header is not ES256 with the determinationtyp(#2953, absent included), or one with no stringkid, isMalformed; a kid without thecanopy-{program}-prefix isUnknownKeybefore any key is tried; the key registered under exactly that kid, or else the key the provider serves for it, decidesVerifiedorMismatch; a provider miss, or no provider, isUnknownKey; a provider error or an unparseable served PEM isKeyLookupFailed. A determination signed with a since-retired key still verifies through the provider. canopy-eligibility maps each non-Verifiedoutcome to aQuarantineReason(ADR-002 Amendment 5). -
DeterminationSignertrait —fn sign(&self, payload: &[u8]) → Result<String>, implemented bySigningKey. -
load_program_signer(secrets, program, dev_keys) → Result<ProgramSigner, ProgramSignerError>— the program services' boot-time signer (program_signer.rs): the PEM fromCANOPY_<PROGRAM>__SIGNING_KEYthrough the auditedSecretProvider, else, in development only,.keys/<program>-private.pem; thekidderived from the public key;ProgramSigner { signer, identity }carries the(kid, public_pem)paircanopy_api::spawn_signing_key_registration_if_configuredpublishes. With no key every program refuses to boot (#2489). -
ApplicantClaimIssuerandClaimVerifyingKeyRegistry::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’sboot_applicant_verifier. A claim’s protected header is{"alg":"ES256","kid":…,"typ":"canopy-applicant-claim+jwt"}(APPLICANT_CLAIM_TYP). Verification refuses any other or absentalg(ClaimVerifyError::UnexpectedAlg) and any other or absenttyp(UnexpectedTyp) before it looks up thekid, 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).VerifyingKeyLoadErroris that loader’s andfrom_secrets' error. -
KeySigner(key.rs, ADR-049 §9) — the backend-agnostic ES256 signer:public() → &PublicKeyInfo(kid: Kid,alg: JwsAlg,jwk: PublicJwk) andasync sign(signing_input) → Result<RawSignature, SignError>, whereRawSignatureis the 64-byter‖sform (RFC 7518 §3.4) andSignErrorisUnavailable/Timeout/Refused/Internal.JwsAlgis#[non_exhaustive],Es256only.Kidis 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 base64urlx/yof a P-256 point:from_coordinatesrefuses 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,Cloneor 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 answersSignError::Timeoutwhen the signer missesdeadline.conformance::assert_key_signer_conformance(&dyn KeySigner)is the behaviour every backend must show (a verifyingr‖ssignature 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 thetest-helpersfeature. Determination signing does not use it yet (#2502). -
ProvisionedP256Key(provisioned.rs, ADR-049 §10, #2548) — theKeySignerover a provisioned key, for a canopy-identity client’sprivate_key_jwtassertions.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,Cloneor serde implementation, is zeroized on drop, andDebugprints only the public half.load_provisioned_key(secrets, key_name)reads the PEM throughrequire_secret, with no file fallback in any environment; key names end in_PRIVATE_KEY, so thesecret-loadsgate refuses a raw environment read of one.ProvisionedKeyErrorisMissing(unset or blank, naming the secret),Unreadable(the provider failed),Malformed,NotP256(PKCS#8 for another algorithm or curve) orEncrypted(anENCRYPTED PRIVATE KEYPEM); none carries key material. It passesassert_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_pemloads it, andLocalP256Keystill 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 aNoticeTree, one or morenotices/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 insidenotices/; canopy-notices builds it from every configuration layer’snotices/); 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 daydatetime.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 underservices/canopy-notices/tests/notices/golden/;UPDATE_GOLDEN=1rewrites them after an intended change. -
RenderEngine::render(program, template_key, context) → RenderedNotice— the NOA path: resolves the template via the manifest, compiles the.typsource, 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 andNoticeContext; the path is../absolute-validated. -
manifest::Manifest::load(path)— loadsmanifest.toml, mapping template keys to versioned.typfiles with form numbers and each letter’s requiredhearing_rightsflag (#2431), carried on the resolvedTemplateRef.NoticeContextis the typed render context (agency identity, recipient, case number, notice date, locale, the fair-hearing and continued-benefits fields, plus free-formprogram_dataeach template owns); it deliberately carries noform_number/template_version— the manifest-resolvedTemplateRefis their only source, so the archived PDF and an on-demand re-render cannot print different footers. The engine also sets thetemplate_programinput, the snake_case slug of the program whose manifest entry the template resolved under, afterprogram_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 sharedreqwest::Client(a program service’smainpassescanopy_common::http::data_path_client()); every call carriesRULES_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 thecontext.thresholds.paths andinput.names its service sends;ContractError::Unsuppliednames the decision, the half of the input and every unsupplied reference. canopy-snap and canopy-wic call it at boot (the decision contract), andcanopy_test_lib::threshold_syncshares 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_nameis the decision's file name without.json) and returns the decision-table output;evaluate_with_corpus_hashalso 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.
-
ManifestandBundlereadextensions/<name>/from aConfigSnapshotor a pack directory:extension.toml,module.wasmandmigrations/*.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::recordis theExtensionRecorda determination signs. -
The
runtimefeature (on by default; canopy-pack-check links the crate without it) adds the WebAssembly runtime and the database sandbox. -
Runtime::newcompiles the component with wasmtime and proves it imports only the contract'shostinterface.admitandoutcomerun in the caller's transaction;decidehas no database. Each call is a fresh instance with the manifest's fuel and memory limits. Any failure is aCallError; none continues without the module's answer. -
sandbox::installcreates the module's role, schema and two executor functions and applies its migrations as that role.sandbox::Callwraps 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 arefixtures/extension-src/, committed built asfixtures/extensions//module.wasm;cargo xtask extension-fixturesholds 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*.jsondirectly under a layer directory, in file-name order, compiled through zen-engine (GraphContent, thenDecision), the path canopy-rules evaluates. Each file'sFileOutcomeisCompiled(CompiledDecision),ParameterFile(no top-levelnodesarray),Failed,NotJsonorUnreadable, andmisnamed_ascarries the embeddednameof 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 whosenameis itsruleset(or only the layers itspackslists), its output read as canopy-rules serves it and held to itsexpectblock. An outcome isEvaluated(with the failure, if any),Unmatched,Ignored,NotJsonorUnreadable. -
replay_pack_fixtures(&[CompiledDecision], fixture_dir, jurisdiction)— the same replay for one pack's fixtures over its stack: a fixture'spacksis 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 whosepacksleaves no decision yieldsFixtureOutcome::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 underoverrides. canopy-rules calls it as it loads a stack (NamedFilesystemLoader::from_files). -
audit_pack_citations(pack_dir, slug, max_staleness_days) → Result<PackCitationAudit, CitationError>— thecanopy_policy::citationaudit of a pack'sjurisdiction.tomlagainst itscitations.toml, including the election citations against the federal option keys. APackCitationAuditcarries the manifest, the pack's key count and everyValidationIssue;findings()is its error-severity issues (a staleness warning is not a finding).federal_option_keys()andorphan_allowlist(CitationFamily)are the two lists the audit consults, compiled in fromcompliance/federal-options/*.tomlandcompliance/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 auditreads the federal family's allowlist from the same function. -
restated_federal_constants(jurisdiction_toml) → Result<Vec<Finding>, CheckError>— canopy-common'srefuse_pack_copiesapplied to a pack file forsnap-procedure.jsonandtanf-time-limit.json: at most one finding per federal file, with the message a service refuses to boot with. canopy-common is declared without itssqlxfeature, 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].classnames that no row declares; and a reason codemedicaid-denial-reasons.jsoncan 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, afiling_window_daysoutside its federal bound, or a printedappeal_deadline_daysthat 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, whichcargo xtask rules processing-daysalso 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_replacementapplied across a stack of layer directories, lowest first, each with theoverridesits 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 whatcanopy config checkruns: the pack's compile and decision names, the override rule across federal then pack, the pack's ownfixtures/rulesets/(when present) replayed againststack_decisions, then the federal-constant, citation and paired-clock checks of itsjurisdiction.toml. APackCheckholds everyFindingand theNotevalues 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 (checkis a kebab-caseCheck);FileCompilation::findings(),FixtureOutcome::finding(),PackCitationAudit::findings()and the two pack-file checks produce them.CheckErroris 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 whosecalls()send withsource, 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 whenprojectionnamesPersonSsn, #2705),list_addresses, and the bulkbatch_get_persons/batch_get_households. -
Writes (create/claim):
create_person,create_household,claim_member,claim_income,claim_asset,claim_expense,claim_address— each takes anOption<&FinalizeStep>that tags the write for idempotent finalization (ADR-038);Noneis 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::StepKeyis 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 runtimesqlx, so the crate compiles against no schema. Every writer takes the caller’s instant and binds each stamp it writes from it — no SQLnow(), andCANONICAL_STAMPS_NO_DEFAULT_MIGRATION_SQLdrops the stamp defaults (#2576) — so a program service passes its request’s or delivery’s instant from its decision clock. Callers areapiand 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 aListAdmissionand itsClaimAdmissionsfor the others, andclaim_routes(claims), which registers the four per-claim paths under/overpayments/{id}without/overpaymentsitself (#2242). canopy-tanf and canopy-medicaid each mergeroutes(…)into theirapi::routes()and name the six handlers in theirApiDoc. canopy-snap registers/overpaymentswith 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 sharedlist_claims, mergesclaim_routes(…), and names its ownpost_claimin itsApiDoc.to_api_erroris public — the oneOverpaymentError→ HTTP mapping every claim handler uses, a service’s own create handler included. The routes sit under/v1behind each service’s receiver: the per-claim reads admit a system caller or aCASEWORKER_OR_ABOVE_ROLESdelegation, the writes a system caller or aCASEWORKER_WRITER_ROLESdelegation (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_OVERPAYMENTSand its siblings). The handlers take theExtension<PgPool>each service’smain.rslayers, so each service’s handlers reach only its own database; the writing handlers also take itsExtension<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,RulesClientand the rest). No method returnsserde_json::Value(quality budget B7, locked at zero, #3411): a JSON response is read into a typed struct, nearly always itscanopy-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, andTanfClient::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 fromtokens;.healthy_or_skip()— probes/livezand reports a miss itself throughskip_or_panicby service name and URL, so a setup guard isif !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 itsCANOPY_TEST__*_URLvariable, 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.envan 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 namedtest_…. -
infrastructure_available()— TCP-probes Postgres and the rules canary; underCANOPY_TEST_INFRA=requiredorCANOPY_CI=truean unavailable stack PANICS instead of skipping (everycargo xtasklane arms the former — Testing › infra required);skip_or_panic(detail)is the dependency-level skip seam, andok_or_skip(result, what)reports a failed setup step’s error through it and answersOption(#3132). -
poll_until(description, timeout, interval, check)/poll_until_observed(…)— wait on an observed condition instead of sleeping.poll_until's check answersSome(value)once the condition holds; a wait that times out panics naming what it waited for.poll_until_observed's check answersOk(value), orErr(seen)while it waits, and its timeout panic also names the lastseen, 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) orTokenBroker::from_env()overBrokerConfig::from_env(), which readsCANOPY_TESTIDENTITY_ISSUER,CANOPY_TESTSECURITY_URL,CANOPY_TESTUPSTREAM_CREDENTIALS,CANOPY_TESTUPSTREAM_CA,CANOPY_TESTUPSTREAM_ADDR,CANOPY_TESTIDENTITY_KEYS,CANOPY_TESTIDENTITY_BROKER_CACHEandCANOPY_TESTWEB_ADDR(.ports.envloaded first; a relative path resolves against the workspace root holding it). A person is a cast name (upstream::PERSONS; any other isBrokerError::UnknownPerson).session(person) → FederatedSession;delegation(person, CanopyService, &Narrowing)andstepped_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) → UpstreamSessionsigns the person in at the upstream, andauthorise_query(&UpstreamSession, query) → Authorizationanswers the upstream’s response to a relying party’s own authorization query for that person;upstream() → &Upstreamnames the upstream’skind,origin,authorization_endpointandscopes, canopy-web’sclient_idand registeredredirect_uris, and the CA asca_pem, all public;ui_credentials(person) → UiCredentialsanswers 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, itsDebugshowing neither secret.link_cast() → LinkReportlinks every cast person butLINKING_ADMINtoSeedPerson::realm_subject()through the admin routes where its pair does not already open as it, the devstack bring-up’s last step.BrokerError::is_unavailablenames 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_PATHandJWKS_PATHare 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 publicationfrom_credentialsassumes;sign_in,sign_in_with,authorise,authorise_queryandtokens_forsign in and authorise as a browser would,expire_account,restore_accountandset_rolesare the conformance cases' admin writes, andoidc()is the plain OIDC client (upstream::oidc::OidcClient: exchange, refresh, revoke, userinfo, discovery, JWKS).upstream::{Credentials, Secret, TotpSeed, UpstreamError}are vendor-neutral;Credentials::profile_yamlis the profile canopy-web would load for the server. -
tokens— a test’s canopy-identity tokens through one process-wideTokenBroker, built fromBrokerConfig::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) andcli(person, CanopyService)(canopy-cli’s delegation from a device session).tokens::or_skipholds the same five answeringOption, a miss reported throughskip_or_panicwith the broker’s error before theNone.cast(username) → &strmaps a pre-switch test username to its cast person (the same name, butadminiscanopy.admin);system_caller(CanopyService) → Option<ConfidentialClient>names the client asystem()arm’s test mints for.bearer_sub(jwt)/bearer_iss(jwt)read a minted token’ssub/issunverified, andmint_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;FixedBearerandfixed_source(token)answer one fixed token for a stub receiver;test_principalbuilds thePrincipala receiver would insert; andbearer_rejected()is a receiver’s 401token_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 pinsweb.canopy.testtoCANOPY_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, andStubReceiver, 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'DeterminationContextResponseover theDeterminationContextProgramrows given;context_program(program, status)is a row with no episode, to extend with struct update syntax.spawn_mock_persons()serves canopy-persons'HouseholdWithMembersandHouseholdFull(oneselfmember),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 aMockHandlewhose 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 apack_infra_testsmodule; 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 synthetictest-federallayer, #3365) — the configuration a service ofgeorgia,default,test-minortest-maxboots on, as unverified working copies of this checkout (federal, thennotices-neutralbeneath 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].timezoneof theCANOPY_TEST__JURISDICTIONpack, throughcanopy_common::settings::load_jurisdiction_timezoneoverconfig::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)andlegal_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) andday_split_instant(day, tz)(an instant whose date in the zone isdaywhile 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")]—SpanCaptureuses 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.