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_middleware over the bootstrap’s IdentityReceiver); a service with no receiver (canopy-exchange) mounts no /v1;

  • GET /livez (process-alive, always 200) and GET /readyz (readyz_check, dependency readiness; the outbox and background-worker checks report degraded but never flip it to 503; a stale configuration layer does) and GET /version (the build and the configuration layers' commits, ADR-051). There is no /healthz and no /metrics: telemetry is OTLP push (crates/canopy-common/src/telemetry.rs);

  • Swagger UI at /swagger-ui over /api-doc/openapi.json, the source cargo xtask api-docs snapshots into docs/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 passes Router::new() unless an endpoint lives outside /v1: canopy-security’s canopy-identity routes under /identity (services/canopy-security/src/identity/), and a noop-adapters canopy-verification’s /internal/v1 adapter 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)?;
    // …
}
  • WRITER is Admission::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 take CASEWORKER_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 code names 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 401 token_missing or token_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) with canopy_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’s IdentitySender as 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/ (the kind(test) lane); a lib/bin test that touches infrastructure goes in a module whose path has a segment ending in infra_tests — cargo xtask test-lanes-lint enforces the split. Every cargo xtask lane arms CANOPY_TEST_INFRA=required: an unavailable stack panics, it never skips (testing.adoc#infra-required).

  • Database tests use EphemeralSchema::new_for_<name>(base_url) — add one define_ephemeral_schema_for!(<name>) line to crates/canopy-test-lib/src/db_constructors.rs. The constructor replays your migrations/ into an isolated schema, so no test touches the service’s real tables; there is no testcontainers.

  • HTTP goes through a typed client in crates/canopy-test-lib/src/clients/ over the contracts crate’s DTOs, whose tests/roundtrip.rs proptest pins serialisation.

  • Register the new service where the tooling enumerates services: crates/canopy-test-lib/src/topology.rs, SERVICES in xtask/src/cmd/api_docs.rs, and DATABASES in xtask/src/cmd/migrate.rs and xtask/src/cmd/seed.rs when it carries seed data.

9. Devstack, profiles and CI

  • Compose: add the service to docker-compose.yml with profiles: per ADR-005. The six valid profiles are in Deployment Guide › Profiles (VALID_PROFILES in xtask/src/cmd/dev.rs); there is no snap-tanf. A program service also gets a [capability.<program>] entry in compliance/deployment-profile-capabilities.toml (url_var, service, required_profiles), which cargo xtask compliance capabilities checks against compose; canopy-eligibility’s ProgramServiceRegistry::from_env reads the url_var.

  • Database: an infrastructure service’s database is created by devstack/postgres/init.sql on the shared instance; a program service gets a dedicated postgres-<program> instance (ADR-001). The inventory is in Deployment Guide.

  • Schema changes land with cargo xtask dev refresh (data kept); dev restart wipes volumes (Local Development).

  • CI needs no per-service job: the car's one cargo build compiles every binary in lanes::BINARY_PACKAGES, and dev start packages them by the root Dockerfile'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>.adoc and data-models/canopy-<name>.adoc pages plus its row in Canopy Service Catalog, and a CHANGELOG.adoc entry under == Unreleased.

Edit this page · default