Adding a Service
For a contributor adding or extending a canopy-* service: this page walks the
chassis every service shares and names the file that implements each piece.
Conventions (SPDX header, the 201 Created override, Askama quirks, database
patterns) are in Coding Conventions (Canopy); the crate-by-crate API is
Shared Crates Reference; a service’s routes and tables live on its api/ and
data-models/ pages, indexed by the Service Catalog.
1. The chassis (canopy-api)
Every service is an Axum binary under services/canopy-<name>/ that hands its
settings, name and embedded migrator to
canopy_api::bootstrap_with(prefix, settings, service_name, migrator)
(crates/canopy-api/src/bootstrap.rs). Bootstrap resolves secrets, runs the
migration phase (How migrations run) and returns the
BootstrapResult the service builds its state from. The router
(ApiServer::router in crates/canopy-api/src/lib.rs) mounts:
-
the service’s routes under
/v1, behind canopy-identity’s receiver (canopy_auth::identity_receiver_middlewareover the bootstrap’sIdentityReceiver); a service with no receiver (canopy-exchange) mounts no/v1; -
GET /livez(process-alive, always 200) andGET /readyz(readyz_check, dependency readiness; the outbox and background-worker checks reportdegradedbut never flip it to 503; a stale configuration layer does) andGET /version(the build and the configuration layers' commits, ADR-051). There is no/healthzand no/metrics: telemetry is OTLP push (crates/canopy-common/src/telemetry.rs); -
Swagger UI at
/swagger-uiover/api-doc/openapi.json, the sourcecargo xtask api-docssnapshots intodocs/modules/ROOT/openapi/; -
the service’s
public_routes, at the root: outside the receiver layer, the idempotency layer and the per-IP limiter, inside every outer layer. A service passesRouter::new()unless an endpoint lives outside/v1: canopy-security’s canopy-identity routes under/identity(services/canopy-security/src/identity/), and anoop-adapterscanopy-verification’s/internal/v1adapter routes, which carry their own receiver layer and admissions (ADR-049 Amendment 16).
Paths are declared once, in full post-mount form, in the service’s contracts
crate (crates/canopy-contracts-<name>/src/paths.rs, e.g.
canopy_contracts_snap::paths::DETERMINE = "/v1/determine"); the router
registers the un-prefixed form.
2. Skeleton and configuration
services/canopy-<name>/
├── Cargo.toml # workspace member
├── migrations/ # forward-only SQL; a program service adds COMPLIANCE.adoc (below)
├── src/main.rs # settings → bootstrap_with → state → ApiServer
├── src/api/mod.rs # pub fn routes() -> Router<AppState>, one .route() per path const
└── tests/ # integration tests (the kind(test) lane)
config/canopy-<name>/default.yaml # ADR-012 layered config
Every program service carries migrations/COMPLIANCE.adoc, an auditor’s note
on the records the service holds. canopy-snap, canopy-tanf and canopy-medicaid
carry one for the restricted classes they are authorised to hold — FTI under
IRS Publication 1075, IEVS and SSA SOLQ/BENDEX match data under their use
restrictions (ADR-004;
compliance/data-tenancy-authorisation.toml). canopy-caps and canopy-wic hold
none of those classes; theirs record the CCDF and WIC reporting and retention
obligations the tenancy matrix does not cover — 45 CFR 98.70 and 98.90(e) with
the DECAL CAPS manual, and 7 CFR 246.25 with the DPH WIC manual — each claim
cited to its CFR paragraph or policy-corpus doc id
(compliance/policy-sources/).
Configuration is load_service_config (crates/canopy-common/src/settings.rs):
the shared ServiceSettings baseline (port, database_url, rabbitmq_url,
identity_issuer, identity_internal_url, jurisdiction, …) plus the service’s own
struct, sourced from config/<svc>/default.yaml, the overlay tier an explicit
CANOPY_ENV names (Configuration
Reference › Layering) and the prefixed environment (CANOPY_<SVC><KEY>, double underscore). The baseline
is deny_unknown_fields and the loader partitions keys by
ServiceSettings::FIELDS, so a key in neither struct fails boot naming itself.
config_source, the configuration layers the service reads its policy
through, is required and has no shipped default: outside development
CANOPY_CONFIG_SOURCE sets the whole stack and
CANOPY_<SVC>CONFIG_SOURCE pins one service, and a boot without one is
refused; the development overlay dev.yaml names the devstack’s (#2627). The
jurisdiction is the one the jurisdiction layer’s canopy-config.toml names
(Configuration Reference ›
Configuration source, ADR-051). Secrets
are read through the audited secret provider, never from YAML: the signing key
(from secrets/dev.yaml through cargo xtask secrets on the devstack) and,
for a service that calls another, its canopy-identity client key,
CANOPY_<SVC>__IDENTITY_CLIENT_PRIVATE_KEY, a reserved key with no file
fallback, without which the service refuses to boot (on the devstack, from the env file xtask writes:
Local Development › Upstream IdP: Kanidm).
Every variable is documented in Configuration Reference.
3. Authentication and authorisation
canopy-identity, hosted in canopy-security, is the only token issuer
(ADR-049). A service’s receiver
admits only a bearer issued for that service: a delegation token (a worker
acting through canopy-web or canopy-cli, or a service delegating that worker
onward) or a system token (a confidential client on a compiled System or
Both edge, crates/canopy-auth/src/identity_policy/call_graph.rs). It
inserts the caller as a Principal, and each handler admits it by a named
Admission. POST /v1/determine in canopy-snap
(services/canopy-snap/src/api/determine_handler.rs):
pub async fn post_determine(
Extension(principal): Extension<Principal>,
// … the service's own extractors …
Extension(outbound): Extension<RequestOutbound>,
body: axum::body::Bytes,
) -> Result<Json<SignableDetermination>, ApiError> {
principal.admit(&super::WRITER)?;
// …
}
-
WRITERisAdmission::system().and_user_roles(CASEWORKER_WRITER_ROLES)(services/canopy-snap/src/api/mod.rs): any system caller, or a delegation whose user holds a writer role; its reads takeCASEWORKER_OR_ABOVE_ROLES. The role names and the read/write split are in RBAC Matrix. -
A route a worker reaches only through named clients takes its row’s constant from
canopy_auth::delegated(e.g.delegated::SNAP_GET_DETERMINATIONS), whose via arm (user_roles_via(&[clients], roles)) names them;Admission::system_from(&[clients])admits only the listed system callers, and a portal route adds a portal arm (portal(scope)). -
A refusal is a 403 Problem Details whose
codenames the rule (required_role_missing,actor_not_allowed,system_caller_required, …,crates/canopy-auth/src/identity_receiver/denial.rs); a missing or rejected bearer is the receiver’s 401token_missingortoken_rejected. -
A handler that calls another service sends through the request’s
RequestOutbound(onward delegation for a user, a system token for a system caller) withcanopy_auth::send_with_retry, which re-mints once after a receiver refuses the bearer. Work outside a request (a background task, a durable retry, boot) sends through the service’sIdentitySenderas itself, and a system caller’s recorded actor is its client id.
Every route’s admission is inventoried in Fleet authorization inventory
and RBAC Matrix — do not restate role lists in a service.
cargo xtask delegated-routes check holds the delegated table to the
services' registrations, cargo xtask call-graph check holds the compiled
call graph to the services' peer settings, and each service’s identity
contract test pins the receiver’s refusals
(Testing › Identity). Errors are RFC 9457
Problem Details via canopy_common::error::ApiError.
4. Events
Publishing goes through the persistent outbox (ADR-018, ADR-039):
canopy_mq::Publisher::publish_tx writes the row inside the caller’s
transaction (publish is the one-shot wrapper) and the service’s
OutboxDrainer::spawn(pool, manager, &tuning) flushes it to the canopy.events topic
exchange (EVENTS_EXCHANGE). There is no in-memory buffer and no inline
publish. The EventEnvelope (crates/canopy-mq/src/envelope.rs) carries id
(UUID v7), timestamp, source_service, event_type (the AMQP routing key),
schema_version, payload, an optional trace_context and an optional
programs set:
{ "id": "01942a3b-…", "timestamp": "2026-04-15T14:30:00Z", "source_service": "canopy-snap",
"event_type": "snap.determination_completed", "schema_version": 1,
"payload": { "determination_id": "…", "status": "…" },
"trace_context": { "traceparent": "…" }, "programs": ["snap"] }
A payload naming a restricted field is refused (PublishError::RestrictedField;
ADR-004 — events carry IDs, statuses and timestamps only). Subscribers:
Subscriber::subscribe() for competing consumers (database-mutating handlers),
subscribe_exclusive() for per-instance fan-out (cache invalidation). A new
routing key needs an in-tree consumer or an allowlist entry (cargo xtask
mq-topology), and the service’s event_outbox migrations are generated by
cargo xtask outbox-migrations --write. Delivery guarantees and the
parked-state inbox: Event-Delivery Protocol.
5. Determination signing as built (ADR-002)
A program service signs its own determinations. At boot it loads its ECDSA
P-256 private key from CANOPY_<SVC>__SIGNING_KEY (the SOPS-provided secret;
.keys/<program>-private.pem is the devstack fallback), builds a
DeterminationSigner over canopy_signing::SigningKey::from_pem, and
registers the public key with canopy-security’s signing_key_history through
canopy_api::spawn_signing_key_registration (services/canopy-snap/src/main.rs;
ADR-036). canopy-eligibility verifies with canopy_signing::verifier: the
current key per program from CANOPY_VERIFY_KEY_<PROGRAM> (from_secrets
falls back to .keys/<program>-public.pem in development only), retired keys lazy-loaded
from signing_key_history. A production pair comes from
canopy-manage gen-signing-keys --program <p> --output-dir <dir>; the devstack generates its own
on start (ensure_signing_keys in xtask/src/devstack_guard.rs).
Rotation: Signing Key Rotation.
6. Rules evaluation (ADR-003)
Eligibility logic lives in versioned JDM rulesets in the configuration
layers, the jurisdiction’s over the federal one
(ADR-006, ADR-051), evaluated by
canopy-rules. Its routes (crates/canopy-contracts-rules/src/paths.rs):
GET /v1/rule-sets, GET /v1/rule-sets/{name}, POST /v1/evaluate,
GET /v1/evaluations, GET /v1/corpus. There is no hot-reload route: a
ruleset change is a file change, gated by cargo xtask rules check and picked
up by cargo xtask dev reload. Program services call canopy-rules through
crates/canopy-rules-client; the jurisdiction they evaluate under is the one
their configuration source’s jurisdiction layer names (§2).
7. The determination flow
worker / applicant
└─ canopy-applications POST /v1/applications
└─ canopy-eligibility POST /v1/eligibility/determine (orchestrator, ADR-002)
├─ canopy-persons household facts
├─ canopy-<program> POST /v1/determine ─► canopy-rules POST /v1/evaluate
│ returns the program's signed determination (§5)
└─ assembles the multi-program result and publishes it through the outbox (§4)
The orchestrator dispatches only to programs whose capability variable is set (§9), so a profile without a program skips it rather than failing (ADR-005).
8. Tests
-
Integration tests live in
tests/(thekind(test)lane); a lib/bin test that touches infrastructure goes in a module whose path has a segment ending ininfra_tests—cargo xtask test-lanes-lintenforces the split. Everycargo xtasklane armsCANOPY_TEST_INFRA=required: an unavailable stack panics, it never skips (testing.adoc#infra-required). -
Database tests use
EphemeralSchema::new_for_<name>(base_url)— add onedefine_ephemeral_schema_for!(<name>)line tocrates/canopy-test-lib/src/db_constructors.rs. The constructor replays yourmigrations/into an isolated schema, so no test touches the service’s real tables; there is notestcontainers. -
HTTP goes through a typed client in
crates/canopy-test-lib/src/clients/over the contracts crate’s DTOs, whosetests/roundtrip.rsproptest pins serialisation. -
Register the new service where the tooling enumerates services:
crates/canopy-test-lib/src/topology.rs,SERVICESinxtask/src/cmd/api_docs.rs, andDATABASESinxtask/src/cmd/migrate.rsandxtask/src/cmd/seed.rswhen it carries seed data.
9. Devstack, profiles and CI
-
Compose: add the service to
docker-compose.ymlwithprofiles:per ADR-005. The six valid profiles are in Deployment Guide › Profiles (VALID_PROFILESinxtask/src/cmd/dev.rs); there is nosnap-tanf. A program service also gets a[capability.<program>]entry incompliance/deployment-profile-capabilities.toml(url_var,service,required_profiles), whichcargo xtask compliance capabilitieschecks against compose; canopy-eligibility’sProgramServiceRegistry::from_envreads theurl_var. -
Database: an infrastructure service’s database is created by
devstack/postgres/init.sqlon the shared instance; a program service gets a dedicatedpostgres-<program>instance (ADR-001). The inventory is in Deployment Guide. -
Schema changes land with
cargo xtask dev refresh(data kept);dev restartwipes volumes (Local Development). -
CI needs no per-service job: the car's one
cargo buildcompiles every binary inlanes::BINARY_PACKAGES, anddev startpackages them by the rootDockerfile's COPY lines (one per binary; add yours) (ADR-040; Contributor Workflow Conventions). The merge train's pipeline runs the whole battery and owns correctness (CI is the gate). -
Docs: the service’s
api/canopy-<name>.adocanddata-models/canopy-<name>.adocpages plus its row in Canopy Service Catalog, and aCHANGELOG.adocentry under== Unreleased.