Worker identity as an opaque OIDC subject, with typed actors (#1008)

Status: Done (2026-09-26) — !1517
Issues: #1008, #2327–#2333 (epic &129)
Branches: refactor/1008-oidc-subject-actors (carries this page)

This is a Design + Scope plan. GitLab owns tracking, and each child issue (and #1008 for U-A) carries its unit’s exact inventory. The plan freezes when U-A starts. It ships as one MR with one battery, because the wire and contract changes must land in lockstep. For example, enrollment’s assignment gate deserializes applications' response, and medicaid’s consent subscriber parses applications' event.

Erratum (2026-09-26): D4’s guard also refuses every row whose pre-#1008 writer recorded a service’s own sub as a UUID subject, since that cannot be told from a human’s: every application_sections row, every cancelled rep_disqualifications row, every overpayment_claims row, every overpayment_recomputes row and every resolved ievs_discrepancies row. A converted service account would be an invented human.

Erratum (2026-09-26): D7’s framed form also opens every nullable input with a presence byte (0x00 absent, 0x01 then the value) in place of the NONE / GENESIS sentinels, and hashes source_application_id, which was not a chain input. The verifier reads the stored actor as raw text, so a malformed, doubled or missing actor is a break at that row, not an error.

Erratum (2026-09-26): the snap IEVS resolution event carries its actor as resolved_by (D3’s wire name), not under the facts author key. canopy-security’s actor-field scan reads every #1008 actor field and composition’s actor_user_id, and only a typed Actor may record the reserved human / service classes (D8).

Erratum (2026-09-26): EffectiveUser::actor() also refuses (403) a bearer naming two distinct services, or a citizen-class azp that disagrees with its service: role. The portal finalize records its ELE consent as the finalizing service and admits only a citizen-class principal equal to the bearer’s azp.

Context

A worker is (issuer, sub), and sub is opaque and case-sensitive (OIDC Core 1.0 §2). Canopy projects it into a Uuid almost everywhere:

  • Projections and duplicates. parse_worker_uuid (services/canopy-web/src/api/composition.rs:197), parse_user_id (api/dashboard.rs:708), canopy_composition::UserId (crates/canopy-composition/src/types.rs:140), about 20 service-side sub parses, KeycloakSub beside the contracts-security WorkerSubject, and three {worker_id} path templates (the typed-id allowlist’s only entries).

  • Nil sentinels. A service act records Uuid::nil() (api/reopen_support.rs:54, postponement_saga.rs:364, snap api/recompute_handler.rs:239-245), encoded in three CHECKs (20261222000000_reopen_void_audit.sql:42-48, 20261223000000_postponement_episodes.sql:55-59).

  • Lost or wrong actors. Many service writes record NULL, which loses which service acted. Section edits record canopy-web’s service account, and ELE consent records an applicant PersonId when no human bearer is present.

  • Actors in bodies. The renewals nudge / redetermination action_by, WIC assessor_worker_id and IPV referred_by come from request bodies, the service-transported human that ADR-043 C1 retired. Some worker fields are typed PersonId.

Rulings in force: the #1008 ruling (2026-09-11, amended); the maintainer’s 2026-09-25 rulings (the type name; the correct service-actor model); ADR-046 (opaque, query-borne subject; issuer deferred, item 5); ADR-043 (EffectiveUser); ADR-001 §B4. Pre-1.0: no compatibility shims, and data that cannot be expressed is refused, never invented.

Scope

In scope: D1–D9 below.

Out of scope (GitLab follow-ups, linked from the closing comment):

  • free-string actor columns typed as Actor: eligibility requested_by (the worker’s display name, from a body), the appeals *_actor columns, WIC scheduled_by, medicaid claim_adjustments.actor, renewals converted_by, and enrollment’s sub=…; actor=… composites;

  • a per-row issuer at the federation trigger (ADR-046 item 5);

  • more TEXT actor columns outside this inventory: quarantine_resolutions.actor, the cohort_runs actors, snap/tanf claim_provenance_adjustments.actor, tanf recorded_by / resolved_by;

  • the pending-verifications panel filters on the never-written verifications.worker_id;

  • canopy-web’s WIC assessment form captures no risk_codes, so its write is refused;

  • #607’s assignment revamp builds on OidcSubject (coordinate, don’t block).

Design

Decisions

# Decision

D1

Types (new crates/canopy-common/src/identity.rs, never id.rs: its UUID-v7 invariant stands).

  • OidcSubject: the OIDC sub, compared byte for byte (OIDC Core 1.0 §2).

    • Invariant: 1–255 bytes of ASCII with no control characters.

    • Constructors: TryFrom<String> / FromStr (typed InvalidOidcSubject), serde try_from = "String", utoipa value_type = String, as_str, Display.

    • No infallible From, and no trimming, case folding or other normalization anywhere.

    • SQL: Type and Encode delegate to String. Decode is hand-written: it decodes a String, then applies TryFrom, so a malformed stored value is a decode error (not sqlx’s transparent derive, which builds the wrapper unchecked).

  • ServicePrincipal: a service caller’s name, the service:<name> role suffix. Same rules and the same validating Decode.

  • Actor: Human { subject: OidcSubject } | Service { service: ServicePrincipal }.

    • Serde is internally tagged on actor_type (the Author precedent in crates/canopy-contracts-facts/src/lib.rs).

    • Actor::from_columns(Option<OidcSubject>, Option<ServicePrincipal>) → Result<Option<Actor>, ActorColumnsError> refuses both being set. Actor::columns() yields the pair to bind.

  • Deleted, with no alias:

    • KeycloakSub (and its canopy-contracts-persons re-export);

    • the contracts-security WorkerSubject, parse_worker_uuid, parse_user_id, canopy_composition::UserId (its v7 test is rewritten against OidcSubject).

      OpenAPI renames the KeycloakSub / WorkerSubject components to OidcSubject (persons, snap, security).

  • The subject trims go: canopy-security’s worker observation and lookup (api/mod.rs:1471 and its lookup twin) and canopy-persons close_author (api/mod.rs:1508).

D2

The bearer is the only actor source.

  • canopy_auth::Claims.sub: OidcSubject. A token whose sub breaks D1 fails validation (401). Claims loses Default (no subject is a valid default).

  • EffectiveUser::actor() → Result<Actor, ApiError>:

    • Direct → Human(sub);

    • System → Service from its service: role; a System without a valid principal → 403.

      Claims stays publicly constructible, so the conversion is fallible rather than assumed. attribution_sub() keeps its string projection for non-column uses (idempotency principal, accessed_by, logs).

  • An actor is never read from a body or path. A body or query field survives only as a referent, a worker the request names who is not the caller: household_assignments.worker_id, appeal_requests.hearing_officer_id, the verifications worker_id filter.

  • Request and query types that lose an actor or gain subject are deny_unknown_fields. A stale action_by, referred_by or discovered_by, or a subject sent to /all, is refused.

D3

Storage: one of three shapes per column (ALTER COLUMN … TYPE TEXT USING …::text; existing UUID values remain valid subjects).

  1. Human-only act (every writer refuses service bearers): <col> TEXT holding OidcSubject, NOT NULL when the act is mandatory.

  2. Service-reachable act (a scheduler, saga, subscriber or service-admitting gate writes it): the pair <col> (subject, NULL) + <col>_service (principal, NULL).

    • A mandatory act has CHECK (num_nonnulls(<col>, <col>_service) = 1).

    • An optional act has num_nonnulls(…) ⇐ 1 plus the act predicate: attribution is present exactly when the act happened. For example, (reverted_at IS NULL) = (num_nonnulls(reverted_by, reverted_by_service) = 0).

    • Rows carry Actor / Option<Actor>, and so does the wire.

    • The existing reopen and postponement *_service columns are reused. An owning service’s own job names itself, e.g. Service("canopy-medicaid").

  3. Referent: <col> TEXT holding OidcSubject.

    • Names say what they hold, in columns and on the wire: actor_uuid → actor, interview_completed_by_uuid → interview_completed_by, medicaid ele_grant_events.actor_id → actor (+ actor_service).

    • PersonId-typed worker fields are retyped the same way.

    • snap ievs_discrepancies.resolved_by (UUID, never written) is dropped. resolved_by_sub becomes the pair resolved_by + resolved_by_service.

    • Columns with no writer take the human-only shape.

D4

Migrations and the reset cutover (pre-1.0, so the only populated databases are devstacks).

  • Nil sentinels go: reopen_support.rs Actor::subject() (reopen and postponement), the saga compensation (Service("canopy-applications"), COMPENSATION_SERVICE) and snap caller_uuid all write D3 actors.

  • Each migration runs in this order:

    1. drop every CHECK that mentions a retyped actor column: the three nil CHECKs, and lifecycle CHECKs such as postponement_reverted_pair, whose (reverted_at IS NULL) = (reverted_by IS NULL) a service revert would break;

    2. ALTER … TYPE TEXT and DROP NOT NULL where a pair needs it;

    3. rewrite a nil actor that has a named service to NULL + that service;

    4. run the guard;

    5. re-add every dropped CHECK restated over the pair, then the D3 CHECKs, all VALID.

  • The guard. It raises, naming cargo xtask dev restart, if any row would need a provenance nobody recorded:

    • a service act with no named service, such as historic system denials, NULL service cancels, and NULL system ELE events;

    • a nil actor with no service;

    • any ele_grant_events row (D7).

      No backfill invents a provenance, and no NOT VALID constraint survives.

  • Durable messages. Consumers of an event whose actor field changes shape parse the new shape only. An old or malformed message makes the handler return an error, so canopy-mq nack-requeues it to max_attempts and then routes it to the DLQ. No consumer acks and drops, as medicaid’s consent handler does today (main.rs:1671-1676).

  • Upgrade. It is quiesced: outboxes and queues drain before the new build starts. The devstack procedure is cargo xtask dev restart (it wipes the database and broker volumes; the reseed refills them). The CHANGELOG carries the upgrade note.

D5

Routes (auth classes unchanged unless D6 says otherwise).

  • canopy-applications, still service-only: POST /v1/assignments {worker_id, household_id}, GET /v1/assignments?subject=, GET /v1/assignments/household-ids?subject= (a static segment beside /v1/assignments/{id}).

  • canopy-eligibility: GET /v1/eligibility/cross-program-alerts/scoped?subject=&limit=, beside /all.

    • resolve_effective_worker keeps its three arms. Caseworker tier uses the bearer’s subject; a supplied subject must equal it, else 403. Supervisor-or-above and the allowlisted canopy-web service caller must supply subject.

    • The scoped feed gets its own query type.

    • The retired spellings keep returning 404, so mixed deployments fail closed both ways (the #596 property).

  • ?subject= is always URL-encoded (reqwest .query), never interpolated. An invalid subject is refused before any lookup.

  • The typed-id allowlist loses all three entries. Its header and the xtask/src/cmd/typed_ids.rs doc are rewritten, and the gate passes empty.

D6

Actors move from bodies to the bearer.

  • The renewals nudge action drops action_by. canopy-web already sends the exchanged bearer.

  • WIC’s risk assessment is a human clinical act.

    • Its route becomes human-only (ReceiverContract::require_user_only over its current writer roles), and the assessor comes from the bearer.

    • The body becomes CreateNutritionalRiskAssessment (no id / created_at / assessor). canopy-web stops sending the display name.

    • Its form still captures no risk_codes, which the handler requires, so the web write stays refused. That is a follow-up.

  • The renewals redetermination action and IPV referral (POST /v1/ipv/cases) adopt require_service_or_exchanged(CASEWORKER_WRITER_ROLES) (the nudge action’s gate) and derive the actor. Their body action_by / referred_by are deleted. They have test-lib callers only.

  • The canonical overpayments CreateClaimRequest.discovered_by is deleted. The handler derives the actor.

  • canopy-web’s section proxy (put_section_proxy) sends the exchanged worker bearer, as the other application writes do.

  • ELE consent: consent_recorded_by is an Actor on application.ele_consent_recorded and a pair in ele_consents. A service path records its service, never the applicant’s PersonId (the event’s person_id names the applicant).

D7

The ELE hash chain is framed (services/canopy-medicaid/src/ele_audit.rs, ADR-014).

  • The current form concatenates fields with no framing. Once a subject can be any D1 string and an actor can be a service, that is ambiguous: Human("NONE") would hash as an absent actor, and a crafted subject as a service.

  • The new form length-prefixes every field (u32 big-endian byte length, then the bytes). The actor is one tagged field: N | H + subject | S + principal.

  • It replaces the old form outright. No version column and no second verifier: D4’s guard refuses a database that still holds chain rows, and the reset reseeds.

  • Tests: new golden vectors for all three actor arms; Human("NONE") ≠ absent; Human("NONEservice:canopy-medicaid") ≠ Service("canopy-medicaid"); a field shifted across a boundary breaks verification.

D8

Audit rendering uses actor metadata, not spelling.

  • canopy-security’s extract_actor (event_parsing.rs) reads an Actor object in any candidate field. It records user_id = the subject or principal and user_role = human or service.

  • canopy-web’s resolve_actor decides the class from user_role when present: service → the principal; human → "you", the directory name, or "another worker".

  • Without a role (older rows) it matches exactly, with no trimming or case folding:

    • NULL or empty → "system";

    • the session subject → "you";

    • a directory hit → the name;

    • otherwise → "another worker".

      The literal system / none match and the UUID test both go.

D9

Issuer: not stored (ADR-046 item 5).

  • Two IdPs issuing one sub collide in attribution columns and the composition user layer. The trigger is a ruleset with more than one (#515, #568), and a follow-up is filed.

  • Subjects may be logged (ADR-046 item 7 already logs issuer + subject).

Column shapes (D3)

The shapes are classified by writer class, as of main at 5664cb71d. The child issues carry each column’s file and line.

Shape Columns

Pair, mandatory (= 1)

  • applications:

    • application_sections.last_edited_by, application_interviews.actor;

    • administrative_denials.actor, plus (initiated_by = 'system') = (actor_service IS NOT NULL); the drains name canopy-applications;

    • the existing reopened_by, postponed_by;

  • medicaid: ele_consents.consent_recorded_by, ele_grant_events.actor;

  • appeals: ipv_cases.referred_by, ipv_timeline_events.recorded_by, appeal_timeline_events.recorded_by (every writer passes NULL today, and each now passes its actor);

  • snap: overpayment_recomputes.requested_by;

  • reporting: snap_monthly_reports.generated_by (the monthly worker names canopy-reporting);

  • overpayment_claims.discovered_by (snap, tanf, medicaid).

Pair, optional (⇐ 1 + the act predicate)

  • applications: applications.interview_completed_by, rep_disqualifications.cancelled_by, the existing reverted_by;

  • verification: verifications.completed_by, verifications.cancelled_by (the bulk cancel now names its service);

  • renewals: recert_nudges.action_by, pr_redeterminations.action_by;

  • snap: ievs_discrepancies.resolved_by.

Human-only

  • applications: application_documents.accepted_by / rejected_by / scan_override_by, reopen_cure_attestations.attested_by, rep_disqualifications.created_by;

  • web: the composition created_by / archived_by;

  • wic: wic_nutritional_risk_assessments.assessor_worker_id.

    With no writer today: ievs_hits.reviewed_by, ele_consents.revoked_by, snap_change_reports.processed_by, abawd_discretionary_exemption_grants.granted_by, snap_disqualification_screenings.screened_by.

Referent

  • household_assignments.worker_id;

  • appeal_requests.hearing_officer_id;

  • verifications.worker_id.

Invariants

Over the columns above and their wire fields and events:

  • None holds a UUID-projected or nil subject, or a value that fails D1.

  • Every recorded actor is exactly one of a human’s OIDC subject or a named service, and it comes from the bearer or the writing job.

  • No provenance is invented: a row that cannot state its actor is refused, never guessed.

Units — U-A → U-H, one MR

Commit 1 is docs(plans): plan the OIDC subject and typed actors (#1008). The last is docs(plans): close the OIDC subject plan (#1008).

Each unit retypes its service’s columns, contracts, events and clients, and updates every consumer of what it changes, so each commit compiles. Each unit also updates its services' pages under docs/modules/ROOT/pages/api/ and docs/modules/ROOT/pages/data-models/.

U-A (w5) — refactor(common,auth): one OidcSubject type and a typed Actor (#1008)

Files:

  • crates/canopy-common/src/{identity,lib}.rs; crates/canopy-auth/src/{claims,effective_user}.rs, plus every Claims { sub: … } literal and .sub read in the workspace.

  • contracts-facts, contracts-persons and contracts-security, with their persons / snap / security / web worker_directory.rs consumers.

  • ADR-043 amendment (the typed actor, D2/D3) and ADR-046 addendum (opaque subjects in every row; issuer deferred).

Tests:

  • A proptest that D1’s invariant round-trips and refuses empty / over-255-byte / control input.

  • Actor serde and from_columns (both set → error).

  • A malformed stored subject or principal fails Decode.

  • A token with an invalid sub → 401; a System without a valid service: role → 403 from actor().

  • Security’s observation and lookup, and persons' close_author, keep " alice " distinct from "alice".

U-B (w3) — refactor(web): take the session subject as OidcSubject (#2327)

Files: the composition crate (UserId removed); the canopy-web migration (composition_documents.created_by and the archive’s created_by / archived_by in ONE migration); session.rs worker_id: OidcSubject; participation.rs; D8: canopy-web audit/mod.rs resolve_actor and canopy-security event_parsing.rs extract_actor.

Tests:

  • A non-UUID session subject writes and merges the user layer. The stored-session JSON fixture passes unchanged.

  • A human subject spelled System renders as a worker, not "system".

  • An Actor service row renders its principal.

U-C (w8) — refactor(applications): typed actors and body-borne assignees (#2328)

Files:

  • All 14 applications columns (D3/D4): the migration order (including postponement_reverted_pair), the guard, the pair CHECKs.

  • The D5 assignment routes, contracts and events (SectionUpdatedEvent, DocumentScanOverriddenEvent plus canopy-security’s parser, EleConsentRecordedEvent plus medicaid’s subscriber and ele_consents).

  • Consumers: eligibility’s assignments client, enrollment’s AssignmentRow, web participation and the section proxy (D6), test-lib clients, tests/e2e/lib/given/assignments.ts.

Tests:

  • A non-UUID worker end to end: assign, list, the enrollment gate’s AssignmentRow, section edit.

  • Each mandatory pair refuses both and neither.

  • Each optional pair admits neither before the act, and refuses neither once the act predicate holds, and both at any time.

  • A service-reverted postponement converts. The guard raises on a historic system denial and on a nil with no service.

  • A saga revert records Service.

  • A service consent records its service. An old-shape consent event reaches medicaid’s DLQ, not an ack.

U-D (w3) — refactor(eligibility,enrollment): scope reads by OidcSubject (#2329)

Files: eligibility handlers.rs (the scoped route and query, AlertsAccessedV1.effective_worker); enrollment api/{mod,continuations,successors}.rs, events.rs, services/canopy-enrollment/src/clients/mod.rs (the AC-6 gate); the web cross-program-alerts panel and Plugin.toml; test-lib eligibility client; allowlist + typed_ids.rs.

Tests:

  • The resolve matrix, with non_uuid_subject_fails_closed rewritten to pass, and the alerts gate with a non-UUID assigned worker.

  • A reserved-character subject reaches applications encoded.

  • The old paths → 404.

  • Every enrollment human read is audited, including an assigned non-UUID caseworker.

U-E (w5) — refactor(verification,wic,appeals): typed actors and referents (#2330)

Files: verification (the completed_by / cancelled_by pairs, worker_id referent, reviewed_by; store.rs ::UUID casts); WIC (D6 route and request, actions_wic.rs); appeals (referred_by pair + D6 gate, both recorded_by, hearing_officer_id referent; PersonId → OidcSubject); the test-lib conformance entries for changed gates.

Tests:

  • A postponement-saga cancel records Service("canopy-applications").

  • A WIC assessment by an exchanged worker records its subject, a service bearer → 403, and a body assessor is refused.

  • An exchanged IPV referral records the human.

U-F (w5) — refactor(medicaid,snap,tanf): typed actors and the ELE chain (#2331)

Files:

  • Medicaid ele_grant_events pair + D7 and revoked_by.

  • The canonical overpayments discovered_by pair: a new crates/canopy-overpayments template + const + parity test, stamped identically into snap / tanf / medicaid.

  • Snap overpayment_recomputes.requested_by pair (caller_uuid removed), granted_by, screened_by, the ievs_discrepancies pair, in a separate snap-only migration.

Tests: D7’s vectors and collision cases; the guard on existing chain rows; parity; a scheduler lapse records Service("canopy-medicaid"); a non-UUID recompute records the human.

U-G (w3) — refactor(renewals,reporting): action actors from the bearer (#2332)

Files: renewals recert_nudges / pr_redeterminations pairs + D6, processed_by; reporting generated_by; web actions.rs nudge body; conformance entries.

Tests: a body action_by is refused (unknown field). An exchanged redetermination action records the human; a service one records its service.

U-H (w3) — test(seed): seed opaque subjects and document typed actors (#2333)

Files:

  • Seed: model/datagen/sql/manifest. Seed-cast workers that never log in use non-UUID subjects; realm-fixture users keep their realm subjects.

  • tests/e2e/lib/seed.ts.

  • Docs: CHANGELOG, authorization-inventory.adoc, shared-crates.adoc, ADR-027 line 64, guide/supervisor.adoc and runbooks/alerts-scoping-cutover.adoc (the retired routes), tools/canopy-cli docs.

  • OpenAPI (api-docs --update).

Tests: the seed integration suite asserts a non-UUID subject in every retyped table it writes.

Verification

  1. Per unit: fmt, clippy, nextest and quality-budgets in isolated worktrees.

  2. cargo xtask dev restart (the D4 reset), then cargo xtask test --integration --host --no-refresh --skip-static --run-ignored for the touched services.

  3. cargo xtask e2e (it reseeds).

  4. typed-ids audit-path-uuid, route-authz, api-docs --update, then git push. The battery is the gate.

Documentation Updates

  • ADR-043 amendment; ADR-046 addendum.

  • The docs/modules/ROOT/pages/api/ and docs/modules/ROOT/pages/data-models/ pages of every touched service; authorization-inventory.adoc; rbac-matrix.adoc (WIC, IPV and redetermination gates); shared-crates.adoc.

  • CHANGELOG.adoc:

    • Changed: the columns, the routes, Claims.sub, the actor wire shape, the gates.

    • Removed: the two newtypes, UserId, the worker path segments, the body actors.

    • Fixed: section-edit attribution; service writes that recorded no service.

    • The D4 upgrade note: a quiesced drain, then the reset.

  • GitLab: file the out-of-scope follow-ups.

Review log

round vendor resolved model verdict

1 (2026-09-25)

Anthropic

claude-opus-5-5

no-ship — four blockers fixed: commit subjects over 72 characters; the WIC web write claim (its form lacks risk_codes, now a follow-up); pair CHECKs against existing rows (an ordered migration, the administrative_denials backfill, a guard instead of a reopen cutover); the ELE actor_id pair naming.

2 (2026-09-26)

OpenAI

gpt-6-astra

no-ship — 11 findings fixed. A framed ELE hash replaces the ambiguous concatenation (D7). The migration drops lifecycle CHECKs such as postponement_reverted_pair before conversion. Denials take a mandatory pair. No unproven backfill: a guard plus the reset cutover (D4). Subjects are never trimmed. Audit rendering reads actor metadata (D8). Decode validates. actor() is fallible. Durable messages go to the DLQ behind a quiesced upgrade. Optional-pair tests are separated. The completion order satisfies plan-lint --done. No round 3.

Edit this page · default