From ed454f3a008d145a9927a074ba5d81d8e3d0aedd Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 03:02:25 +0300 Subject: [PATCH 01/28] docs(roadmap): close P03-8 delivery after merge Record PR #45's merge, the final-head layout A run beside the failed attempts and the evidence boundaries that stay open: opposite-layout B qualification, manual accessibility and the held contract transition. Mark P03-8 complete in the phase Status block and G12's row, point the ADR-0099 index row at the Status block instead of its commit history, and bring the README's Identity row up to the delivered packets. Point to P03-9 without starting its decision pass. ADR: 0069, 0099 Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- docs/decisions/README.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 76 ++++++++++++++++++++++++- docs/roadmap/phase-03-identity-admin.md | 14 +++-- 4 files changed, 87 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f55fda9e..25c8192e 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ for identity, membership and authorization work; the | Area | Delivered now | Next milestone | |---|---|---| | **Tenancy** | Tenant provisioning, organizations, locales, typed settings/branding reads, host resolution and database isolation, plus bounded organization, default, locale and setting administration | Full organization and settings editors in [Phase 06](docs/roadmap/phase-06-renderer-admin-studio.md) | -| **Identity** | Global User binding, contextual Membership/Profile/Role foundations, live scoped authorization, bounded member directory and trusted denial evidence, protected Studio membership and Role administration, native new-user entry and scope switching, verified invitations with automatic email, and revision-pinned Membership custom values with personal consent | Provider event ingress, back-channel revocation, federation, platform authority and DSAR in [Phase 03](docs/roadmap/phase-03-identity-admin.md) | +| **Identity** | Global User binding, contextual Membership/Profile/Role foundations, live scoped authorization, bounded member directory and trusted denial evidence, protected Studio membership and Role administration, native new-user entry and scope switching, verified invitations with automatic email, revision-pinned Membership custom values with personal consent, authenticated provider-event ingress with a deduplicated tenant Audit mirror, back-channel session revocation, and confined tenant SAML/OIDC federation | Platform authority, operational recovery and DSAR in [Phase 03](docs/roadmap/phase-03-identity-admin.md) | | **Customization** | Content types, level taxonomies, exact-definition and generation-cached batched display readers, text-card metadata validation, finite Membership field definition authoring, create-only provisioning defaults and semantic built-in seed verification | Remaining authoring capabilities across [Phases 04–08a](docs/roadmap/README.md) | | **Audit** | Classified write path and transactional durability for business changes | Operational hardening in [Phase 11](docs/roadmap/phase-11-production-hardening.md) | | **Education** | Course and Lesson aggregates, translations, protected-content policy, scoped authoring commands, complete demo seeds and isolated public GET/HEAD reads | Full versioned curriculum in [Phase 05](docs/roadmap/phase-05-education-learning-content.md) | diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 075fbb2e..53110a3c 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -141,7 +141,7 @@ records hosted qualification. Phase 11 owns production qualification. | 0096 | [P03-5 Administration Contract Baseline](0096-p035-administration-contract-baseline.md) | Accepted 2026-11-10 after maintainer review and development-only/no-active-use confirmation: one exact snapshot/finding/comparator-bound incompatibility, with coordinated consumers and separate runtime/CI proof. Delivery stays in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0097 | [Retained Provider Events and Tenant Audit Mirror](0097-retained-provider-events-and-tenant-audit-mirror.md) | Accepted 2026-11-11 after maintainer review: confined machine intake, finite pull recovery, nonblocking durable problem handling and frozen tenant Audit targets; implementation/qualification stay in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0098 | [Session-Targeted Back-Channel Logout](0098-session-targeted-back-channel-logout.md) | Accepted 2026-11-12 after maintainer review: signed sid-targeted native notification, bounded replay/late-publication fences and owned callback-only TLS reachability; delivery/proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | -| 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation Step 0 (Keycloak pin to 26.7.5) is committed in `ed168594`; Step 1 (registry v4 key, connection aggregate and storage) is committed in `7928fc8b`–`37af223c` with fixes through `30d94bb5`; Step 2 (application operations and API) is committed in `8e435ed6`–`91501770` with round-one and round-two review corrections; Step 3 (egress fetcher, Keycloak adapter and realm invariants) is committed in `d166e12d` with round-one and round-two review corrections; Step 4 (native BFF host binding and `federation_test`, the Studio page and the brokered SAML proof) is committed with round-one and round-two review corrections. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | +| 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation (Steps 0–4, including the Keycloak pin move to 26.7.5) is delivered and merged in PR #45; the [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns packet state. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | | 0100 | [P03-8 Federation Contract Transition](0100-p038-federation-contract-transition.md) | Accepted 2026-11-18 after the maintainer's review, four independent reviews and the development-only/no-active-use confirmation: one exact snapshot-, finding- and comparator-bound incompatibility for registry v4, federation administration and the self `federationAlias`, one carrier per ADR and a stated end of the exception's basis; the later growth of the closed grant contract stays open as G20; delivery and proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | ## Proposed ADRs diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 2adb91db..f47de89a 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -479,7 +479,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-7 hosted repeat failure and closed diagnostic correction (2026-11-12)](#p03-7-hosted-repeat-failure-and-closed-diagnostic-correction-2026-11-12) — 56 lines - [P03-7 faulted test-owner lifetime correction (2026-11-12)](#p03-7-faulted-test-owner-lifetime-correction-2026-11-12) — 73 lines - [P03-7 merge and delivery closeout (2026-11-12)](#p03-7-merge-and-delivery-closeout-2026-11-12) — 89 lines -- [P03-8 — Tenant federation](#p03-8--tenant-federation) — 2,331 lines +- [P03-8 — Tenant federation](#p03-8--tenant-federation) — 2,404 lines - [P03-8 proposed tenant federation package (2026-11-13)](#p03-8-proposed-tenant-federation-package-2026-11-13) — 109 lines - [Maintainer decisions recorded 2026-11-13](#maintainer-decisions-recorded-2026-11-13) — 10 lines - [P03-8 proposal review round one and corrections (2026-11-13)](#p03-8-proposal-review-round-one-and-corrections-2026-11-13) — 40 lines @@ -508,6 +508,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [ADR-0100 maintainer review disposition and acceptance (2026-11-18)](#adr-0100-maintainer-review-disposition-and-acceptance-2026-11-18) — 71 lines - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines + - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines @@ -24092,3 +24093,76 @@ mapper-readback statement and Amendment 9 for the rest. | `python3 scripts/run-realm-node-tests.py` | 13 files, 498 passing tests | | `python3 scripts/test-openapi-ci.py` | 64 tests OK; the other eleven suites in `scripts/` OK; `test-ci-native-provisioning.py` not run | | `make docs-index`, `make lint-docs` | index regenerated; 3,845 fragment links resolve; roadmap structure conforms; delivery log indexes current | + +### P03-8 merge and delivery closeout (2026-11-19) + +The maintainer merges [PR #45](https://github.com/HodeTech/LearnStack/pull/45) at +02:59:14 Europe/Istanbul on 2026-11-19 (23:59:14 UTC on 2026-11-18). Reviewed head +`5eeba2c3` and merge commit `02654275` share tree `d43ee66d`; the merge parents are +`0c7394c7` and `5eeba2c3`. Development fast-forwards to that merge without switching +branches or changing files. + +P03-8 implementation delivery is complete and merged under Accepted ADR-0099 (Amendments +1–9) and the contract transition ADR-0100: D11 is delivered. Steps 0 to 4, their review +rounds, the CI triage, the contract transition and the +[PR review disposition](#p03-8-pr-review-disposition-2026-11-18) are recorded above. +This closeout changes documentation only and selects no new policy or ADR. + +Delivered behavior: + +- A tenant administrator configures one SAML or OIDC identity provider per tenant in + Studio. LearnStack owns the shared Keycloak broker and fixes every trust, flow, mapper + and egress decision; client secrets are write-only and egress is bounded and + address-class checked. +- Provider writes are intent-first and readback-verified: Begin, the provider call + outside any transaction, then Complete, each with its own MUST audit row. A lost write + settles as uncertain and Resume reconciles it. Drift, an expired test window and an + entitlement lapse are corrected at the next readback. +- The lifecycle is Draft, test window, passed test, Active, Disabled and a Deleted + tombstone. The sign-in option appears only for an Active, entitled connection, and + brokered sessions are host-bound at every credential publication path. +- The first-broker flow only links an existing account and creates none. The Keycloak + account console is retired, so no realm user has Keycloak self-service, and the realm + is pinned to 26.7.5 by digest. +- The OpenAPI gate approves the exact reviewed snapshot pair under ADR-0100 and is + isolated from a pull request's own scripts. + +Final-head evidence: + +- [Run 44408689473, attempt 3](https://github.com/HodeTech/LearnStack/actions/runs/44408689473/attempts/3) + passes 27 jobs with two skipped (the bot reviewers), layout **A**, at reviewed head + `5eeba2c3`; every required check is green. Attempt 1 (layout A) failed `ordinary-6`, + `ordinary-10` and the integration aggregate; attempt 2 (layout B) failed `ordinary-11` + and the aggregate. +- The failed shards' `ci-proof` artifacts show the Keycloak fixture start-up timeout + (`readiness_timeout` at `provider_starting`, TLS readiness not completing within 120 + seconds) with the failed cases lasting a millisecond, so no test body ran. The cause + is not localized, and the later pass does not erase the failed attempts. Only those + failed shards' artifacts were read; no original archive set was retained for this + head. +- Merge-triggered main run `44425299178` was queued at this observation and has a + different source identity. +- The local verification of the final tree is in the disposition record's table. + +Evidence boundaries and handoff: + +- No successful opposite-layout B exists on this final head. Final-head A/B + reconciliation remains an open P03-11 evidence follow-up, and the merge does not waive + Testing 06's complete-pair requirement. +- Manual accessibility for the Studio federation page and the sign-in option was not + performed (ADR-0099 C20). The full local Integration and Architecture suites were not + run; hosted CI ran them. +- The served-contract changes held for a new transition decision (the + `clientAuthentication` read-model field, the operation status descriptions and the + bound mismatches), gate G20, the Phase 11 items for the production realm invariants, + pre-registered accounts and the confirm-link copy, and the managed launcher's closed + inventory stay open as the disposition record lists them. + +Next by packet order is P03-9, platform authority and operational recovery (D12/D13, +C14/C15). G13 and G14 are Open and its decision pass must settle them before the first +Platform writer. It also owns the ADR-0099 federation operator steps: the orphan-broker +sweep, the operator disable of a broker the tenant cannot reach and the +delegated-account review. G20 is decided no later than the first packet that adds an +assignable permission key. P03-10 DSAR and global closure, which integrates +`federation_connections` and its broker, and P03-11 exit enforcement remain unstarted. +Phase 03 stays in progress; this closeout starts no next packet. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 74b49ce0..a1375b17 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -1,6 +1,6 @@ # Phase 03: Identity Domain, Authorization, and Admin Foundation -> **Status (2026-11-18).** P03-0 through P03-7 implementation delivery is complete; +> **Status (2026-11-19).** P03-0 through P03-8 implementation delivery is complete; > Phase 03 remains in progress. Packet closeouts below own the delivered scope. > P03-7 is merged in [PR #44](https://github.com/HodeTech/LearnStack/pull/44) under > Accepted [ADR-0098](../decisions/0098-session-targeted-back-channel-logout.md). @@ -18,7 +18,13 @@ > acceptance covers earlier UI, with later fixes also lacking fresh human evidence. > P03-6/P03-7 add no new manual UI gate. Earlier intermittent CI causes remain > unlocalized except where the dated records establish a specific correction. -> P03-8's design is [accepted in ADR-0099](../decisions/0099-confined-tenant-federation.md) and G12 is closed as Accepted. Step 1 (authority and storage) is committed with its first and second review rounds' corrections; Step 0 moved the Keycloak pin to 26.7.5 ([ADR-0099 Amendment 2](../decisions/0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13)); Steps 2 and 3 are committed under their own approvals; Step 4 (native and Studio) is committed with [Amendment 6](../decisions/0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14), its first review round is corrected with [Amendment 7](../decisions/0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) and its second with [Amendment 8](../decisions/0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15). PR #45 is open, its OpenAPI contract transition is [accepted in ADR-0100](../decisions/0100-p038-federation-contract-transition.md) and the hosted pinned approval passed at `cd71cb6d`, and its review findings are corrected with [Amendment 9](../decisions/0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18). P03-9–11 remain unstarted. +> P03-8 is merged in [PR #45](https://github.com/HodeTech/LearnStack/pull/45) under Accepted +> [ADR-0099](../decisions/0099-confined-tenant-federation.md) (Amendments 1–9) and +> [ADR-0100](../decisions/0100-p038-federation-contract-transition.md). Its +> [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) records +> final-head `5eeba2c3` layout A (27/27, attempt 3). Opposite-layout B/pair +> qualification stays open before P03-11 exit; manual accessibility was not performed. +> G12 is closed as Accepted; G20 stays Open. P03-9–11 remain unstarted. > > | Packet | Title | State | > |---|---|---| @@ -30,7 +36,7 @@ > | P03-5 | Custom fields and privacy classification | Complete and merged — [closeout](phase-03-delivery-log.md#p03-5-merge-and-delivery-closeout-2026-11-11); final-head A/B and all original archives verified; manual-evidence boundary retained | > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | -> | P03-8 | Tenant federation | In progress — PR #45 open; its contract transition is [accepted in ADR-0100](../decisions/0100-p038-federation-contract-transition.md), [record](phase-03-delivery-log.md#adr-0100-maintainer-review-disposition-and-acceptance-2026-11-18), and the hosted pinned approval passed at `cd71cb6d`; PR review findings corrected, [record](phase-03-delivery-log.md#p03-8-pr-review-disposition-2026-11-18); Step 4 (native and Studio) implemented, [record](phase-03-delivery-log.md#p03-8-step-4--native-and-studio-2026-11-14); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-4-review-round-1-corrections-2026-11-15); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-4-review-round-2-corrections-2026-11-15); Step 3 (provider and realm) implemented in `d166e12d`, [record](phase-03-delivery-log.md#p03-8-step-3--provider-and-realm-2026-11-14), [commit correction](phase-03-delivery-log.md#p03-8-step-3-commit-and-log-correction-2026-11-14); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-3-review-round-1-corrections-2026-11-14); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-3-review-round-2-corrections-2026-11-14); Step 2 (application and API) implemented, [record](phase-03-delivery-log.md#p03-8-step-2--application-and-api-2026-11-13); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-2-review-round-1-corrections-2026-11-14); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-2-review-round-2-corrections-2026-11-14); Step 1 (authority and storage) implemented, [record](phase-03-delivery-log.md#p03-8-step-1--authority-and-storage-2026-11-13); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-1-review-round-1-corrections-2026-11-13); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-1-review-round-2-corrections-2026-11-13); Step 0 (Keycloak pin to 26.7.5) implemented, [record](phase-03-delivery-log.md#p03-8-step-0--keycloak-pin-move-2026-11-13); Step 0 review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-0-review-round-1-corrections-2026-11-13); its round 2 is recorded in the PR review disposition. Design: [ADR-0099](../decisions/0099-confined-tenant-federation.md) | +> | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | > | P03-9 | Platform authority and operational recovery | Not started | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | @@ -143,7 +149,7 @@ named part, and the register links each explicit acceptance and vehicle. | G9 | How do field definitions and values preserve schema/classification history? | Decide revision pins/active uniqueness, scalar-field compatibility with the existing admitted object profile, nested data, required/default/retire/reclassify/key-reuse behavior, consent and supported localized forms; no raw JSONB bypass | P03-5 before its schema | Customization/privacy contract; ADR-0043 disclosure or successor if needed; module specs | Accepted — 2026-11-10, [ADR-0095](../decisions/0095-revision-pinned-membership-custom-fields.md) and [corrected package](phase-03-delivery-log.md#p03-5-conditional-acceptance-and-step-1-start-2026-11-10); implementation/qualification remain separate | | G10 | What authenticated durable provider ingress is selected, and how are global events attributed? | Name producer, acknowledgement, stable provider-event dedup, ordering, tenantless/multi-membership routing, privacy and retention; enqueue through outbox, never direct business publication; no invented tenant or privileged app consumer | P03-6, or an earlier mechanism needing ingress | Provider-event ADR; ADR-0046/0057 boundaries, exact grants and Audit subscription | Accepted — 2026-11-11, [ADR-0097 and corrections](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11); [delivery and evidence record](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12) | | G11 | Which back-channel token profile, route and session targets are supported? | Separate OIDC purpose validation, signature/issuer/audience/time/events/no-nonce, replay retention, provider/session indexing and reachability; preserve late-work/accounting fences and unrelated/new session owners | P03-7 | ADR-0070 bounded extension; native route/provider configuration package | Accepted — 2026-11-12, [ADR-0098 and reviewed package](phase-03-delivery-log.md#p03-7-maintainer-review-corrections-and-acceptance-2026-11-12); implementation delivery is merged, with final-source evidence and the remaining pair qualification in the [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12) | -| G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation and qualification remain open | +| G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation delivery is merged, with evidence and follow-ups in the [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) | | G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Open for human/operator authority; machine-ingress slice only Accepted — 2026-11-11 under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) and its [acceptance](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11) | | G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Open | | G15 | Who may request which person's data in which tenant/org scope and for which recipient/purpose? | Separate self/admin/delegate authority, subject predicates and org boundaries; category is not disclosure authority; resolve third-party data, holds, eligibility and post-erasure status access | P03-10 request writer | Data Protection/Identity request contract and module matrices | Open | From 24547d5bd47a7cf474a8102557ce08b81d48e873 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 03:43:43 +0300 Subject: [PATCH 02/28] docs(decisions): propose P03-9 operator authority and recovery Draft ADR-0101 (operator authority), ADR-0102 (production onboarding and issuer rebind) and ADR-0103 (operator recovery) with the P03-9 decision package in the Phase 03 delivery log. All are Proposed: no gate closes, no register status changes and no code is authorized until acceptance. Co-Authored-By: Claude Sonnet 5.5 --- .../0101-platform-operator-authority.md | 265 ++++++++++++++++++ ...-tenant-onboarding-and-authority-rebind.md | 198 +++++++++++++ ...-operator-recovery-of-asynchronous-work.md | 209 ++++++++++++++ docs/decisions/README.md | 3 + docs/roadmap/phase-03-delivery-log.md | 140 +++++++++ 5 files changed, 815 insertions(+) create mode 100644 docs/decisions/0101-platform-operator-authority.md create mode 100644 docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md create mode 100644 docs/decisions/0103-operator-recovery-of-asynchronous-work.md diff --git a/docs/decisions/0101-platform-operator-authority.md b/docs/decisions/0101-platform-operator-authority.md new file mode 100644 index 00000000..06322e2f --- /dev/null +++ b/docs/decisions/0101-platform-operator-authority.md @@ -0,0 +1,265 @@ +# ADR-0101: Platform Operator Authority + +## Status + +Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no +Accepted record and authorizes no code until Accepted. Acceptance would close gate G13 +for human operator authority together with +[ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), and would +carry the bounded disclosures listed under +[Carriers owed at acceptance](#carriers-owed-at-acceptance). + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- `DenyAllPlatformAdminGate` refuses everyone, so no cross-tenant act, killswitch + toggle or privileged recovery exists. The gate's only input is a `reason` string, the + scope writes a null actor and null correlation id, and no production caller of + `EnterAsync` exists. A real gate needs a principal, an operation and a permission. +- [ADR-0004 Amendment 1](0004-authentication-strategy.md) places operators in the + separate `learnstack-hub` realm and says tenant routes refuse them. + [ADR-0064](0064-tenant-api-authentication-boundary.md) closes the tenant bearer + scheme to every other issuer and to `scope=platform`. No code authenticates an + operator today, the realm export carries one public client, no audience and no + assurance mapper, and `/api/internal/*` has no endpoint. +- [ADR-0036](0036-tenant-resolution-trusted-inputs.md) routes operator cross-tenant + work through `/api/internal/*` under the Hub chain, while + [ADR-0004](0004-authentication-strategy.md) says that chain is independent of the + operator JWT and uses a service account, and + [ADR-0034](0034-hub-contract-surface-invariant.md) makes any new crossing a + coordinated decision in both repositories. The two readings cannot both hold. +- Every phase from 02d to 11 must work without a Hub + ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), including a Self-Hosted + deployment whose operator is the customer. +- C14 requires a real operator with a specific Platform permission, tenant and + wrong-purpose credentials refused before a bypass connection exists, surviving + human attribution, reason and correlation, and a retained connection that cannot + run autocommit after scope completion. +- [Standard 19](../standards/19-permissions.md) refuses Keycloak roles as authority and + makes Platform definitions never assignable to tenant roles. The pinned OpenAPI gate + ([ADR-0100](0100-p038-federation-contract-transition.md)) refuses every new + assignable key, so the design must not touch the tenant grant union. + +## Considered Options + +1. **A separate strict operator scheme on a LearnStack-owned prefix, grants held by + LearnStack** (chosen). The pinned issuer and audience gate admission; a closed + Platform catalogue and a grant source decide authority per act. +2. **Hub-mediated operator identity on the `/api/internal` chain** (rejected). It + needs a new claim or endpoint, so a coordinated ADR-0034 change in two + repositories. It loses the no-Hub baseline and carries a service identity where + C14 needs a human. +3. **Accept the `learnstack-hub` issuer on the tenant scheme** (rejected). + [ADR-0064](0064-tenant-api-authentication-boundary.md) refuses it and a shared + scheme invites a tenant token into an operator route. +4. **Authority from Keycloak realm or client roles** (rejected). + [Standard 19](../standards/19-permissions.md) forbids it, and a role has no + per-act freshness or audit. +5. **A deployment tool with deployment credentials only** (rejected as the general + mechanism). It gives no verified human attribution. It remains the shape for the + offline act in [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), + which still authenticates the human. + +## Decision + +LearnStack admits one human operator population, authenticated at a pinned operator +issuer, and gates every privileged act on a per-act, LearnStack-held Platform +permission. + +1. **Population.** Operators are LearnStack or deployment staff. The issuer is + `PlatformOperator:Issuer`, by default the `learnstack-hub` realm, and may be any + OIDC issuer a Self-Hosted deployment configures. No service or machine operator is + admitted: the Hub service-account chain carries no operator, and background or + external job frames are refused privileged entry + ([ADR-0047](0047-transactional-background-job-runtime.md)). An operator is never a + `users` row or a tenant member, and a tenant token never admits. +2. **Authentication.** A separate scheme, `PlatformOperator`, validates signature, + exact issuer, audience `learnstack-platform`, an allow-listed public PKCE `azp`, + `typ`, finite `exp` and a lifetime of at most 15 minutes. It exists only when the + issuer is configured; otherwise no operator route is mapped. The tenant scheme + still refuses the operator issuer and the operator scheme refuses the tenant + realm. Roles and any other claim carry no authority. +3. **Assurance.** An act requires the `acr` claim from the operator issuer to be in + `PlatformOperator:AcceptedAcr` and `auth_time` no older than + `PlatformOperator:MaxAuthenticationAge` (default 15 minutes). This names the claim + and the source that [Architecture 13](../architecture/13-identity-and-auth.md) + requires and satisfies [ADR-0099](0099-confined-tenant-federation.md)'s rule that + assurance comes only from LearnStack-controlled authentication. An absent or + unlisted value refuses; no value is inferred from a role. +4. **Surface.** Operator routes live under `/api/platform/v1/*`, outside `/api/v1` + and `/api/internal`. The prefix is unclassified by host, joins the route census, + and is excluded from the pinned tenant document because the document includes + only `/api/v1` paths. A target tenant is named in the route as data and never + populates `ITenantContext`: no route resolves a tenant from a request value + ([ADR-0036](0036-tenant-resolution-trusted-inputs.md)). The operator contract is + served as its own document and is not part of the tenant SDK. +5. **Platform permissions.** Platform definitions live in a separate catalogue. They + are never `Assignable`, never enter `OperationPolicyCatalog` or the tenant grant + union, and the served tenant document stays byte-identical. The closed key set is: + + | Key | Act | Owner | |---|---|---| | `platform.killswitch.write` | Toggle a declared + killswitch | this ADR | | `platform.tenant.write` | Provision a Tenant and default + Organization | ADR-0102 | | `platform.tenant_bootstrap.write` | Role templates, first + admin, recovery | ADR-0102 | | `platform.identity_authority.admin` | Controlled + issuer rebind | ADR-0102 | | `platform.delivery.read` | Inspect dead letters and + quarantined jobs | ADR-0103 | | `platform.delivery.write` | Targeted replay and + narrow producer reset | ADR-0103 | | `platform.federation.read` | Report orphan or + unreadable brokers | ADR-0099 | | `platform.federation.admin` | Operator disable and + orphan removal | ADR-0099 | + + Standard 19 owns the final spelling and the scope table when Step 1 lands. +6. **Grants.** `IPlatformOperatorGrantSource` maps an operator subject key to Platform + keys. The shipped adapter reads configuration, validates every entry against the + catalogue at start, reloads without a restart and is evaluated on every act, never + from claims. A database adapter is demand-gated + ([ADR-0035](0035-demand-gated-infrastructure.md)): its trigger is a need for audited + runtime grant changes, its owning phase is + [Phase 11](../roadmap/phase-11-production-hardening.md), and the Hub operator portal + consumes it. The operator subject key is the base64url SHA-256 of the issuer, a + newline and `sub`; audit rows carry the key, never the raw `sub`. +7. **Admission.** `IPlatformOperatorGate.AdmitAsync(witness, operation, ticket)` + replaces `IPlatformAdminGate.IsPermittedAsync(reason)`. The witness is minted only by + the operator authentication boundary from a validated principal, under a closed + minter census. An operation is a closed registry entry: permission, audit slug, + reason slug and whether it needs the platform role. The reason is that slug. The + ticket is a 1 to 64 character token matching `[A-Za-z0-9._:/#-]`, required for every + write act and carried only in `metadata` and the bounded `reason` column of the + written row. Admission runs before any privileged credential or connection is + resolved. +8. **Scope.** `EnterAsync` takes a `PlatformAdmission` and nothing else. Admission is + required by every operator act; the platform role is entered only by an act that + needs it. The handle exposes no provider connection. Work runs through a bounded + facade, completion and abandonment close the underlying connection, and a reference + captured before completion cannot execute, begin a transaction or reopen. A mutant + test captures such a reference. Entry still refuses job and external frames. +9. **Attribution.** Every row an operator act writes carries `actor_user_id` NULL, the + closed reason slug, the correlation id and `metadata.operator`: subject key, issuer + key, `kind` (`human`), accepted `acr` and the executing component. The shape is a + fixed census, not free text. A tenant-targeted act writes its rows under the real + target tenant so that tenant's administrators see it; the entry row and a + platform-wide act use the platform sentinel. +10. **Result audit.** A MUST result row commits in the transaction that changes the + state. A platform-role act uses a new witness-bound seam on the scope's work + transaction, a second caller of the platform write in + [ADR-0044](0044-audit-write-path.md) § 10. An outbox-role act uses the fenced + witness of [ADR-0103](0103-operator-recovery-of-asynchronous-work.md). An app-role + act uses the ordinary pipeline of + [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md). A forced + audit failure rolls the act back, and an act the audit made unavailable answers 503. +11. **Denied evidence.** A pre-authentication refusal answers 401 with a counter and a + structured log and writes no row + ([ADR-0077](0077-trusted-authorization-evidence.md): a tenantless refusal invents + no tenant). An authenticated operator who lacks the permission, names an unknown + operation or supplies an invalid ticket answers 403 before any connection opens, + with a counter and a Warning log carrying the operation slug and subject key. No + durable denial row is written, because one needs a bypass connection for a refused + caller or a third sentinel class. This ADR records that as the decided evidence. +12. **No-Hub baseline.** The surface depends on the configured issuer and the grant + source only. Development has no permissive gate: its configuration grants the real + pinned `learnstack-hub` demo operator and the proof runs against real Keycloak. + Forwarding an operator identity from the Hub needs its own coordinated ADR. +13. **First consumer: the killswitch writer.** + [ADR-0045 Amendment 1 § 4](0045-entitlement-and-feature-flag-socket.md) withheld it + until a Platform gate existed. It is a service, not a MediatR request, and keeps the + matrix row `tenancy.killswitch.toggle` off-path. It resolves a key only from + `KillswitchKeys.All`, reads the before state, upserts the row with the operator, a + bounded ticket and the time, writes the MUST result row on the work transaction, and + removes the overlay cache entry after commit, including an indeterminate commit. + The runbook states the 60-second cross-instance lag and the overlay's fail-open + read. + +## Context + +The gate was shaped as a refusal on purpose: a permissive Development gate would repeat +the inversion where the demo passes and production refuses. P03-9 now owns the +population that makes the refusal answerable. The corpus supplies three fixed points: +operators live in their own realm, tenant schemes refuse them, and Keycloak roles are +not authority. It supplies two statements that cannot both be true, an operator reaching +LearnStack through the Hub chain and an operator JWT independent of that chain. This ADR +takes the second, because the first needs a Hub crossing that does not exist and cannot +serve the no-Hub baseline. + +A scheme per audience keeps each acceptor class closed. A grant source evaluated per act +gives revocation without a token wait, which a claim cannot. Configuration is enough for +a population of a few staff and keeps the first packet free of a second platform table +and its writer; the port and the trigger make the table a plain addition. The +result-audit seam is the real cost: the entry row commits before the work and records +entry only, so a result row needs the work transaction, which the platform write seam +does not take today. + +What would reopen this: a Hub operator portal that needs delegated operator identity +(an ADR-0034 amendment in both repositories), a need for durable denial evidence from +Phase 11 monitoring, or a service operator for scheduled platform work. + +## Consequences + +### Positive + +- C14's positive and negative controls become provable against real Keycloak, and + Self-Hosted works with no Hub. +- Tenant tokens cannot reach an operator route and operator tokens cannot reach a tenant + route, by two closed schemes and a disjoint prefix. +- The tenant contract does not change, so the OpenAPI gate and G20 are not triggered. +- Attribution survives in every row: who, why, through which assurance, under which + correlation. + +### Negative + +- Two schemes and a second realm client to operate and test, plus one new realm client + and audience mapper in this repository's realm export. +- Configuration grants give no audited runtime grant change until the table adapter. +- No durable denial row: a refused operator leaves a counter and a log only. +- Operators have no browser screen in this repository. The Hub operator portal, which + has not started, is the intended client of the served document. + +### Neutral + +- The scope's handle contract changes. Its only callers are tests today. +- `docs/runbooks/` begins here with operator access and the killswitch, earlier than the + Phase 11 deliverable that names it. + +## Implementation Notes + +- Step 1 delivers the scheme, witness, catalogue, grant source, gate, scope redesign, + result seam, route census, problem mapping, killswitch writer and runbooks. Realm + changes: a `learnstack-platform` audience client, a public PKCE `learnstack-operator` + client with an audience mapper, a token lifetime cap and an ACR-to-level mapping with + step-up. +- The mutation targets are the gate call, its position before connection acquisition, + the admission refusal inside job frames, the closure fence, a null actor and a missing + result row. +- Architecture rules: `PlatformAdminScope_Entry_Requires_Platform_Permission` conjunct B + is rewritten against the real gate, not deleted; SQL on `platform_killswitches` is + confined to the writer; a Platform definition is non-assignable and the tenant + document bytes are unchanged; the minter census of the witness is closed. +- The Platform permission rows start in the + [Tenancy matrix](../modules/tenancy/permissions.md) and the platform operations in its + [audit matrix](../modules/tenancy/audit.md). + +## Carriers owed at acceptance + +Each is a dated disclosure, never a body edit: +[ADR-0004](0004-authentication-strategy.md) (the operator scheme and audience), +[ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the platform URL space), +[ADR-0044](0044-audit-write-path.md) (the second platform write caller and the +`metadata.operator` shape), [ADR-0045](0045-entitlement-and-feature-flag-socket.md) +(the writer's shape), [ADR-0100](0100-p038-federation-contract-transition.md) (a +Platform key is not assignable, so it does not recur the refusal). Standards 04, 11, 18, +19, 21, 12 and 13, Architecture 13 and 28, the glossary and Phase 03 follow. + +## References + +- [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) +- [ADR-0004](0004-authentication-strategy.md), + [ADR-0034](0034-hub-contract-surface-invariant.md), + [ADR-0036](0036-tenant-resolution-trusted-inputs.md), + [ADR-0044](0044-audit-write-path.md), + [ADR-0045](0045-entitlement-and-feature-flag-socket.md), + [ADR-0064](0064-tenant-api-authentication-boundary.md), + [ADR-0077](0077-trusted-authorization-evidence.md) +- [Permission Standards](../standards/19-permissions.md), + [Security Standards](../standards/11-security.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md b/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md new file mode 100644 index 00000000..52071822 --- /dev/null +++ b/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md @@ -0,0 +1,198 @@ +# ADR-0102: Production Tenant Onboarding and Authority Rebind + +## Status + +Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no +Accepted record and authorizes no code until Accepted. Acceptance would close the +production first-admin, provisioning, recovery and issuer-rebind parts of gate G13 +together with [ADR-0101](0101-platform-operator-authority.md). + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) and + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) leave production + first-admin setup and a controlled issuer rebind to P03-9. The fixed seed capability + grants no operator authority, and no production rename path exists. +- `ProvisionTenantCommand` and the identity seed handlers accept only the `Seed` source. + Nothing outside the Seeder, which refuses no deployment mode, creates a Tenant, + its Role templates or a first administrator. Host-to-tenant mappings arrive in + production only through a Hub endpoint that does not exist + ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), so the no-Hub baseline cannot + make a tenant reachable. +- The invariants that make an administrator safe, last-admin protection, the User fence + and ordered membership locks + ([ADR-0074](0074-membership-admission-under-ordered-locks.md)), live in app-role + domain code. A raw write on the platform connection skips them and the audit capture + of [ADR-0044](0044-audit-write-path.md) § 7. +- `identity_authority` is a singleton qualified once at startup. Subject keys hash its + `AuthorityId` ([Database Standards](../standards/05-database.md)), so an issuer change + that alters the id re-keys every person and can resurrect a closed tombstone. +- C14 asks for positive and denied proof, partial-commit proof, unknown-COMMIT + reconciliation and identity continuity, and says seed authority is insufficient. + +## Considered Options + +1. **Operator-admitted acts on the app role through the ordinary pipeline, and an + offline rebind that is still an admitted operator act** (chosen). Invariants, RLS and + audit capture stay where they are proven. +2. **Run onboarding as raw SQL on the platform connection** (rejected). It skips the + last-admin and User invariants and the audit capture, and widens a `BYPASSRLS` role. +3. **Accept the `Seed` source in production** (rejected). The Seeder is a development + tool with fixed identities and no mode refusal. +4. **A platform-issued invitation for the first administrator** (rejected here). It + reuses [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) but needs an + exception for an inviter who holds no membership, and it adds an email dependency to + recovery. +5. **A rebind through an HTTP operator act under a runtime admission freeze** + (rejected). It puts a database read on every authentication and keeps old issuers + alive in running processes, because the qualification is startup-only. + +## Decision + +1. **A confined operator source.** `AuthorizationSourceKind` gains `PlatformOperator`, + minted only from an [ADR-0101](0101-platform-operator-authority.md) admission. The + operator acts below accept that source and no other, and the `Seed` policies stay + `Seed`-only, so neither authority can perform the other's acts. The target tenant is + announced by that source through exactly one new confined setter call in the closed + census, never from a request value, and the platform role is not used. Step 2 fixes + the exact origin value against the code. +2. **The act family.** Four acts, each a `platform.*` permission under ADR-0101: + provision a Tenant with its default Organization and map its hosts through the + existing commands; create the finite Role templates; create the first tenant-wide + administrator Membership; recover a tenant that has none. Tenancy provisioning keeps + its Tenant and default Organization pair. The tenant id is generated by the server + and never chosen by the operator; a retry carries an idempotency key. +3. **Naming the person.** The operator names the first administrator by provider subject + at the identity authority's issuer. The person must already have completed new-user + bootstrap, so a `users` binding exists. A confined single-act resolver maps the + subject to a `UserId`; an unknown subject refuses with a bootstrap-required outcome. + The operator creates no `User`, and an email address is never an identifier. +4. **Separate transactions, resumable.** Provisioning, each Role template and the + Membership commit in their own transactions, as + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) requires. A retry + after partial setup resumes from the first absent step by reading state, with the + pristine-prefix predicates of the Role roots. An unknown COMMIT is reconciled by that + read, never by a blind repeat. Naming a tenant that does not exist, or a person who + is not bootstrapped, refuses before any write. +5. **Recovery.** Recovery uses the same acts and refuses unless, inside the transaction, + the tenant has no active tenant-wide administrator. Its reason slug differs, and the + last-admin invariant is unchanged. The act is not a tenant-administrator escalation + path. +6. **Audit.** Each step writes its MUST row in its own transaction through the ordinary + pipeline, under the real target tenant, with the operator attribution of + [ADR-0101](0101-platform-operator-authority.md) § 9. +7. **Controlled issuer rebind.** The rebind changes only the origin of + `identity_authority.issuer`, under the same realm path. It preserves `AuthorityId`, + subject keys, actor ids and closed tombstones, and no realm rename is admitted. + It is an offline operator act: a new verb of the authority installer tool runs while + the API and worker fleets are stopped, accepts the human's operator access token, + is admitted for `platform.identity_authority.admin`, enters the platform scope, and + writes its MUST result row on that scope's work transaction. +8. **Frozen admission.** The tool refuses unless it holds a session-level exclusive lock + and observes no other session of the application or outbox role. It does not trust an + operator's statement that the fleet is stopped. +9. **Continuity proof.** Before the change, the tool reads the new issuer's discovery + and key set, enumerates every user of the new realm through the realm Admin API with + the deployment's own credential, and hashes each `sub` under the preserved + `AuthorityId` exactly as the binding does. Every active stored subject key must be + present. A closed tombstone key must be absent, so a closed person cannot reappear. + Any miss, or an enumeration that does not complete, refuses. +10. **Database guard.** The platform role receives `UPDATE (issuer)` on + `identity_authority` and nothing else on it. A trigger refuses any other column, + refuses an issuer that breaks the realm grammar and refuses the change unless the + transaction announced the rebind token the tool sets. Processes that start with the + old issuer fail qualification, so a restart with the new configuration is the + unfreeze. +11. **Seed capability.** The Seeder refuses to run when `Deployment:Mode` is not + Development. A test proves the seed source cannot perform an operator act and the + operator source cannot perform a seed act. + +## Context + +Onboarding is not the platform scope's job. The scope exists to cross tenants and write +platform tables, and the platform role bypasses row security. A first administrator is +the opposite case: one tenant, ordinary tables, and the strongest invariants in the +Identity module. Running it on the app role keeps those invariants and the capture of +[ADR-0044](0044-audit-write-path.md) § 7, and costs one new confined source and one new +setter call, which the closed census makes visible and testable. The cost is real: the +source enum, the setter census and the minting rules of the authorization candidate all +change, and the existing negative controls must keep refusing everything else. + +Naming a person by provider subject keeps email out of authority. It asks the person to +sign in once first, which is the same zero-membership entry P03-3 already ships. The +operator reads the `sub` from the issuer's own console, which the operator already +holds. + +The rebind is rare and dangerous, so it is shaped to be hard to do by accident. An HTTP +act would need a runtime freeze on every authentication and still could not retire the +issuer that running processes hold. Offline with a lock, a session check, a continuity +proof and a guarded column makes each claim checkable without touching the hot path. +What the session check cannot see is a process on another database role or another +cluster node that the deployment forgot; the runbook states it. + +The host mapping is included because a tenant that resolves to no host is not onboarded. +It does not widen the Hub contract: the Hub endpoint stays the Hub's, and this act +reuses the existing mapping command. + +What would reopen this: a Hub that pushes provisioning and mappings, a need for a +self-service first administrator, or a realm rename. + +## Consequences + +### Positive + +- No production onboarding depends on the development seed, and a test proves the two + authorities cannot substitute. +- The last-admin and User invariants and the audit capture are unchanged and exercised. +- The rebind is checkable: a continuity set, a lock, a guarded column and a result row. +- The no-Hub baseline can create a reachable tenant with an administrator. + +### Negative + +- A new authorization source kind, a new confined setter call and a new definer-style + resolver widen closed sets that tests currently pin, so each census is edited + deliberately. +- An operator needs the person's `sub` and the person must sign in first. +- A rebind needs a downtime window. + +### Neutral + +- `ProvisionTenantCommand` and the host command gain the operator source beside `Seed`. +- Seeded Development tenants are unaffected. + +## Implementation Notes + +- Step 2 delivers the source, setter call, resolver, acts, routes, rebind verb, guard + migration and canonical SQL, the Seeder mode refusal, and the tenant onboarding and + rebind runbook. The migration changes the grants table in + [Database Standards](../standards/05-database.md) and the pinned grant expectations in + the same commit. +- Proof: positive and denied acts; wrong tenant; unbootstrapped person; interruption + between every pair of steps with a retry that completes once; an unknown COMMIT; the + last-admin invariant after recovery; seed insufficiency in both directions; a rebind + with a missing, extra and tombstoned subject, a live second session and an unchanged + `AuthorityId`. The mutation targets are the source check, the in-transaction no-admin + test, the continuity comparison and the guard trigger. + +## Carriers owed at acceptance + +Dated disclosures in [ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the production path +and the rebind), [ADR-0040](0040-ambient-unit-of-work.md) (the setter +census, if the census is named there), Standards 05 and 19, the Identity and Tenancy +module specifications, the Phase 03 Status and Phase 11 realm items. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) +- [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md), + [ADR-0074](0074-membership-admission-under-ordered-locks.md), + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) +- [Identity module](../modules/identity/README.md), + [Database Standards](../standards/05-database.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md new file mode 100644 index 00000000..3da8e48c --- /dev/null +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -0,0 +1,209 @@ +# ADR-0103: Operator Recovery of Asynchronous Work + +## Status + +Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no +Accepted record and authorizes no code until Accepted. Acceptance would close gate G14 +and, with [ADR-0101](0101-platform-operator-authority.md), decide the dashboard +question that D13 raises. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0046](0046-durable-event-delivery-and-recovery.md) says "operator replay is Phase + 03, with a separately specified reset/fencing contract before any endpoint ships". + `DeliveryDispatchStore.ReplayAsync` exists and has no production caller. It takes no + actor, reason or stale-state token, and writes no audit row, so a second operator can + reset a row a first operator already re-terminalized. +- [ADR-0047](0047-transactional-background-job-runtime.md) keeps a quarantined job + frozen for every role by trigger, retains its reservations, and releases capacity only + on confirmed completion, no-start or quiescence. Operator authority, elapsed time and + a missing worker are not that proof. The only external definition today, invitation + email, ends in `Unknown`, which no operator can turn into proof. +- `learnstack_platform` holds no privilege on inbox, delivery or job tables + ([Data Protection](../architecture/23-data-protection.md)), and the outbox role is + confined by census to the dispatcher. A recovery owner needs a named principal and no + silent widening. +- The Hangfire dashboard needs a browser session on an API with none + ([ADR-0004](0004-authentication-strategy.md)). The runtime's storage runs on the + privileged source, so a dashboard write control reaches past the job fences. The stock + statistics are suppressed ([ADR-0058](0058-bounded-stock-hangfire-maintenance.md)), a + vendor "Succeeded" is not business success, and the runtime pins no dashboard package. + [ADR-0015](0015-api-gateway-apisix.md) still guides a backend filter on the realm role + `platform-admin`, which [Standard 19](../standards/19-permissions.md) forbids. +- C15 requires dashboard and recovery to remain absent until admitted, and then proof of + positive and denied routes, stale fences, producer-versus-subscriber separation, + unchanged siblings, quiescence and reservations, MUST result audit and usable + runbooks. + +## Considered Options + +1. **A fixed inspection and recovery set on a confined outbox-role owner, no dashboard** + (chosen). Every transition carries a stale-state fence, an operator admission and a + same-transaction result row. +2. **Admit the Hangfire dashboard read-only** (rejected now). It adds a package, a + browser session path and a second source borrower, and shows state the runtime says + is not authoritative. Its read-only form shows less than the inspection set below. +3. **Run recovery in the platform scope with new platform grants** (rejected). It widens + a `BYPASSRLS` role on tables that the corpus holds closed, and none of the chosen + acts needs to cross tenants. +4. **Release or requeue quarantined jobs on operator attestation** (rejected). It + supersedes [ADR-0047](0047-transactional-background-job-runtime.md)'s quiescence rule + and would let an unfenced external start run again. +5. **Admit nothing and ship a runbook** (rejected). An exhausted dead letter would have + no remedy, and C15's stale-fence and sibling proofs would have no subject. + +## Decision + +LearnStack admits three operator transitions and a metadata-only inspection, and no +dashboard. + +1. **Inspection.** `platform.delivery.read` returns cursor-paged metadata for + dead-lettered or terminal-requested outbox rows, terminal delivery rows and + quarantined jobs with their reservation occupancy. An explicit column list makes the + projection free of envelope payloads, job parameters, plans and outcomes. Each row + returns the fence its transition needs. +2. **Targeted subscriber replay.** `platform.delivery.write` resets one + `(tenant, subscription, event)` delivery. The request carries the fence read at + inspection: `replay_count`, `dead_lettered_at` and `terminal_reason`. The reset is + refused unless those still match, the row is dead-lettered and unleased, and the + subscription is an Active ordinary one. A completed delivery, its inbox row, every + sibling delivery and the producer row are untouched, and a privileged, unknown or + retired subscription is refused. +3. **Narrow producer reset.** The same permission resets a dead-lettered outbox row + whose `terminal_reason` is `retry_exhausted` and which is not processed, under the + fence `(attempts, dead_lettered_at)`. It clears the terminal fields and the lease, + resets attempts and sets `available_after` to now. `invalid_envelope`, `unknown_type` + and `retired_type` are refused, because an immutable envelope cannot become valid. + The reset deliberately renews the six-attempt budget. A publication that already + reached a subscriber is absorbed by stable event-id acceptance + ([ADR-0046](0046-durable-event-delivery-and-recovery.md): terminal state does not + prove that no subscriber accepted), and the next dispatch reaches every subscription + that is Active now. Producer reset is not a power of subscriber replay: the two are + separate requests with separate fences, and neither writes the other's table. +4. **Principal.** A new confined owner uses the outbox-role credential behind an + [ADR-0101](0101-platform-operator-authority.md) admission. No platform scope is + entered and no grant is added. + `LearnStack_OutboxAdmin_Role_OnlyUsedBy_OutboxProcessor` gains exactly that owner, + `ReplayAsync` moves behind it with its new signature, and no HTTP path reaches the + dispatcher's store. +5. **Result audit.** The row is minted from the fenced `UPDATE ... RETURNING` witness, + the way a terminal witness is, on the same outbox-role transaction. It carries the + real event tenant, the closed reason slug, `metadata.operator` and `metadata.fence` + (before and after). A forced audit failure rolls the transition back and answers 503 + with no state change. A stale fence answers 409 with no change and no row. +6. **Not admitted: job recovery.** No job requeue, retry, probe re-arm, reservation or + capacity release exists. A quarantined job stays frozen, retains its reservation and + keeps `jobs` unhealthy, exactly as + [ADR-0047](0047-transactional-background-job-runtime.md) says. The trigger to admit + one is the first external definition whose adapter can supply provider fencing or + process-tree termination evidence. Its owning phase is the one that ships that + adapter, [Phase 08a](../roadmap/phase-08a-assessment-notifications.md) for + notification providers, with [Phase 11](../roadmap/phase-11-production-hardening.md) + owning operational reconciliation. The invitation path's remedy stays the reissue of + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md). +7. **Not admitted: recurrence recovery.** No recurrence, occurrence or recipient skip, + abandon, pause or resume exists. No production recurrence exists; Phase 11 owns it. +8. **Dashboard.** `/admin/hangfire*` stays unmapped and answers 404 in every deployment + mode, and `BackgroundJob_Runtime_Has_No_Production_Definitions_Or_Dashboard` stays. + The inspection set is the operator's view. A dashboard write control is never + admitted. A read-only dashboard needs its own decision on authentication, the + dependency and the source borrower. +9. **Erasure floor.** No replay floor after erasure is invented here. P03-10 (G16) owns + it and re-verifies these transitions at its first writer. Until then the runbook + forbids replaying an event of a tenant in erasure. +10. **Runbook.** `docs/runbooks/operator-recovery.md` covers the signal, inspection, the + replay-versus-reset choice, what is not recoverable, the invitation reissue path and + how to verify that the row became due and the real executor completed it. + +## Context + +The existing replay is correct in shape and unsafe in use: it checks the row state and +nothing about which state the operator saw. A fence token is the smallest change that +makes a second operator's stale decision refuse instead of act. The producer side is +admitted narrowly because its one recoverable case is real. A burst of dispatch failures +longer than the six-attempt budget strands an event with no remedy, and acceptance is +idempotent by stable identity, so a deliberate redispatch is safe. The three invalid +reasons are not recoverable by any operator and are refused by the same code that proves +the fence. + +Job recovery is left closed because the closing condition is evidence the runtime cannot +get from an operator. That is a real limit, not a deferral for convenience: with a lost +SMTP reply the four tenant invitation slots can stay occupied, and the remedy lives in +the invitation contract. Admitting an attested release would reopen +[ADR-0047](0047-transactional-background-job-runtime.md) and is a decision for the phase +that has a provider able to prove quiescence. + +The dashboard is the one place this ADR departs from the roadmap's wording of D13. The +roadmap says the dashboard is admitted behind the Platform gate. The findings above show +that the gate cannot make it safe: authentication is the wrong shape, and its controls +write around the fences. The inspection set gives the operator the same facts in a +contract this repository owns and tests. + +What would reopen this: a Hub or Phase 11 need for a read-only dashboard, a provider +adapter that supplies quiescence proof, or a measured need to re-arm reconciliation. + +## Consequences + +### Positive + +- C15's stale-fence, sibling, producer-versus-subscriber and audit proofs have real + subjects, with no new grant and no widened bypass role. +- An operator sees exactly what a transition will act on, and a stale decision refuses. +- ADR-0015's false guidance is withdrawn with a dated disclosure. + +### Negative + +- The operator has no dashboard, only an API and a runbook, until a UI exists in the Hub + operator portal. +- A stuck external job has no operator remedy beyond domain-level reissue, which is + [ADR-0047](0047-transactional-background-job-runtime.md)'s rule restated, not + softened. +- The producer reset renews the retry budget and may deliver a historical event to a + subscription activated since. The runbook states both. + +### Neutral + +- [Phase 11](../roadmap/phase-11-production-hardening.md)'s statements that producer + replay and job requeue exist are rewritten as conditional on this ADR. + +## Implementation Notes + +- Step 3 delivers the owner, routes, fences, the two witness-bound seams, census edits, + the ADR-0015 and ADR-0046 disclosures and the runbook. The pinned grant expectations + and the `DeliveryDispatchBoundaryTests` signature census change with the code. +- Proof: a replay with a current fence completes and the real executor runs once; a + stale fence, a completed, live, pending, privileged and retired delivery each refuse; + the sibling, another tenant, another event, the inbox and the producer row are + byte-identical; a reset of each invalid reason and of a processed row refuses; a + forced audit fault leaves no change; a tenant token, a wrong-purpose token and a + different Platform permission fail before the outbox credential is resolved; + `/admin/hangfire` is 404 in every mode; quarantined job rows are byte-identical after + every act. The mutation targets are the fence comparison, the reason filter and the + result row. + +## Carriers owed at acceptance + +Dated disclosures in [ADR-0015](0015-api-gateway-apisix.md) (Amendment 2: the realm-role +gate bullet quoted and withdrawn, the route stays absent), +[ADR-0046](0046-durable-event-delivery-and-recovery.md) (the replay and reset contract), +[ADR-0047](0047-transactional-background-job-runtime.md) (operator reconciliation is +inspection only), [ADR-0044](0044-audit-write-path.md) (the two witness kinds). +[Phase 11](../roadmap/phase-11-production-hardening.md)'s replay and requeue statements, +Standard 20's dashboard line, the Phase 03 D13 wording and the dangling fragment in +[Architecture 30](../architecture/30-api-gateway.md) follow. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md) +- [ADR-0015](0015-api-gateway-apisix.md), + [ADR-0046](0046-durable-event-delivery-and-recovery.md), + [ADR-0047](0047-transactional-background-job-runtime.md), + [ADR-0058](0058-bounded-stock-hangfire-maintenance.md), + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) +- [Event and Outbox](../architecture/15-event-and-outbox.md), + [Data Protection](../architecture/23-data-protection.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G14, D13, C15 diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 53110a3c..2b63cb2a 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -143,6 +143,9 @@ records hosted qualification. Phase 11 owns production qualification. | 0098 | [Session-Targeted Back-Channel Logout](0098-session-targeted-back-channel-logout.md) | Accepted 2026-11-12 after maintainer review: signed sid-targeted native notification, bounded replay/late-publication fences and owned callback-only TLS reachability; delivery/proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation (Steps 0–4, including the Keycloak pin move to 26.7.5) is delivered and merged in PR #45; the [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns packet state. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | | 0100 | [P03-8 Federation Contract Transition](0100-p038-federation-contract-transition.md) | Accepted 2026-11-18 after the maintainer's review, four independent reviews and the development-only/no-active-use confirmation: one exact snapshot-, finding- and comparator-bound incompatibility for registry v4, federation administration and the self `federationAlias`, one carrier per ADR and a stated end of the exception's basis; the later growth of the closed grant contract stays open as G20; delivery and proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | +| 0101 | [Platform Operator Authority](0101-platform-operator-authority.md) | Proposed 2026-11-19: one human operator population at a pinned issuer, a separate strict scheme on `/api/platform/v1`, per-act grants held by LearnStack, an admission witness, attributed result audit and the killswitch writer; closes nothing until Accepted. | +| 0102 | [Production Tenant Onboarding and Authority Rebind](0102-production-tenant-onboarding-and-authority-rebind.md) | Proposed 2026-11-19: operator-admitted tenant, Role-template, first-admin and recovery acts on the app role, and an offline admitted issuer rebind with a continuity proof; closes nothing until Accepted. | +| 0103 | [Operator Recovery of Asynchronous Work](0103-operator-recovery-of-asynchronous-work.md) | Proposed 2026-11-19: metadata inspection, fenced targeted subscriber replay and a narrow producer reset on a confined outbox-role owner; no job release, no dashboard; closes nothing until Accepted. | ## Proposed ADRs diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index f47de89a..9c668aca 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,6 +509,8 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 138 lines + - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines @@ -24166,3 +24168,141 @@ delegated-account review. G20 is decided no later than the first packet that add assignable permission key. P03-10 DSAR and global closure, which integrates `federation_connections` and its broker, and P03-11 exit enforcement remain unstarted. Phase 03 stays in progress; this closeout starts no next packet. + +## P03-9 — Platform authority and operational recovery + +### P03-9 proposed platform authority and recovery package (2026-11-19) + +**Status: Proposed.** The maintainer requests P03-9 through `implement-task` on +`development`, with a review of every existing governing document before +implementation, explicit approval of any new ADR before its dependent code, and every +decision that needs the maintainer shown up front. Each implementation step takes a +commit, a fresh independent review round one, verified fixes and a commit, then a +different fresh review round two, verified fixes and a commit. The work continues +between steps without an unnecessary stop. No Fable model is used. + +The baseline is clean `development` at `ed454f3a`. The request cites a +`docs/roadmap/current.md` that does not exist; the scope below comes from the +[Phase 03](phase-03-identity-admin.md) P03-9 row, gates G13 and G14, deliverables +D12/D13 and criteria C14/C15/C19. This proposal changes no register status, claims no +runtime behavior and authorizes no code. + +#### Problem, document review and decision boundary + +P03-9 delivers the first real Platform authority and the operational recovery that +privileged execution has waited on since Phase 02a. The gate still refuses everyone, no +operator is authenticated anywhere, and production has no tenant, first administrator, +issuer-rebind or recovery path outside the development seed. G13 and G14 are Open. + +Four independent read-only reviews compared the P03-9 text with ADR-0004/0015/0033/ +0034/0035/0036/0044/0045/0046/0047/0058/0064/0070/0072/0073/0074/0076/0077/0093/0097/ +0099/0100, Standards 04/05/11/18/19/20/21, Architecture 13/15/23/28/30, the Identity and +Tenancy module specifications, the realm exports, the Phase 02b/02c/11 text and the +code at `HEAD`. The maintainer's session re-verified the headline findings: the gate +and scope signatures, the null actor and correlation in the entry row, the absence of an +HTTP mapping for `PlatformAdminScopeDeniedException`, the singleton registration, the +absence of any production caller of `EnterAsync` and `ReplayAsync`, the missing +`/admin/hangfire` mapping, the platform role's lack of any grant on +`federation_connections`, and that the tenant OpenAPI document includes only `/api/v1` +paths. The load-bearing findings are: + +| Finding at HEAD | Action | +|---|---| +| ADR-0036 routes operators through `/api/internal` under the Hub chain; ADR-0004 says that chain is independent of the operator JWT | ADR-0101 chooses a direct operator scheme; ADR-0004 and ADR-0036 disclosures | +| Standard 04 writes `/api/v1/platform/...`; ADR-0036 leaves the URL space open | ADR-0101 fixes `/api/platform/v1`; Standard 04 edit | +| Standard 11 says the hub realm serves only the Hub portal | Standard 11 edit under ADR-0101 | +| "A real actor" is claimed for the scope row; the row carries null actor and correlation | ADR-0045 disclosure; matrix rewritten with Step 1 | +| Standard 18 says the scope reason is shown to tenant admins; sentinel rows are tenant-invisible | ADR-0101 § 9 and a Standard 18 clarification | +| The gate has no principal and is a singleton; its comments call permissions absent | ADR-0101 § 7 and § 8; comments corrected in Step 1 | +| ADR-0015 still guides a realm-role dashboard gate | ADR-0103 and ADR-0015 Amendment 2 | +| Phase 11 asserts producer replay and job requeue exist | Conditional rewrite at acceptance | +| D13 says the dashboard is admitted; its safe admission conditions do not hold | ADR-0103 § 8; D13 reworded | +| ADR-0099 defines an orphan as a missing row; delete keeps a tombstone | ADR-0099 Amendment 10 covers absent and `Deleted` rows | +| ADR-0100 expects Platform keys to recur the OpenAPI refusal | A Platform key is non-assignable; disclosure at acceptance | +| The `(planned)` matrix row fails coverage once its slug is registered | Row and registration change in one commit | +| `docs/runbooks/` is a Phase 11 deliverable that does not exist; D12/D13 need runbooks | Created in Step 1; Standards 12 and 13 amended | +| CODEOWNERS is cited as enforcing in four documents; the file is absent | Recorded for G20; not changed here | +| The Seeder refuses no deployment mode | ADR-0102 § 11 | + +#### Choices presented together + +- **Operator authentication.** A separate strict scheme at a pinned issuer, by default + the `learnstack-hub` realm, audience `learnstack-platform`, MFA by `acr`, human + operators only, on `/api/platform/v1/*`. No Hub forwarding and no service operator. +- **Grants.** A port with a configuration adapter, evaluated per act; a table adapter on + a named trigger. Keycloak roles carry no authority. +- **Denied evidence.** A counter and a log, with no durable row, because a durable row + needs a bypass connection for a refused caller or a third sentinel class. +- **Onboarding.** Operator-admitted acts on the app role through the ordinary pipeline: + provision a tenant and map its hosts, create Role templates, create the first + administrator, recover. The person is named by provider subject and must have signed + in once. The platform role is not used. +- **Issuer rebind.** An offline operator act through the installer tool: stopped fleet + checked by a session test, a continuity proof over every stored subject key, a guarded + column and a result row. No HTTP rebind and no runtime freeze. +- **Recovery.** Metadata-only inspection, targeted subscriber replay with a stale-state + fence, and a narrow producer reset limited to `retry_exhausted`, all on a confined + outbox-role owner with no new grant. +- **Not admitted, with owners.** Job requeue and reservation release until a provider + can prove quiescence (Phase 08a, Phase 11); recurrence recovery (Phase 11); every + dashboard form. +- **Federation operator steps.** Admitted as ADR-0099 Amendment 10, written at + acceptance: a separate operator port that lists marker-bearing brokers, reports each + class, removes an orphan or unreadable owned broker and disables a nonconforming + readable one at the provider only, with the row left to the tenant readback. The + platform role gains a column-limited `SELECT` on `federation_connections` (id, tenant, + state, deletion time). The delegated-account review is a runbook, because no + LearnStack credential may enumerate or remove realm users and the brokered link events + expire after seven days. The result rows of a disable or removal name the review as + owed. +- **G20.** Not triggered. Every P03-9 key is a non-assignable Platform key, no tenant + field changes, and the tenant document stays byte-identical. G20 stays Open for the + first assignable key. +- **Operator client.** The served operator document is the contract. This repository + ships no operator screen and no command-line client; the Hub operator portal, not + started, is the intended interface. Runbooks give the exact requests. + +#### Experience, performance and security confirmation + +- **Experience.** Every operator write has a report or inspection first. Responses use + closed Problem Details types with the next step named: stale fence (re-inspect), + bootstrap required (the person signs in first), audit unavailable (retry is safe), + forbidden (which permission). Writes accept an idempotency key. Runbooks carry exact + requests and the expected rows. +- **Performance.** Operator routes are low volume and add nothing to tenant requests: + no admission read on the authentication hot path and no freeze flag. Grants are + in-memory. Inspections are cursor-paged on existing indexes with an enforced page + cap, and the federation listing is paged with a deadline. +- **Security.** Two disjoint schemes and prefixes; admission before any privileged + credential; the platform role only for acts that need it; no raw provider connection + in the scope handle; every result row in the state's transaction; a Seeder mode + refusal. The hazards the reviews found map to the proofs in each ADR. + +#### Four implementation steps after approval + +1. **Operator authority and killswitch.** Realm client and audience, the scheme, + witness, Platform catalogue, grant source, gate, scope redesign, result seam, route + census, problem mapping, the killswitch writer, matrix and Standard 19 rows, and the + operator-access and killswitch runbooks. +2. **Production onboarding and issuer rebind.** The operator source and its setter + call, the resolver, the four acts and routes, the rebind verb with its guard + migration and canonical SQL, the Seeder refusal and the onboarding runbook. +3. **Operational recovery.** The confined owner, inspection, replay and reset with + fences, the two witness seams, census edits, the ADR-0015 and ADR-0046 disclosures + and the recovery runbook. +4. **Federation operator steps.** ADR-0099 Amendment 10, the operator port, report, + removal and disable, the column grant, the adapter route census update and + the federation operator runbook. + +Closeout follows: Status, the register, Phase 11 rewrites and the delivery record. Each +step ends with its own commit, review rounds and verified fixes before the next begins. + +#### Carriers owed at acceptance + +Accepting ADR-0101, ADR-0102 and ADR-0103 would close G13 and G14 and name this package +as their record. Dated disclosures follow in ADR-0004, ADR-0015 (Amendment 2), +ADR-0036, ADR-0040, ADR-0044, ADR-0045, ADR-0046, ADR-0047, ADR-0072, ADR-0073, +ADR-0099 (Amendment 10) and ADR-0100; Standards 04, 05, 11, 12, 13, 18, 19, 20 and 21; +Architecture 13, 28 and 30; the glossary; the Identity and Tenancy module +specifications; and the Phase 03 and Phase 11 documents. This proposal edits none of +them. From a396f50e80558f6933ff193d93932e9a08d9d6f7 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 09:38:21 +0300 Subject: [PATCH 03/28] docs(decisions): accept P03-9 operator ADRs 0101-0104 Accept ADR-0101 (operator authority), 0102 (production onboarding), 0103 (operator recovery) and the new 0104 (controlled issuer rebind) after the maintainer's decisions and three independent reviews, whose dispositions are recorded in the Phase 03 delivery log. Close gates G13 and G14, apply the dated disclosures in the affected Accepted ADRs (including ADR-0099 Amendment 10), correct the standards, architecture, glossary, Tenancy matrix, Phase 03 and Phase 11 text that the decisions made false, and update the CLAUDE.md outbox rule. No code and no behavior change. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 8 +- docs/architecture/13-identity-and-auth.md | 4 +- .../28-platform-tenant-organization.md | 11 +- docs/architecture/30-api-gateway.md | 8 +- .../0003-tenant-isolation-defense-in-depth.md | 13 + .../decisions/0004-authentication-strategy.md | 15 + docs/decisions/0015-api-gateway-apisix.md | 19 + docs/decisions/0033-audit-durability-model.md | 12 + .../0036-tenant-resolution-trusted-inputs.md | 19 + docs/decisions/0040-ambient-unit-of-work.md | 12 + docs/decisions/0044-audit-write-path.md | 20 + ...045-entitlement-and-feature-flag-socket.md | 14 + ...046-durable-event-delivery-and-recovery.md | 14 + ...47-transactional-background-job-runtime.md | 13 + ...0064-tenant-api-authentication-boundary.md | 11 + ...72-application-owned-identity-bootstrap.md | 11 + ...membership-and-identity-data-foundation.md | 12 + ...embership-admission-under-ordered-locks.md | 9 + .../0077-trusted-authorization-evidence.md | 11 + .../0099-confined-tenant-federation.md | 41 ++ ...100-p038-federation-contract-transition.md | 14 + .../0101-platform-operator-authority.md | 359 ++++++++++-------- ...-tenant-onboarding-and-authority-rebind.md | 198 ---------- .../0102-production-tenant-onboarding.md | 209 ++++++++++ ...-operator-recovery-of-asynchronous-work.md | 246 +++++++----- .../0104-controlled-issuer-rebind.md | 185 +++++++++ docs/decisions/README.md | 7 +- docs/glossary.md | 4 +- docs/modules/tenancy/audit.md | 4 +- docs/roadmap/phase-03-delivery-log.md | 129 ++++++- docs/roadmap/phase-03-identity-admin.md | 68 ++-- docs/roadmap/phase-11-production-hardening.md | 29 +- docs/standards/04-api-design.md | 4 +- docs/standards/11-security.md | 11 +- docs/standards/12-infrastructure.md | 4 +- docs/standards/13-documentation.md | 2 +- docs/standards/18-audit-coverage.md | 8 +- docs/standards/19-permissions.md | 9 +- 38 files changed, 1225 insertions(+), 542 deletions(-) delete mode 100644 docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md create mode 100644 docs/decisions/0102-production-tenant-onboarding.md create mode 100644 docs/decisions/0104-controlled-issuer-rebind.md diff --git a/CLAUDE.md b/CLAUDE.md index 68deedb0..9e69f553 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -347,9 +347,11 @@ rules: branches once, modules never. - Write `audit_log`, `platform_entitlement_cache`, or producer `outbox_messages` rows directly — use `IAuditStore`, `IEntitlementProvider.RefreshAsync`, `IOutbox`. - Only ADR-0046's confined dispatcher writes outbox status through fenced - parameterized SQL; its terminal UPDATE and narrow witness-bound audit INSERT - share one transaction. + Only ADR-0046's confined dispatcher and + [ADR-0103](docs/decisions/0103-operator-recovery-of-asynchronous-work.md)'s confined + operator recovery owner write outbox status through fenced parameterized SQL; each + terminal or recovery UPDATE and its narrow witness-bound audit INSERT share one + transaction. - Write `inbox_messages` or `event_deliveries` from a module or Seeder. ADR-0046's transport-owned acceptance, inbox/business owner and confined scheduler alone write their granted columns. diff --git a/docs/architecture/13-identity-and-auth.md b/docs/architecture/13-identity-and-auth.md index 6afee47e..f9e7344c 100644 --- a/docs/architecture/13-identity-and-auth.md +++ b/docs/architecture/13-identity-and-auth.md @@ -453,7 +453,9 @@ MFA is a Keycloak responsibility. Enforced for: - Tenant admin accounts (configurable, defaults to mandatory). - Other roles (tenant choice). -LearnStack does not read the `amr` claim today, and the access-token profile admits no assurance claim. A future MFA-gated operation needs an accepted decision that names its claim and source. Brokered sign-ins carry no LearnStack MFA assurance ([ADR-0099](../decisions/0099-confined-tenant-federation.md)). +LearnStack does not read the `amr` claim today, and the access-token profile admits no assurance claim. A future MFA-gated operation needs an accepted decision that names its claim and source; +[ADR-0101](../decisions/0101-platform-operator-authority.md) names `acr` and `auth_time` from the +deployment-controlled operator issuer for Platform operator acts. Brokered sign-ins carry no LearnStack MFA assurance ([ADR-0099](../decisions/0099-confined-tenant-federation.md)). ## Logout diff --git a/docs/architecture/28-platform-tenant-organization.md b/docs/architecture/28-platform-tenant-organization.md index c44e3b11..18ed4630 100644 --- a/docs/architecture/28-platform-tenant-organization.md +++ b/docs/architecture/28-platform-tenant-organization.md @@ -58,8 +58,11 @@ flowchart TB LearnStack operators manage tenant lifecycle, plans, subscriptions, license issuance, custom domain admin, compliance caps. -LearnStack operators authenticate against the `learnstack-hub` Keycloak realm. They do -**not** have tenant data access; Hub holds tenant metadata only (ADR-0019). +LearnStack operators authenticate against the `learnstack-hub` Keycloak realm. They have +no tenant data access through the Hub, which holds tenant metadata only (ADR-0019). +Platform operator acts on LearnStack itself are permissioned, attributed and audited +([ADR-0101](../decisions/0101-platform-operator-authority.md)), and reach tenant data +only through the operations ADR-0102 to ADR-0104 define. ### Layer 2 — Tenant (LearnStack's customer) @@ -210,8 +213,8 @@ domain-specific shape comes from the tenant's customization data (ADR-0018). ## 5. Hub responsibilities (what LearnStack operators do) -Operators (LearnStack staff) work through Hub. They do **not** access tenant data; they -manage: +Operators (LearnStack staff) work through Hub. The Hub does **not** access tenant data; +they manage: - **Tenant lifecycle**: provision, suspend, archive, terminate. - **Plans & subscriptions**: define plans (features + limits + price), assign to tenants, diff --git a/docs/architecture/30-api-gateway.md b/docs/architecture/30-api-gateway.md index 6369e82e..536737fe 100644 --- a/docs/architecture/30-api-gateway.md +++ b/docs/architecture/30-api-gateway.md @@ -540,10 +540,10 @@ Phase 11 deliverables: - [ ] Per-tenant rate-limit override (consumer keys; requires etcd mode). - [ ] `KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true` for Keycloak issuer split (Docker network vs browser); document in 13-identity-and-auth.md. -- [ ] Hangfire dashboard route gated by BasicAuth at the gateway and the - application's Platform-scope permission; Phase 03 owns the dated ADR-0015 - disclosure before mapping, and Phase 11 owns gateway qualification. - (backend). +- [ ] The Hangfire dashboard stays unmapped + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), ADR-0015 + Amendment 2). Any future admission needs its own decision and a Platform-scope + permission, and Phase 11 owns gateway qualification. - [ ] Production CORS allow-list (no `localhost`). - [ ] OpenAPI dev route gated by environment (404 in prod). - [ ] Real client IP forwarding via `real-ip` configured with trusted L4 LB ranges only. diff --git a/docs/decisions/0003-tenant-isolation-defense-in-depth.md b/docs/decisions/0003-tenant-isolation-defense-in-depth.md index 47f2c844..d051feb0 100644 --- a/docs/decisions/0003-tenant-isolation-defense-in-depth.md +++ b/docs/decisions/0003-tenant-isolation-defense-in-depth.md @@ -600,3 +600,16 @@ global directory or generic bypass is added. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +## Amendment 14 — Confined identity-rebind role (2026-11-19) + +Accepted [ADR-0104](0104-controlled-issuer-rebind.md) adds `learnstack_identity_rebind`, +a sixth login role without `BYPASSRLS`, beside the fifth role of Amendment 13. It is +used only by an offline rebind tool. Its grants are `SELECT` and `UPDATE (issuer)` on +`identity_authority`, `SELECT` of four columns on `users`, and an `INSERT` on +`audit_log` that a policy limits to the platform sentinel, the identity module and the +two rebind operations. Its credential is never configured on an API or worker host. The +grants of the other roles and the canonical policy template are unchanged. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0004-authentication-strategy.md b/docs/decisions/0004-authentication-strategy.md index 362cd080..3f1cdd7a 100644 --- a/docs/decisions/0004-authentication-strategy.md +++ b/docs/decisions/0004-authentication-strategy.md @@ -84,3 +84,18 @@ user under the same identity, and vice versa. ## Amendment 2 — Federation adapter boundary (2026-11-13) Accepted [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds the first runtime Keycloak adapter that writes to the Admin REST API, scoped to tenant-brokered identity-provider configuration. Its port is `IFederationProvider`, not the `IIdentityProvider` named in the Consequences above, which remains unimplemented. The domain depends on no provider type, and the adapter lives in `LearnStack.Infrastructure.Identity.Federation`. Realm-level brokering stays the mechanism of Amendment 1; ADR-0099 specifies its confinement. Tenants receive no realm administration authority. + +## Amendment 3 — Operator scheme at LearnStack (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) admits Amendment 1's operator +on LearnStack. A second bearer scheme, `PlatformOperator`, accepts a token from the +`learnstack-hub` realm, or from another issuer the deployment controls, for audience +`learnstack-platform` and a public PKCE client, with a lifetime of at most 15 minutes +and MFA shown by the `acr` and `auth_time` claims. It requires no `scope: "platform"` +claim and is confined to `/api/platform/v1`, which is what "platform endpoints" means +here. The Hub service-account chain stays independent of the operator JWT, and the +tenant scheme still refuses the operator issuer. Realm-level MFA enforcement stays Phase +11. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0015-api-gateway-apisix.md b/docs/decisions/0015-api-gateway-apisix.md index 9f2b0da2..27f5c082 100644 --- a/docs/decisions/0015-api-gateway-apisix.md +++ b/docs/decisions/0015-api-gateway-apisix.md @@ -310,3 +310,22 @@ replay/reconciliation permission and surface; Phase 11 retains the edge surround Platform protection remains required for any later operator surface. No gateway, permission or recovery route is implemented by this acceptance. + +### Amendment 2 — Hangfire dashboard guidance withdrawn (2026-11-19) + +This amendment quotes and withdraws one bullet of the section "Architecture tests / CI +gates": "Hangfire dashboard route (`/admin/hangfire*`) gated by both APISIX (BasicAuth +or JWT) and backend (`HangfireAuthFilter.IsInRole("platform-admin")`). Architecture test +fails if the backend filter is bypassed in any environment." A realm-role gate +contradicts [Standard 19](../standards/19-permissions.md), the named filter and test do +not exist, and a gateway BasicAuth credential is shared, so it attributes no human. + +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md) replaces it. No dashboard is +mapped and `/admin/hangfire*` stays absent in every deployment mode. Any future +admission needs a Platform-scope permission through the operator gate of +[ADR-0101](0101-platform-operator-authority.md), never a realm role, and its own +decision. Phase 11 keeps the APISIX surround. Amendment 1 is unaffected. This is a +withdrawn design statement, not an ADR-0041 correction. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0033-audit-durability-model.md b/docs/decisions/0033-audit-durability-model.md index a684e47e..717686c2 100644 --- a/docs/decisions/0033-audit-durability-model.md +++ b/docs/decisions/0033-audit-durability-model.md @@ -861,3 +861,15 @@ adds the separately attributed per-occurrence claim-context assertion record; ADR-0065's host allowance does not apply. P03-2 implements/proves this accepted extension before activation. Other durability rules and historical Accepted body/status/date remain unchanged. + +## Amendment 13 — Operator evidence in authorization audit composition (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds `PlatformOperator` as a +source of the authorization audit context. For that source the composition admits a null +actor, a closed reason slug and the fixed `metadata.operator` members of +[ADR-0101](0101-platform-operator-authority.md), as it admits a null actor only for the +seed source today. The in-transaction rule is unchanged: an operator act on the app role +writes its MUST rows in its own transaction under the real target tenant. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0036-tenant-resolution-trusted-inputs.md b/docs/decisions/0036-tenant-resolution-trusted-inputs.md index fd8a4551..7e4dc489 100644 --- a/docs/decisions/0036-tenant-resolution-trusted-inputs.md +++ b/docs/decisions/0036-tenant-resolution-trusted-inputs.md @@ -1406,3 +1406,22 @@ origin inferred from provider data. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +### Amendment 21 — Platform URL space and confined operator target (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) fixes the platform URL space +this record left open: `/api/platform/v1/*`, unclassified by host like `/api/internal` +and authenticated by the operator scheme. This record's sentence that operator +cross-tenant work enters through `/api/internal/*` under the Hub chain is read as the +Hub's machine chain only, which carries no human operator. A human operator act uses the +platform prefix. + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds one announcement: the +target tenant of an admitted operator act, declared by the operation and never taken +from a header, query, cookie or body of an ordinary route, is announced to the unit of +work by one confined setter. The rule that no route resolves a tenant from a +request-supplied override stands for every route that resolves context from a host or a +claim. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0040-ambient-unit-of-work.md b/docs/decisions/0040-ambient-unit-of-work.md index 7c4e7049..42400b75 100644 --- a/docs/decisions/0040-ambient-unit-of-work.md +++ b/docs/decisions/0040-ambient-unit-of-work.md @@ -1002,3 +1002,15 @@ reader, outside that connection and its announcement. That read is no setter sta and writes nothing. Amendment 22's text is unchanged; the P03-8 Step 4 review round 2 (C5-4) in the [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md) records the finding. + +### Amendment 24 — Eleventh logical setter: operator target (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds the eleventh logical +tenant setter, confined to the `PlatformOperator` source. It reads the target of an +admitted operation, announces it once per unit of work and refuses any other caller. The +four context writers do not change. The single-act resolver that maps a provider subject +to a `UserId` is a ninth definer function; its signature, owner, body and ACL land in +[Standard 05](../standards/05-database.md) with the packet that ships it. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index d2815d6b..029d4087 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1309,3 +1309,23 @@ with SystemActor distinct from the affected subject and provider outcome. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +## Amendment 17 — Platform operator rows and witness-bound result writes (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md), +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](0104-controlled-issuer-rebind.md) extend the seams of Amendment 14 by name: + +- The platform-scope class of § 1 includes a platform-wide MUST result row written on + the scope's work transaction through a new witness-bound method. + `WritePlatformScopeAsync` keeps its single entry-row caller and the § 10 entry-row + rule. +- Operator audit rows carry `actor_user_id` NULL, a closed reason slug, the correlation + id and `metadata.operator` with `issuer`, `subjectDigest`, `kind`, `acr` and + `executor`. The ticket appears only in sentinel-tenant rows. `AuditEntryDraft.Reason` + stays a closed slug. +- Two outbox-role witness kinds for targeted replay and producer reset, distinct from + the terminal witness, and two rebind methods for `learnstack_identity_rebind`. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0045-entitlement-and-feature-flag-socket.md b/docs/decisions/0045-entitlement-and-feature-flag-socket.md index 3ea754b7..2bfeab9e 100644 --- a/docs/decisions/0045-entitlement-and-feature-flag-socket.md +++ b/docs/decisions/0045-entitlement-and-feature-flag-socket.md @@ -623,6 +623,20 @@ against the `platform_entitlement_cache` columns Packet 6 created. which records the mapping; and `EntitlementProjection`'s remarks in `IEntitlementProvider.cs`. No other Accepted ADR's body changes. +## Amendment 5 — Killswitch writer shape (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) § 13 lifts the withholding of +Amendment 1 § 4 once the writer ships. It is a service entered through the Platform +gate, not a MediatR request. `toggled_by` stays NULL because an operator is not a +`users` row, the bounded ticket goes in the `reason` column, the MUST result row commits +on the work transaction, and the overlay cache entry is removed after the commit, +including an indeterminate one. Section 5's statement that the scope gives the row a +real actor is read as the `metadata.operator` attribution; the shipped scope writes a +null actor. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + ## References - [ADR-0021 Feature-Based Entitlement Model](0021-feature-based-entitlement.md) diff --git a/docs/decisions/0046-durable-event-delivery-and-recovery.md b/docs/decisions/0046-durable-event-delivery-and-recovery.md index 04d4f535..6edc825c 100644 --- a/docs/decisions/0046-durable-event-delivery-and-recovery.md +++ b/docs/decisions/0046-durable-event-delivery-and-recovery.md @@ -524,6 +524,20 @@ general exemption. The producer/subscriber delivery policy, five existing audit writes and their shipped receipts remain unchanged. P02b-4 implements the new job control/seam and their proof obligations; acceptance claims no job runtime. +### Amendment 5 — Operator replay and reset contract (2026-11-19) + +Accepted [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) supplies the +"separately specified reset/fencing contract" this record requires before any operator +replay ships. Two transitions run on a confined owner that uses the outbox-role +credential and is a second status writer beside the dispatcher: targeted subscriber +replay, fenced and filtered by terminal reason, and a producer reset limited to +`retry_exhausted`. Neither adds a write grant. "Permanently excluded from dispatch" is +read as: until an operator reset under that record. Result audit uses two new witness +kinds. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + ## References - [ADR-0006](0006-events-and-outbox.md), [ADR-0010](0010-cross-module-communication.md) diff --git a/docs/decisions/0047-transactional-background-job-runtime.md b/docs/decisions/0047-transactional-background-job-runtime.md index 43c89278..f4e69e8f 100644 --- a/docs/decisions/0047-transactional-background-job-runtime.md +++ b/docs/decisions/0047-transactional-background-job-runtime.md @@ -1030,3 +1030,16 @@ source/operation/permission/audit/storage details live in Standards 01/04/05/07/11/18/19/20/21 and the Identity/Tenancy specifications. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and source-bound qualification; acceptance supplies no runtime proof. + +### Amendment 7 — Operator reconciliation is inspection only (2026-11-19) + +Accepted [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) reads the "audited +operator reconciliation" that Phase 03 owns as metadata inspection only. No job requeue, +retry, probe re-arm or reservation release exists, quarantine stays nonterminal with +retained reservations, and no dashboard is mapped. For inspection, `learnstack_platform` +receives `SELECT` on named metadata columns of the job tables; this record's statement +that the platform role has no job privileges is read as applying to every other column +and to every write. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0064-tenant-api-authentication-boundary.md b/docs/decisions/0064-tenant-api-authentication-boundary.md index 78dbc525..908c942a 100644 --- a/docs/decisions/0064-tenant-api-authentication-boundary.md +++ b/docs/decisions/0064-tenant-api-authentication-boundary.md @@ -707,3 +707,14 @@ qualification; acceptance supplies no runtime proof. ### Amendment 8 — Federation adapter outside the API bearer boundary (2026-11-13) P02b-5 introduced no Keycloak admin adapter. [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds one, `IFederationProvider`, confined to tenant-brokered identity-provider configuration. It uses a dedicated confidential client with `manage-identity-providers` only, admits a closed list of calls, and grants no tenant authority. The tenant API bearer boundary and the closed access-token profile are unchanged. Brokered ID tokens carry an `idp` claim that the BFF reads only for provenance and host binding; it is not an API authorization input. + +### Amendment 9 — Second scheme confined to the operator prefix (2026-11-19) + +"Register exactly one bearer scheme for the tenant API" stands: the tenant scheme is the +only scheme on `/api/v1`. Accepted [ADR-0101](0101-platform-operator-authority.md) +registers a second scheme, `PlatformOperator`, confined to `/api/platform/v1`. It never +authenticates a tenant route, and the tenant scheme still refuses the operator issuer +and `scope=platform`. "Platform execution remains unavailable to this scheme" stands. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0072-application-owned-identity-bootstrap.md b/docs/decisions/0072-application-owned-identity-bootstrap.md index 26e17c90..56b77368 100644 --- a/docs/decisions/0072-application-owned-identity-bootstrap.md +++ b/docs/decisions/0072-application-owned-identity-bootstrap.md @@ -401,3 +401,14 @@ and qualification; acceptance alone installs no runtime subject. ### Amendment 5 — Federation adapter does not allocate identity (2026-11-13) Amendment 2 mentions no runtime provider administrator in the context of identity allocation. [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds a runtime provider adapter for tenant-brokered identity-provider configuration. It allocates no identity, reissues no subject and merges no email. The rejection of a provider allocator or runtime Admin API for identity allocation in Option 2 stands. A brokered person without a LearnStack binding enters through the existing global-self path and its opt-in budgets. + +### Amendment 6 — Production path and controlled rebind (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) supplies the production path +for tenant, host, Role-template and first-administrator setup, and Accepted +[ADR-0104](0104-controlled-issuer-rebind.md) supplies the controlled issuer rebind. +Rename stays unsupported until the packet that ships the rebind merges. The seed stays a +development tool, and the Seeder refuses to run outside Development. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md index 3cccd6b2..15af69d3 100644 --- a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md +++ b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md @@ -406,3 +406,15 @@ owns persistence, isolation and commit-spanning fences. Historical Accepted body, Status, Date, Deciders and prior rationale remain unchanged. Acceptance registers the bounded contract; actual P03-5 implementation and source-bound proof remain owned by the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). + +### Amendment 8 — Production first administrator and recovery (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) admits operator commands for +the first tenant-wide administrator and for recovery. Separate transactions stay. The +first-admin predicate, no Membership history, differs from the recovery predicate, no +active tenant-wide administrator, and both run under the ordered locks of +[ADR-0074](0074-membership-admission-under-ordered-locks.md). The statement that the +fixed seed capability grants no operator or system bypass stands. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0074-membership-admission-under-ordered-locks.md b/docs/decisions/0074-membership-admission-under-ordered-locks.md index 3bc777e8..75168c8c 100644 --- a/docs/decisions/0074-membership-admission-under-ordered-locks.md +++ b/docs/decisions/0074-membership-admission-under-ordered-locks.md @@ -244,3 +244,12 @@ or strongest-plan/no-upgrade rule. Historical Accepted body, Status, Date, Deciders and prior rationale remain unchanged. Acceptance registers the bounded contract; actual P03-5 implementation and source-bound proof remain owned by the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). + +### Amendment 2 — Operator recovery predicate under the ordered locks (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) evaluates its recovery +predicate, no active tenant-wide administrator, inside the transaction and under this +record's ordered locks, not as a prior check. The lock order is unchanged. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0077-trusted-authorization-evidence.md b/docs/decisions/0077-trusted-authorization-evidence.md index 2470ed36..c6ebf218 100644 --- a/docs/decisions/0077-trusted-authorization-evidence.md +++ b/docs/decisions/0077-trusted-authorization-evidence.md @@ -379,3 +379,14 @@ provenance or generalized evidence dictionary. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +### Amendment 2 — Operator admission denials (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) § 11 places denials of Platform +operator admission outside this record's typed denial event population. They are +tenantless, and this record's rule that a tenantless refusal invents no tenant and uses +no platform sentinel stands. Their evidence is a counter and a Warning log. The +reopening trigger is Phase 11 security monitoring that requires durable denial evidence. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index 50f8c68e..734e7336 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1077,3 +1077,44 @@ Decision is unchanged. The [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md#p03-8-pr-review-disposition-2026-11-18) holds the review record, each finding's disposition and its proof. + +### Amendment 10 — Federation operator steps (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) admits the operator steps this +record assigns to P03-9. The operator acts through a separate port, +`IFederationOperator`, held only by the operator service and never by the tenant runner, +so the rule that the provider port is held only by the runner stands. It uses the same +`learnstack-federation-admin` client and adds no realm authority. The admitted routes +grow from four to five by one paged listing of identity-provider instances. + +1. **Classes.** An alias that starts with `lsf-` and whose owner marker parses to a + tenant and connection is classified. An *orphan* has no live row: the row is absent + or a `Deleted` tombstone, so the text "its connection row was removed" is read that + way. An *unreadable owned* broker carries the marker but reads as foreign. A + *nonconforming* broker is readable and owned but has an extra mapper or a changed + profile (Amendment 9 item 5). An unmarked or marker-mismatched broker is never + touched. +2. **Report.** `platform.federation.read` reads the realm list first, then the rows, and + writes nothing. Reading the rows first would manufacture false orphans. +3. **Remove.** `platform.federation.admin` deletes an orphan or an unreadable owned + broker by its alias after re-reading its row immediately before the delete, and + refuses if a live row exists. Deleting an absent broker is applied. The provider's + deletion also removes the federated links, and the runbook says so. +4. **Disable.** The same permission sets `enabled=false` on a nonconforming broker, or + on one the tenant cannot reach, at the provider only and marker-proven. The row is + left to the tenant's next readback, which corrects it; until then the sign-in option + fails closed. +5. **Rows read.** `learnstack_platform` receives `SELECT` of `id`, `tenant_id`, `state` + and `deleted_at` on `federation_connections`, pinned by a column-privilege test. +6. **Audit.** Each remove or disable writes a MUST intent row before the provider call + and a completion row after it, as Amendment 2 does for the tenant path, under the + real tenant, with a closed reason slug, `metadata.operator` and a follow-up note that + an account review is owed. A lost completion is found by the next report. +7. **Account review.** It is a runbook step. No LearnStack credential may enumerate or + remove realm users (Decision Q1), Keycloak keeps link events for seven days and no + owner notification channel exists before Phase 08a. +8. **Residual.** No provider-side fence exists, so a tenant create that lands after a + sweep produces a new orphan, which the next report finds. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0100-p038-federation-contract-transition.md b/docs/decisions/0100-p038-federation-contract-transition.md index 38fb7e5f..ae7f0720 100644 --- a/docs/decisions/0100-p038-federation-contract-transition.md +++ b/docs/decisions/0100-p038-federation-contract-transition.md @@ -370,6 +370,20 @@ or a failed comparison never creates success. `PublicSurface_Contract_Matches_Served_OpenApi` and the actual response and authority parsers are preserved. +## Amendments + +### Amendment 1 — A Platform key does not recur the refusal (2026-11-19) + +The Decision Drivers expect the permission keys of later modules, Platform among them, +to recur the refusal. Accepted [ADR-0101](0101-platform-operator-authority.md) registers +Platform definitions as non-assignable in a separate catalogue. They never enter the +administration grant union, so they change neither the tenant document nor this +mechanism, and they do not trigger gate G20. G20 stays Open for the first assignable +key. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + ## References - [ADR-0024](0024-api-versioning-policy.md), [ADR-0040](0040-ambient-unit-of-work.md) diff --git a/docs/decisions/0101-platform-operator-authority.md b/docs/decisions/0101-platform-operator-authority.md index 06322e2f..fb44de8a 100644 --- a/docs/decisions/0101-platform-operator-authority.md +++ b/docs/decisions/0101-platform-operator-authority.md @@ -2,65 +2,67 @@ ## Status -Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no -Accepted record and authorizes no code until Accepted. Acceptance would close gate G13 -for human operator authority together with -[ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), and would -carry the bounded disclosures listed under -[Carriers owed at acceptance](#carriers-owed-at-acceptance). +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes gate G13 for human operator authority together with +[ADR-0102](0102-production-tenant-onboarding.md) and +[ADR-0104](0104-controlled-issuer-rebind.md), and authorizes the code it describes. It +is not proof that anything is implemented. **Date:** 2026-11-19 **Deciders:** @cemil ## Decision Drivers -- `DenyAllPlatformAdminGate` refuses everyone, so no cross-tenant act, killswitch - toggle or privileged recovery exists. The gate's only input is a `reason` string, the - scope writes a null actor and null correlation id, and no production caller of - `EnterAsync` exists. A real gate needs a principal, an operation and a permission. +- `DenyAllPlatformAdminGate` refuses everyone, so no cross-tenant act, killswitch toggle + or privileged recovery exists. The gate's only input is a `reason` string, both the + gate and the scope are singletons, the entry row writes a null actor and a null + correlation id, and `EnterAsync` has no production caller. A real gate needs a + principal, an operation and a permission. - [ADR-0004 Amendment 1](0004-authentication-strategy.md) places operators in the separate `learnstack-hub` realm and says tenant routes refuse them. - [ADR-0064](0064-tenant-api-authentication-boundary.md) closes the tenant bearer - scheme to every other issuer and to `scope=platform`. No code authenticates an - operator today, the realm export carries one public client, no audience and no - assurance mapper, and `/api/internal/*` has no endpoint. -- [ADR-0036](0036-tenant-resolution-trusted-inputs.md) routes operator cross-tenant - work through `/api/internal/*` under the Hub chain, while - [ADR-0004](0004-authentication-strategy.md) says that chain is independent of the - operator JWT and uses a service account, and - [ADR-0034](0034-hub-contract-surface-invariant.md) makes any new crossing a - coordinated decision in both repositories. The two readings cannot both hold. + [ADR-0064](0064-tenant-api-authentication-boundary.md) registers exactly one bearer + scheme for the tenant API and refuses every other issuer and `scope=platform`. No code + authenticates an operator, the realm export carries one public client with no audience + mapper and no assurance mapper, and `/api/internal/*` has no endpoint. +- [ADR-0036](0036-tenant-resolution-trusted-inputs.md) routes operator cross-tenant work + through `/api/internal/*` under the Hub chain. + [ADR-0034](0034-hub-contract-surface-invariant.md) and ADR-0004 define that chain as + machine-to-machine under a Hub service identity. It carries no human operator, so it + cannot supply C14's human attribution, and changing it is a coordinated decision in + two repositories. - Every phase from 02d to 11 must work without a Hub ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), including a Self-Hosted deployment whose operator is the customer. - C14 requires a real operator with a specific Platform permission, tenant and - wrong-purpose credentials refused before a bypass connection exists, surviving - human attribution, reason and correlation, and a retained connection that cannot - run autocommit after scope completion. + wrong-purpose credentials refused before a bypass connection exists, surviving human + attribution, reason and correlation, and a retained connection that cannot run + autocommit after the scope completes. - [Standard 19](../standards/19-permissions.md) refuses Keycloak roles as authority and makes Platform definitions never assignable to tenant roles. The pinned OpenAPI gate - ([ADR-0100](0100-p038-federation-contract-transition.md)) refuses every new - assignable key, so the design must not touch the tenant grant union. + ([ADR-0100](0100-p038-federation-contract-transition.md)) refuses every new assignable + key, so the design must not touch the tenant grant union. ## Considered Options 1. **A separate strict operator scheme on a LearnStack-owned prefix, grants held by LearnStack** (chosen). The pinned issuer and audience gate admission; a closed Platform catalogue and a grant source decide authority per act. -2. **Hub-mediated operator identity on the `/api/internal` chain** (rejected). It - needs a new claim or endpoint, so a coordinated ADR-0034 change in two - repositories. It loses the no-Hub baseline and carries a service identity where - C14 needs a human. +2. **Hub-mediated operator identity on the `/api/internal` chain** (rejected). It needs + a new claim or endpoint, so a coordinated ADR-0034 change in two repositories. It + loses the no-Hub baseline and carries a service identity where C14 needs a human. 3. **Accept the `learnstack-hub` issuer on the tenant scheme** (rejected). - [ADR-0064](0064-tenant-api-authentication-boundary.md) refuses it and a shared + [ADR-0064](0064-tenant-api-authentication-boundary.md) refuses it, and a shared scheme invites a tenant token into an operator route. 4. **Authority from Keycloak realm or client roles** (rejected). - [Standard 19](../standards/19-permissions.md) forbids it, and a role has no - per-act freshness or audit. + [Standard 19](../standards/19-permissions.md) forbids it, and a role has no per-act + freshness or audit. 5. **A deployment tool with deployment credentials only** (rejected as the general - mechanism). It gives no verified human attribution. It remains the shape for the - offline act in [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), - which still authenticates the human. + mechanism). It gives no verified human attribution. The offline rebind of + [ADR-0104](0104-controlled-issuer-rebind.md) is a tool, but it authenticates the + human through this ADR's scheme. ## Decision @@ -69,93 +71,118 @@ issuer, and gates every privileged act on a per-act, LearnStack-held Platform permission. 1. **Population.** Operators are LearnStack or deployment staff. The issuer is - `PlatformOperator:Issuer`, by default the `learnstack-hub` realm, and may be any - OIDC issuer a Self-Hosted deployment configures. No service or machine operator is - admitted: the Hub service-account chain carries no operator, and background or - external job frames are refused privileged entry + `PlatformOperator:Issuer`, by default the `learnstack-hub` realm, and is always an + issuer the deployment controls, never a tenant-configured or brokered provider. No + service or machine operator is admitted: the Hub service-account chain carries no + operator, and background or external job frames are refused privileged entry ([ADR-0047](0047-transactional-background-job-runtime.md)). An operator is never a `users` row or a tenant member, and a tenant token never admits. -2. **Authentication.** A separate scheme, `PlatformOperator`, validates signature, +2. **Authentication.** A second bearer scheme, `PlatformOperator`, validates signature, exact issuer, audience `learnstack-platform`, an allow-listed public PKCE `azp`, - `typ`, finite `exp` and a lifetime of at most 15 minutes. It exists only when the - issuer is configured; otherwise no operator route is mapped. The tenant scheme - still refuses the operator issuer and the operator scheme refuses the tenant - realm. Roles and any other claim carry no authority. -3. **Assurance.** An act requires the `acr` claim from the operator issuer to be in - `PlatformOperator:AcceptedAcr` and `auth_time` no older than + `typ` and a finite `exp`, and refuses a token whose `exp - iat` exceeds 15 minutes. + It requires no `scope` claim: audience, client and assurance carry the purpose. The + scheme is bound to the operator prefix and the tenant scheme remains the only scheme + on `/api/v1`. The tenant scheme refuses the operator issuer and the operator scheme + refuses the tenant realm. Roles and any other claim carry no authority. +3. **Assurance.** An act requires the `acr` claim to be in + `PlatformOperator:AcceptedAcr` and `auth_time` to be no older than `PlatformOperator:MaxAuthenticationAge` (default 15 minutes). This names the claim - and the source that [Architecture 13](../architecture/13-identity-and-auth.md) - requires and satisfies [ADR-0099](0099-confined-tenant-federation.md)'s rule that - assurance comes only from LearnStack-controlled authentication. An absent or - unlisted value refuses; no value is inferred from a role. -4. **Surface.** Operator routes live under `/api/platform/v1/*`, outside `/api/v1` - and `/api/internal`. The prefix is unclassified by host, joins the route census, - and is excluded from the pinned tenant document because the document includes - only `/api/v1` paths. A target tenant is named in the route as data and never - populates `ITenantContext`: no route resolves a tenant from a request value - ([ADR-0036](0036-tenant-resolution-trusted-inputs.md)). The operator contract is - served as its own document and is not part of the tenant SDK. -5. **Platform permissions.** Platform definitions live in a separate catalogue. They - are never `Assignable`, never enter `OperationPolicyCatalog` or the tenant grant - union, and the served tenant document stays byte-identical. The closed key set is: + and source that [Architecture 13](../architecture/13-identity-and-auth.md) requires, + and [ADR-0099](0099-confined-tenant-federation.md)'s rule that assurance comes only + from LearnStack-controlled authentication holds because the issuer is + deployment-controlled. An absent or unlisted value refuses. A Self-Hosted issuer must + emit `acr` and `auth_time` as the runbook specifies, or no operator can act. +4. **Surface.** Operator routes live under `/api/platform/v1/*`. The prefix is added to + `VersionedRouteConvention.UnversionedRoutePrefixes` and to the host-classification + prefixes beside `/api/internal`, joins its own route census and + `OperationHttpClassifier` entries, and is served as its own OpenAPI document, outside + the pinned tenant document and the tenant SDK. The controllers are present only when + the issuer is configured, and a test proves absence otherwise. The gateway scaffold + routes no `/api/platform` path; exposing it is a Phase 11 decision. A target tenant + is data of the act and populates `ITenantContext` only through the confined + announcement of [ADR-0102](0102-production-tenant-onboarding.md) § 1; no ordinary + route resolves a tenant from a request value + ([ADR-0036](0036-tenant-resolution-trusted-inputs.md)). +5. **Platform permissions.** Platform permission definitions live in a separate + catalogue. They are never `Assignable`, never enter the tenant grant union, and the + served tenant document stays byte-identical. Trusted operator policies may exist + beside it. The closed key set this ADR family registers is: - | Key | Act | Owner | |---|---|---| | `platform.killswitch.write` | Toggle a declared - killswitch | this ADR | | `platform.tenant.write` | Provision a Tenant and default - Organization | ADR-0102 | | `platform.tenant_bootstrap.write` | Role templates, first - admin, recovery | ADR-0102 | | `platform.identity_authority.admin` | Controlled - issuer rebind | ADR-0102 | | `platform.delivery.read` | Inspect dead letters and - quarantined jobs | ADR-0103 | | `platform.delivery.write` | Targeted replay and - narrow producer reset | ADR-0103 | | `platform.federation.read` | Report orphan or - unreadable brokers | ADR-0099 | | `platform.federation.admin` | Operator disable and - orphan removal | ADR-0099 | + | Key | Acts | Owner | + |---|---|---| + | `platform.killswitch.write` | Toggle a declared killswitch | this ADR | + | `platform.tenant.write` | Provision a Tenant and map its hosts | ADR-0102 | + | `platform.tenant_bootstrap.write` | Role templates, first admin, admin recovery | ADR-0102 | + | `platform.identity_authority.admin` | Controlled issuer rebind | ADR-0104 | + | `platform.delivery.read` | Inspect dead letters and quarantined jobs | ADR-0103 | + | `platform.delivery.write` | Targeted replay and narrow producer reset | ADR-0103 | + | `platform.federation.read` | Report orphan, unreadable and nonconforming brokers | ADR-0099 A10 | + | `platform.federation.admin` | Operator disable and orphan removal | ADR-0099 A10 | - Standard 19 owns the final spelling and the scope table when Step 1 lands. -6. **Grants.** `IPlatformOperatorGrantSource` maps an operator subject key to Platform - keys. The shipped adapter reads configuration, validates every entry against the - catalogue at start, reloads without a restart and is evaluated on every act, never - from claims. A database adapter is demand-gated - ([ADR-0035](0035-demand-gated-infrastructure.md)): its trigger is a need for audited - runtime grant changes, its owning phase is - [Phase 11](../roadmap/phase-11-production-hardening.md), and the Hub operator portal - consumes it. The operator subject key is the base64url SHA-256 of the issuer, a - newline and `sub`; audit rows carry the key, never the raw `sub`. + The `platform.*` examples in Standard 19 that no ADR registers stay unregistered, and + Standard 19 cites the catalogue instead. It owns the final spelling when Step 1 + lands. +6. **Grants.** `IPlatformOperatorGrantSource` maps an operator subject digest to + Platform keys. The shipped adapter binds `PlatformOperator:Grants` through + `IOptionsMonitor`, validates every entry against the catalogue at start, takes effect + on the next act when the configuration provider reloads (a provider that cannot + reload needs a restart, and the runbook says so), and is evaluated on every act, + never from claims. The adapter refuses a grant for the exported demo operator unless + `Deployment:Mode` is Development, and refuses to start on any grant that fails + validation. A database adapter is demand-gated + ([ADR-0035](0035-demand-gated-infrastructure.md)): the trigger is a need for audited + runtime grant changes, the owning phase is + [Phase 11](../roadmap/phase-11-production-hardening.md), and managing it through an + operator route needs its own decision. 7. **Admission.** `IPlatformOperatorGate.AdmitAsync(witness, operation, ticket)` - replaces `IPlatformAdminGate.IsPermittedAsync(reason)`. The witness is minted only by - the operator authentication boundary from a validated principal, under a closed - minter census. An operation is a closed registry entry: permission, audit slug, - reason slug and whether it needs the platform role. The reason is that slug. The - ticket is a 1 to 64 character token matching `[A-Za-z0-9._:/#-]`, required for every - write act and carried only in `metadata` and the bounded `reason` column of the - written row. Admission runs before any privileged credential or connection is - resolved. -8. **Scope.** `EnterAsync` takes a `PlatformAdmission` and nothing else. Admission is - required by every operator act; the platform role is entered only by an act that - needs it. The handle exposes no provider connection. Work runs through a bounded - facade, completion and abandonment close the underlying connection, and a reference - captured before completion cannot execute, begin a transaction or reopen. A mutant - test captures such a reference. Entry still refuses job and external frames. -9. **Attribution.** Every row an operator act writes carries `actor_user_id` NULL, the - closed reason slug, the correlation id and `metadata.operator`: subject key, issuer - key, `kind` (`human`), accepted `acr` and the executing component. The shape is a - fixed census, not free text. A tenant-targeted act writes its rows under the real - target tenant so that tenant's administrators see it; the entry row and a - platform-wide act use the platform sentinel. + replaces `IPlatformAdminGate.IsPermittedAsync(reason)`. The witness is minted by one + minter class from a validated operator principal, and the closed minter census allows + two callers: the operator scheme handler and the offline tool of + [ADR-0104](0104-controlled-issuer-rebind.md), which validates the same token through + the same validator. An operation is a closed registry entry: permission, audit slug, + reason slug, and whether it needs the platform role. The reason is that slug. The + optional ticket is 1 to 64 characters of `[A-Za-z0-9._:/#-]`. A malformed ticket + answers 400 `validation_failed`. A missing permission or an unknown operation answers + 403. Admission runs before any privileged credential or connection is resolved. +8. **Scope.** `EnterAsync` takes a `PlatformAdmission` and keeps the compiler-supplied + caller attributes. Admission is required by every operator act; the platform role is + entered only by an act that needs it. The handle exposes no provider connection. + Work runs through a bounded facade, completion and abandonment close the underlying + connection, and a reference captured before completion cannot execute, begin a + transaction or reopen. A mutant test captures such a reference. Entry still refuses + job and external frames. +9. **Attribution.** An operator act writes `actor_user_id` NULL on its audit rows, the + closed reason slug, the correlation id and `metadata.operator` with fixed members: + `issuer`, `subjectDigest`, `kind` (`human`), `acr` and `executor`. The digest is the + unpadded base64url SHA-256 of `learnstack.operator.subject.v1`, a line feed, the + issuer, a line feed and `sub`; it is distinct from the identity subject key. The + optional ticket appears only in sentinel-tenant rows, which no tenant can read. Rows + a tenant can read carry the correlation id and never the ticket, and the response + returns the correlation id for the operator's own record. Business columns an + operator act writes use `UserId.SystemActor` for `created_by`, and + `platform_killswitches.toggled_by` stays NULL. 10. **Result audit.** A MUST result row commits in the transaction that changes the - state. A platform-role act uses a new witness-bound seam on the scope's work - transaction, a second caller of the platform write in - [ADR-0044](0044-audit-write-path.md) § 10. An outbox-role act uses the fenced - witness of [ADR-0103](0103-operator-recovery-of-asynchronous-work.md). An app-role - act uses the ordinary pipeline of - [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md). A forced - audit failure rolls the act back, and an act the audit made unavailable answers 503. + state. A platform-role act writes it through a new witness-bound method on the + scope's work transaction; `WritePlatformScopeAsync` keeps its single entry-row + caller. An outbox-role act uses the fenced witnesses of + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md). An app-role act uses the + ordinary pipeline extended by [ADR-0102](0102-production-tenant-onboarding.md). The + rebind uses an intent row and a result row from its own role + ([ADR-0104](0104-controlled-issuer-rebind.md)). The sentinel tenant may appear only + on the platform-scope class of [ADR-0044](0044-audit-write-path.md) § 1, which this + family extends to the entry row and a platform-wide result row; a tenant-targeted + result row carries the real tenant. A forced audit failure rolls the act back and + answers 503. 11. **Denied evidence.** A pre-authentication refusal answers 401 with a counter and a - structured log and writes no row - ([ADR-0077](0077-trusted-authorization-evidence.md): a tenantless refusal invents - no tenant). An authenticated operator who lacks the permission, names an unknown - operation or supplies an invalid ticket answers 403 before any connection opens, - with a counter and a Warning log carrying the operation slug and subject key. No - durable denial row is written, because one needs a bypass connection for a refused - caller or a third sentinel class. This ADR records that as the decided evidence. + structured log and writes no row. An authenticated operator who lacks the permission + or names an unknown operation answers 403 before any connection opens, with a + counter and a Warning log carrying the operation slug and subject digest. No durable + denial row is written, because one needs a bypass connection for a refused caller or + a third sentinel arm. Operator denials are outside the tenant denial population of + [ADR-0077](0077-trusted-authorization-evidence.md) and the denied-outcome rule of + [Standard 18](../standards/18-audit-coverage.md), which receive dated disclosures + saying so. Reopening needs Phase 11 security monitoring that requires durable + denial evidence. 12. **No-Hub baseline.** The surface depends on the configured issuer and the grant source only. Development has no permissive gate: its configuration grants the real pinned `learnstack-hub` demo operator and the proof runs against real Keycloak. @@ -163,35 +190,38 @@ permission. 13. **First consumer: the killswitch writer.** [ADR-0045 Amendment 1 § 4](0045-entitlement-and-feature-flag-socket.md) withheld it until a Platform gate existed. It is a service, not a MediatR request, and keeps the - matrix row `tenancy.killswitch.toggle` off-path. It resolves a key only from - `KillswitchKeys.All`, reads the before state, upserts the row with the operator, a - bounded ticket and the time, writes the MUST result row on the work transaction, and - removes the overlay cache entry after commit, including an indeterminate commit. - The runbook states the 60-second cross-instance lag and the overlay's fail-open - read. + matrix row `tenancy.killswitch.toggle` off-path with its `(planned)` marker removed + in the commit that registers it. It resolves a key only from `KillswitchKeys.All`, + reads the before state, upserts the row with the time and the ticket in the bounded + `reason` column, writes the MUST result row on the work transaction, and removes the + overlay cache entry after commit, including an indeterminate commit. Writes to + `platform_killswitches` are confined to it by an architecture rule; the overlay's + reads are unaffected. The runbook states the 60-second cross-instance lag, the + fail-open read, and that no production code reads a killswitch yet. +14. **Signals.** Counters record admissions by outcome and operation, refusals by cause, + and result rows by operation, so a monitoring owner can alert without a log search. ## Context The gate was shaped as a refusal on purpose: a permissive Development gate would repeat the inversion where the demo passes and production refuses. P03-9 now owns the -population that makes the refusal answerable. The corpus supplies three fixed points: -operators live in their own realm, tenant schemes refuse them, and Keycloak roles are -not authority. It supplies two statements that cannot both be true, an operator reaching -LearnStack through the Hub chain and an operator JWT independent of that chain. This ADR -takes the second, because the first needs a Hub crossing that does not exist and cannot -serve the no-Hub baseline. +population that makes the refusal answerable. The corpus fixes three points: operators +live in their own realm, tenant schemes refuse them, and Keycloak roles are not +authority. Its one unfinished edge is the route: ADR-0036 reaches operators only through +a machine chain that has no human. This ADR gives the human a LearnStack-owned prefix +and scheme, and leaves the Hub chain as it is. -A scheme per audience keeps each acceptor class closed. A grant source evaluated per act -gives revocation without a token wait, which a claim cannot. Configuration is enough for -a population of a few staff and keeps the first packet free of a second platform table -and its writer; the port and the trigger make the table a plain addition. The -result-audit seam is the real cost: the entry row commits before the work and records -entry only, so a result row needs the work transaction, which the platform write seam -does not take today. +A scheme per audience keeps each acceptor class closed, which is why a second scheme is +confined to its prefix instead of widening the tenant one. A grant source evaluated per +act gives revocation without a token wait, which a claim cannot. Configuration is enough +for a few staff and keeps the first packet free of a second platform table and its +writer; the port and the trigger make the table a plain addition. The result-audit +method is the real cost: the entry row commits before the work and records entry only, +so a result row needs the work transaction, which no platform write method takes today. -What would reopen this: a Hub operator portal that needs delegated operator identity -(an ADR-0034 amendment in both repositories), a need for durable denial evidence from -Phase 11 monitoring, or a service operator for scheduled platform work. +What would reopen this: a Hub operator portal that needs delegated operator identity (an +ADR-0034 amendment in both repositories), durable denial evidence from Phase 11 +monitoring, or a service operator for scheduled platform work. ## Consequences @@ -203,16 +233,16 @@ Phase 11 monitoring, or a service operator for scheduled platform work. route, by two closed schemes and a disjoint prefix. - The tenant contract does not change, so the OpenAPI gate and G20 are not triggered. - Attribution survives in every row: who, why, through which assurance, under which - correlation. + correlation, without leaking an operator's ticket to a tenant. ### Negative -- Two schemes and a second realm client to operate and test, plus one new realm client - and audience mapper in this repository's realm export. +- Two schemes and one new realm client and audience mapper in this repository's realm + export, plus an `acr` and `auth_time` profile every Self-Hosted issuer must meet. - Configuration grants give no audited runtime grant change until the table adapter. - No durable denial row: a refused operator leaves a counter and a log only. -- Operators have no browser screen in this repository. The Hub operator portal, which - has not started, is the intended client of the served document. +- Operators have no browser screen here. The Hub operator portal, not started, is the + intended client of the served document. ### Neutral @@ -222,37 +252,38 @@ Phase 11 monitoring, or a service operator for scheduled platform work. ## Implementation Notes -- Step 1 delivers the scheme, witness, catalogue, grant source, gate, scope redesign, - result seam, route census, problem mapping, killswitch writer and runbooks. Realm - changes: a `learnstack-platform` audience client, a public PKCE `learnstack-operator` - client with an audience mapper, a token lifetime cap and an ACR-to-level mapping with - step-up. +- Step 1 delivers the scheme, witness minter, catalogue, grant source, gate, scope + redesign, result method, route mechanics, problem mapping, killswitch writer and + runbooks. Realm changes: one public PKCE client `learnstack-operator` with an audience + mapper for `learnstack-platform`, a client token lifetime of at most 15 minutes, and + an ACR-to-level mapping with step-up. The proof reads a real token and shows the + pinned realm emits `acr` and `auth_time`. - The mutation targets are the gate call, its position before connection acquisition, - the admission refusal inside job frames, the closure fence, a null actor and a missing - result row. + the admission refusal inside job frames, the closure fence, a null actor, a missing + result row and the cache removal after commit. - Architecture rules: `PlatformAdminScope_Entry_Requires_Platform_Permission` conjunct B - is rewritten against the real gate, not deleted; SQL on `platform_killswitches` is - confined to the writer; a Platform definition is non-assignable and the tenant - document bytes are unchanged; the minter census of the witness is closed. -- The Platform permission rows start in the - [Tenancy matrix](../modules/tenancy/permissions.md) and the platform operations in its - [audit matrix](../modules/tenancy/audit.md). + is rewritten against the real gate, not deleted, and gains its marker clause; the + minter census is closed; a Platform definition is non-assignable and the tenant + document bytes are unchanged; the operator prefix census is exact. -## Carriers owed at acceptance +## Carriers -Each is a dated disclosure, never a body edit: -[ADR-0004](0004-authentication-strategy.md) (the operator scheme and audience), -[ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the platform URL space), -[ADR-0044](0044-audit-write-path.md) (the second platform write caller and the -`metadata.operator` shape), [ADR-0045](0045-entitlement-and-feature-flag-socket.md) -(the writer's shape), [ADR-0100](0100-p038-federation-contract-transition.md) (a -Platform key is not assignable, so it does not recur the refusal). Standards 04, 11, 18, -19, 21, 12 and 13, Architecture 13 and 28, the glossary and Phase 03 follow. +Each is a dated disclosure, never a body edit. ADR-0004 (scheme and audience), ADR-0036 +(the platform URL space and the confined target announcement), ADR-0040 (the +announcement setter), ADR-0044 (the result method, the extended sentinel class and the +operator metadata), ADR-0045 (the writer's shape and the corrected actor claim), +ADR-0046 and ADR-0047 (through +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md)), ADR-0064 (a second scheme +confined to its prefix), ADR-0077 (operator denials), ADR-0099 (Amendment 10) and +ADR-0100 (a Platform key does not recur the refusal). Standards 04, 11, 12, 13, 18, 19, +20 and 21, Architecture 13, 28 and 30, the glossary, the Tenancy and Identity module +specifications, and the Phase 03 and Phase 11 documents follow. ## References -- [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md), - [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) +- [ADR-0102](0102-production-tenant-onboarding.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md), + [ADR-0104](0104-controlled-issuer-rebind.md) - [ADR-0004](0004-authentication-strategy.md), [ADR-0034](0034-hub-contract-surface-invariant.md), [ADR-0036](0036-tenant-resolution-trusted-inputs.md), diff --git a/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md b/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md deleted file mode 100644 index 52071822..00000000 --- a/docs/decisions/0102-production-tenant-onboarding-and-authority-rebind.md +++ /dev/null @@ -1,198 +0,0 @@ -# ADR-0102: Production Tenant Onboarding and Authority Rebind - -## Status - -Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no -Accepted record and authorizes no code until Accepted. Acceptance would close the -production first-admin, provisioning, recovery and issuer-rebind parts of gate G13 -together with [ADR-0101](0101-platform-operator-authority.md). - -**Date:** 2026-11-19 -**Deciders:** @cemil - -## Decision Drivers - -- [ADR-0072](0072-application-owned-identity-bootstrap.md) and - [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) leave production - first-admin setup and a controlled issuer rebind to P03-9. The fixed seed capability - grants no operator authority, and no production rename path exists. -- `ProvisionTenantCommand` and the identity seed handlers accept only the `Seed` source. - Nothing outside the Seeder, which refuses no deployment mode, creates a Tenant, - its Role templates or a first administrator. Host-to-tenant mappings arrive in - production only through a Hub endpoint that does not exist - ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), so the no-Hub baseline cannot - make a tenant reachable. -- The invariants that make an administrator safe, last-admin protection, the User fence - and ordered membership locks - ([ADR-0074](0074-membership-admission-under-ordered-locks.md)), live in app-role - domain code. A raw write on the platform connection skips them and the audit capture - of [ADR-0044](0044-audit-write-path.md) § 7. -- `identity_authority` is a singleton qualified once at startup. Subject keys hash its - `AuthorityId` ([Database Standards](../standards/05-database.md)), so an issuer change - that alters the id re-keys every person and can resurrect a closed tombstone. -- C14 asks for positive and denied proof, partial-commit proof, unknown-COMMIT - reconciliation and identity continuity, and says seed authority is insufficient. - -## Considered Options - -1. **Operator-admitted acts on the app role through the ordinary pipeline, and an - offline rebind that is still an admitted operator act** (chosen). Invariants, RLS and - audit capture stay where they are proven. -2. **Run onboarding as raw SQL on the platform connection** (rejected). It skips the - last-admin and User invariants and the audit capture, and widens a `BYPASSRLS` role. -3. **Accept the `Seed` source in production** (rejected). The Seeder is a development - tool with fixed identities and no mode refusal. -4. **A platform-issued invitation for the first administrator** (rejected here). It - reuses [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) but needs an - exception for an inviter who holds no membership, and it adds an email dependency to - recovery. -5. **A rebind through an HTTP operator act under a runtime admission freeze** - (rejected). It puts a database read on every authentication and keeps old issuers - alive in running processes, because the qualification is startup-only. - -## Decision - -1. **A confined operator source.** `AuthorizationSourceKind` gains `PlatformOperator`, - minted only from an [ADR-0101](0101-platform-operator-authority.md) admission. The - operator acts below accept that source and no other, and the `Seed` policies stay - `Seed`-only, so neither authority can perform the other's acts. The target tenant is - announced by that source through exactly one new confined setter call in the closed - census, never from a request value, and the platform role is not used. Step 2 fixes - the exact origin value against the code. -2. **The act family.** Four acts, each a `platform.*` permission under ADR-0101: - provision a Tenant with its default Organization and map its hosts through the - existing commands; create the finite Role templates; create the first tenant-wide - administrator Membership; recover a tenant that has none. Tenancy provisioning keeps - its Tenant and default Organization pair. The tenant id is generated by the server - and never chosen by the operator; a retry carries an idempotency key. -3. **Naming the person.** The operator names the first administrator by provider subject - at the identity authority's issuer. The person must already have completed new-user - bootstrap, so a `users` binding exists. A confined single-act resolver maps the - subject to a `UserId`; an unknown subject refuses with a bootstrap-required outcome. - The operator creates no `User`, and an email address is never an identifier. -4. **Separate transactions, resumable.** Provisioning, each Role template and the - Membership commit in their own transactions, as - [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) requires. A retry - after partial setup resumes from the first absent step by reading state, with the - pristine-prefix predicates of the Role roots. An unknown COMMIT is reconciled by that - read, never by a blind repeat. Naming a tenant that does not exist, or a person who - is not bootstrapped, refuses before any write. -5. **Recovery.** Recovery uses the same acts and refuses unless, inside the transaction, - the tenant has no active tenant-wide administrator. Its reason slug differs, and the - last-admin invariant is unchanged. The act is not a tenant-administrator escalation - path. -6. **Audit.** Each step writes its MUST row in its own transaction through the ordinary - pipeline, under the real target tenant, with the operator attribution of - [ADR-0101](0101-platform-operator-authority.md) § 9. -7. **Controlled issuer rebind.** The rebind changes only the origin of - `identity_authority.issuer`, under the same realm path. It preserves `AuthorityId`, - subject keys, actor ids and closed tombstones, and no realm rename is admitted. - It is an offline operator act: a new verb of the authority installer tool runs while - the API and worker fleets are stopped, accepts the human's operator access token, - is admitted for `platform.identity_authority.admin`, enters the platform scope, and - writes its MUST result row on that scope's work transaction. -8. **Frozen admission.** The tool refuses unless it holds a session-level exclusive lock - and observes no other session of the application or outbox role. It does not trust an - operator's statement that the fleet is stopped. -9. **Continuity proof.** Before the change, the tool reads the new issuer's discovery - and key set, enumerates every user of the new realm through the realm Admin API with - the deployment's own credential, and hashes each `sub` under the preserved - `AuthorityId` exactly as the binding does. Every active stored subject key must be - present. A closed tombstone key must be absent, so a closed person cannot reappear. - Any miss, or an enumeration that does not complete, refuses. -10. **Database guard.** The platform role receives `UPDATE (issuer)` on - `identity_authority` and nothing else on it. A trigger refuses any other column, - refuses an issuer that breaks the realm grammar and refuses the change unless the - transaction announced the rebind token the tool sets. Processes that start with the - old issuer fail qualification, so a restart with the new configuration is the - unfreeze. -11. **Seed capability.** The Seeder refuses to run when `Deployment:Mode` is not - Development. A test proves the seed source cannot perform an operator act and the - operator source cannot perform a seed act. - -## Context - -Onboarding is not the platform scope's job. The scope exists to cross tenants and write -platform tables, and the platform role bypasses row security. A first administrator is -the opposite case: one tenant, ordinary tables, and the strongest invariants in the -Identity module. Running it on the app role keeps those invariants and the capture of -[ADR-0044](0044-audit-write-path.md) § 7, and costs one new confined source and one new -setter call, which the closed census makes visible and testable. The cost is real: the -source enum, the setter census and the minting rules of the authorization candidate all -change, and the existing negative controls must keep refusing everything else. - -Naming a person by provider subject keeps email out of authority. It asks the person to -sign in once first, which is the same zero-membership entry P03-3 already ships. The -operator reads the `sub` from the issuer's own console, which the operator already -holds. - -The rebind is rare and dangerous, so it is shaped to be hard to do by accident. An HTTP -act would need a runtime freeze on every authentication and still could not retire the -issuer that running processes hold. Offline with a lock, a session check, a continuity -proof and a guarded column makes each claim checkable without touching the hot path. -What the session check cannot see is a process on another database role or another -cluster node that the deployment forgot; the runbook states it. - -The host mapping is included because a tenant that resolves to no host is not onboarded. -It does not widen the Hub contract: the Hub endpoint stays the Hub's, and this act -reuses the existing mapping command. - -What would reopen this: a Hub that pushes provisioning and mappings, a need for a -self-service first administrator, or a realm rename. - -## Consequences - -### Positive - -- No production onboarding depends on the development seed, and a test proves the two - authorities cannot substitute. -- The last-admin and User invariants and the audit capture are unchanged and exercised. -- The rebind is checkable: a continuity set, a lock, a guarded column and a result row. -- The no-Hub baseline can create a reachable tenant with an administrator. - -### Negative - -- A new authorization source kind, a new confined setter call and a new definer-style - resolver widen closed sets that tests currently pin, so each census is edited - deliberately. -- An operator needs the person's `sub` and the person must sign in first. -- A rebind needs a downtime window. - -### Neutral - -- `ProvisionTenantCommand` and the host command gain the operator source beside `Seed`. -- Seeded Development tenants are unaffected. - -## Implementation Notes - -- Step 2 delivers the source, setter call, resolver, acts, routes, rebind verb, guard - migration and canonical SQL, the Seeder mode refusal, and the tenant onboarding and - rebind runbook. The migration changes the grants table in - [Database Standards](../standards/05-database.md) and the pinned grant expectations in - the same commit. -- Proof: positive and denied acts; wrong tenant; unbootstrapped person; interruption - between every pair of steps with a retry that completes once; an unknown COMMIT; the - last-admin invariant after recovery; seed insufficiency in both directions; a rebind - with a missing, extra and tombstoned subject, a live second session and an unchanged - `AuthorityId`. The mutation targets are the source check, the in-transaction no-admin - test, the continuity comparison and the guard trigger. - -## Carriers owed at acceptance - -Dated disclosures in [ADR-0072](0072-application-owned-identity-bootstrap.md) and -[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the production path -and the rebind), [ADR-0040](0040-ambient-unit-of-work.md) (the setter -census, if the census is named there), Standards 05 and 19, the Identity and Tenancy -module specifications, the Phase 03 Status and Phase 11 realm items. - -## References - -- [ADR-0101](0101-platform-operator-authority.md), - [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) -- [ADR-0072](0072-application-owned-identity-bootstrap.md), - [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md), - [ADR-0074](0074-membership-admission-under-ordered-locks.md), - [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) -- [Identity module](../modules/identity/README.md), - [Database Standards](../standards/05-database.md) -- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md new file mode 100644 index 00000000..7d54ae34 --- /dev/null +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -0,0 +1,209 @@ +# ADR-0102: Production Tenant Onboarding + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes the production provisioning, first-administrator and recovery parts of +gate G13 together with [ADR-0101](0101-platform-operator-authority.md) and +[ADR-0104](0104-controlled-issuer-rebind.md), and authorizes the code it describes. It +is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) and + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) leave production + first-admin setup to P03-9. The fixed seed capability grants no operator authority. +- The tenant, host-mapping, Role-template and first-admin commands are `Seed`-only by + construction. Their handlers pass a seed guard that demands a single allowed source + `Seed`, an exact trusted `Seed` source and the fixed demo declaration, and the API + registers deny-all continuation and foundation admissions. Adding a source to their + policies would still be refused in the handler, so production onboarding needs its own + commands. +- The invariants that make an administrator safe, last-admin protection, the User fence + and ordered membership locks + ([ADR-0074](0074-membership-admission-under-ordered-locks.md)), live in app-role + domain code. A raw write on the platform connection skips them and the audit capture + of [ADR-0044](0044-audit-write-path.md) § 7. +- A tenant that resolves to no host is not onboarded, and the Hub endpoint that pushes + host mappings does not exist ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), so + the no-Hub baseline needs an operator-admitted mapping. +- The first-admin command refuses any tenant with Membership history, so recovery of a + tenant whose administrators are gone is a different predicate, not a repeat. +- C14 asks for positive and denied proof, partial-commit proof, unknown-COMMIT + reconciliation, and says seed authority is insufficient. + +## Considered Options + +1. **Operator-admitted commands of their own, on the app role, through the ordinary + pipeline** (chosen). They reuse the domain aggregates and extracted shared cores, and + keep the `Seed` commands untouched. +2. **Add the operator source to the existing `Seed` commands** (rejected). The seed + guard requires a single `Seed` source and the fixed declaration, so the handler + refuses it, and widening the guard weakens the seed's only-this-source property. +3. **Run onboarding as raw SQL on the platform connection** (rejected). It skips the + last-admin and User invariants and the audit capture, and widens a `BYPASSRLS` role. +4. **A platform-issued invitation for the first administrator** (rejected here). It + reuses [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) but needs an + exception for an inviter who holds no Membership and depends on automatic email + delivery, so recovery would depend on mail. + +## Decision + +1. **A confined operator source and announcement.** `AuthorizationSourceKind` gains + `PlatformOperator`, minted only from an + [ADR-0101](0101-platform-operator-authority.md) admission for one of the operations + below. The five commands carry `FiniteTrusted` policies whose only source is + `PlatformOperator`, and the `Seed` policies and guards are unchanged, so neither + authority can perform the other's acts. The target tenant is announced to the unit of + work by one new logical tenant setter, confined to that source: it reads the admitted + operation's declared target, never an ambient or header value, announces once per + unit of work and refuses any other caller. It is the eleventh logical tenant setter; + [ADR-0040](0040-ambient-unit-of-work.md) and + [ADR-0036](0036-tenant-resolution-trusted-inputs.md) receive dated disclosures, and + the four context writers do not change. The platform role is not used. +2. **The commands.** `OperatorProvisionTenant` creates a Tenant and its default + Organization. `OperatorMapHost` maps a host through the existing host-mapping store + and its reserved-host and platform-host rules. `OperatorInitializeRole` creates one + finite Role template. `OperatorCreateFirstAdmin` creates the first tenant-wide + administrator Membership. `OperatorRecoverAdmin` creates a replacement administrator. + `platform.tenant.write` covers the first two; `platform.tenant_bootstrap.write` + covers the other three. Shared cores are extracted from the seed handlers so the + domain logic exists once; the seed and operator handlers differ only in their guard. +3. **Identity of the acts.** The operator supplies a UUIDv7 `tenantId` and a slug, and + an act is idempotent on that pair: the same pair finds the existing tenant, and a + known slug under another id refuses. A lost response therefore loses nothing. The + business actor of every written row is `UserId.SystemActor`; the operator is recorded + in audit only, as [ADR-0101](0101-platform-operator-authority.md) § 9 fixes. Operator + policies do not use the membership-candidate path, which refuses `SystemActor`. +4. **Host mapping.** The operator asserts ownership of the host. LearnStack verifies no + DNS, and the seed does not either. The Hub's custom-domain approval for SaaS stays + the Hub's and is unreachable here. The runbook states that a Self-Hosted operator is + responsible for DNS and TLS. +5. **Naming the person.** The operator names the first administrator by provider subject + at the identity authority's issuer. The person must already have completed + global-self bootstrap at the tenant's mapped host, so a `users` binding exists. A + confined single-act resolver computes the canonical subject key under the stored + `AuthorityId`, the request supplying neither, and returns the `UserId` of an Active + user only. An unknown or non-Active subject refuses with a 409 `bootstrap_required` + problem. The operator creates no `User`, and an email address is never an identifier. +6. **Order.** Provision, map the host, the person signs in once at that host, each Role + template, then the first administrator. Each step commits in its own transaction, as + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) requires, and the + Role roots keep their pristine-prefix predicates. A retry resumes from the first + absent step by reading state, never by repeating a write blind. An unknown COMMIT is + reconciled by that read. Naming a tenant that does not exist, or a person who is not + bootstrapped, refuses before any write. +7. **First administrator.** `OperatorCreateFirstAdmin` refuses unless the tenant has no + Membership history, the seed command's predicate, evaluated under the ordered locks + of [ADR-0074](0074-membership-admission-under-ordered-locks.md) inside the + transaction. A tenant that already has an administrator, or ever had a Membership, + cannot gain one this way, so the act is not an escalation path. +8. **Recovery.** `OperatorRecoverAdmin` refuses unless, under the same locks, the tenant + has no active tenant-wide administrator Membership. It has its own audit slug and + reason slug, accepts the same person-naming rule, and leaves the last-admin invariant + unchanged. It is the only act that may add an administrator to a tenant with + Membership history. +9. **Audit.** Each step writes its MUST rows in its own transaction through the ordinary + pipeline, under the real target tenant. Provisioning writes two, the Tenant and the + Organization. The pipeline's authorization audit context, evidence coordinator and + draft composer, which today admit a null actor, a missing tenant and a null reason + only for `Seed`, gain a `PlatformOperator` branch that records the closed reason slug + and `metadata.operator` of [ADR-0101](0101-platform-operator-authority.md) § 9. The + rows never carry the ticket. +10. **Seed capability.** The Seeder refuses to run when `Deployment:Mode` is not + Development. A test proves the seed source cannot perform an operator act and the + operator source cannot perform a seed act. +11. **Signals.** Counters record each act by operation and outcome, and a resumed setup + by the step it resumed at. + +## Context + +Onboarding is not the platform scope's job. The scope exists to cross tenants and write +platform tables, and the platform role bypasses row security. A first administrator is +the opposite case: one tenant, ordinary tables, and the strongest invariants in the +Identity module. Running it on the app role keeps those invariants and the capture of +[ADR-0044](0044-audit-write-path.md) § 7, and costs one new authorization source, one +new confined setter and five commands, which the closed censuses make visible and +testable. The cost is real: the source enum, the setter census and the audit composition +all change, and their existing negative controls must keep refusing everything else. + +The seed guard is the reason for separate commands. It is a deliberate only-this-source +check, and the operator authority must not borrow it. Extracting shared cores keeps the +duplication to the guard. + +Naming a person by provider subject keeps email out of authority. It asks the person to +sign in once first, which is the zero-membership entry P03-3 already ships. The operator +reads the `sub` from the issuer's own console, which the operator already holds. The +operator-supplied tenant id is safe because the command is reachable only with an +admission, and it makes a retry exact. + +What would reopen this: a Hub that pushes provisioning and mappings, a need for a +self-service first administrator, or an operator population too large for subject-based +naming. + +## Consequences + +### Positive + +- No production onboarding depends on the development seed, and a test proves the two + authorities cannot substitute. +- The last-admin and User invariants and the audit capture are unchanged and exercised. +- The no-Hub baseline can create a reachable tenant with an administrator, and recover + one. + +### Negative + +- A new authorization source kind, a new confined setter and a new resolver widen closed + sets that tests pin, so each census is edited deliberately. +- An operator needs the person's `sub`, and the person must sign in first at a mapped + host. +- The operator, not LearnStack, vouches for host ownership. + +### Neutral + +- Shared cores are extracted from the seed handlers; the seed behavior does not change. +- Seeded Development tenants are unaffected. + +## Implementation Notes + +- Step 2 delivers the source, setter, resolver, commands, routes, audit-composition + branch, Seeder mode refusal and the onboarding runbook. It touches the source enum, + `OperationPolicy` and `TrustedOperationDescriptor` source guards, the authorization + audit context, the evidence coordinator and the draft composer. +- Proof: positive and denied acts; wrong tenant; unbootstrapped person; interruption + between every pair of steps with a retry that completes once; an unknown COMMIT; a + tenant with history refusing the first-admin act; recovery refusing a tenant with an + active administrator and succeeding after the last one is revoked; the last-admin + invariant after recovery; seed insufficiency in both directions. The mutation targets + are the source check, the in-transaction predicates, the resolver's Active filter and + the setter's operation binding. + +## Carriers + +Dated disclosures in [ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the target +announcement), [ADR-0040](0040-ambient-unit-of-work.md) (the eleventh logical setter), +[ADR-0044](0044-audit-write-path.md) and [ADR-0033](0033-audit-durability-model.md) (the +audit-composition branch), [ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the production +path), [ADR-0074](0074-membership-admission-under-ordered-locks.md) (the recovery +predicate under its locks), Standards 05, 18 and 19, the Identity and Tenancy module +specifications, and the Phase 03 Status. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md), + [ADR-0104](0104-controlled-issuer-rebind.md) +- [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md), + [ADR-0074](0074-membership-admission-under-ordered-locks.md), + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) +- [Identity module](../modules/identity/README.md), + [Database Standards](../standards/05-database.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md index 3da8e48c..89aea658 100644 --- a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -2,10 +2,13 @@ ## Status -Proposed — 2026-11-19, for the maintainer's review. It closes no gate, changes no -Accepted record and authorizes no code until Accepted. Acceptance would close gate G14 -and, with [ADR-0101](0101-platform-operator-authority.md), decide the dashboard -question that D13 raises. +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes gate G14 and, with [ADR-0101](0101-platform-operator-authority.md), +decides the dashboard question that D13 raises. It authorizes the code it describes and +is not proof that anything is implemented. **Date:** 2026-11-19 **Deciders:** @cemil @@ -15,22 +18,28 @@ question that D13 raises. - [ADR-0046](0046-durable-event-delivery-and-recovery.md) says "operator replay is Phase 03, with a separately specified reset/fencing contract before any endpoint ships". `DeliveryDispatchStore.ReplayAsync` exists and has no production caller. It takes no - actor, reason or stale-state token, and writes no audit row, so a second operator can - reset a row a first operator already re-terminalized. + actor, reason or stale-state token, filters no terminal reason and writes no audit + row, so a second operator can reset a row a first operator already re-terminalized, + and an `invalid_envelope` delivery can be reset to fail again. - [ADR-0047](0047-transactional-background-job-runtime.md) keeps a quarantined job frozen for every role by trigger, retains its reservations, and releases capacity only on confirmed completion, no-start or quiescence. Operator authority, elapsed time and - a missing worker are not that proof. The only external definition today, invitation - email, ends in `Unknown`, which no operator can turn into proof. + a missing worker are not that proof. The external definitions today are the two + invitation-email ones, whose outcome can end `Unknown`, and the mail adapter offers no + fence an operator could cite. - `learnstack_platform` holds no privilege on inbox, delivery or job tables - ([Data Protection](../architecture/23-data-protection.md)), and the outbox role is - confined by census to the dispatcher. A recovery owner needs a named principal and no - silent widening. + ([Data Protection](../architecture/23-data-protection.md)), which says any change + needs its own bounded decision and migration. The outbox role holds table-wide + `SELECT` on `outbox_messages`, so a payload exclusion there would rest on code + discipline alone. +- Only ADR-0046's confined dispatcher writes outbox status today; a second writer is a + decision, not an implementation detail. - The Hangfire dashboard needs a browser session on an API with none ([ADR-0004](0004-authentication-strategy.md)). The runtime's storage runs on the privileged source, so a dashboard write control reaches past the job fences. The stock statistics are suppressed ([ADR-0058](0058-bounded-stock-hangfire-maintenance.md)), a - vendor "Succeeded" is not business success, and the runtime pins no dashboard package. + vendor "Succeeded" is not business success, and the runtime maps no dashboard: an + architecture rule refuses any dashboard type. [ADR-0015](0015-api-gateway-apisix.md) still guides a backend filter on the realm role `platform-admin`, which [Standard 19](../standards/19-permissions.md) forbids. - C15 requires dashboard and recovery to remain absent until admitted, and then proof of @@ -40,101 +49,124 @@ question that D13 raises. ## Considered Options -1. **A fixed inspection and recovery set on a confined outbox-role owner, no dashboard** - (chosen). Every transition carries a stale-state fence, an operator admission and a - same-transaction result row. -2. **Admit the Hangfire dashboard read-only** (rejected now). It adds a package, a - browser session path and a second source borrower, and shows state the runtime says - is not authoritative. Its read-only form shows less than the inspection set below. -3. **Run recovery in the platform scope with new platform grants** (rejected). It widens - a `BYPASSRLS` role on tables that the corpus holds closed, and none of the chosen - acts needs to cross tenants. -4. **Release or requeue quarantined jobs on operator attestation** (rejected). It - supersedes [ADR-0047](0047-transactional-background-job-runtime.md)'s quiescence rule - and would let an unfenced external start run again. -5. **Admit nothing and ship a runbook** (rejected). An exhausted dead letter would have +1. **Metadata inspection through the platform scope on column-limited grants, and fenced + transitions on a confined outbox-role owner, with no dashboard** (chosen). The + database enforces the projection, the scope entry row audits each inspection, and + each transition carries a stale-state fence and a same-transaction result row. +2. **Admit the Hangfire dashboard read-only** (rejected now). It adds a browser session + path and a second source borrower, and shows state the runtime says is not + authoritative. Its read-only form shows less than the inspection set below. +3. **Run the transitions in the platform scope with new platform write grants** + (rejected). It widens a `BYPASSRLS` role with writes on tables the corpus holds + closed, and none of the transitions crosses tenants. +4. **Inspect through the outbox role** (rejected). It reads cross-tenant on a role whose + `SELECT` is table-wide, with no per-call audit. +5. **Release or requeue quarantined jobs on operator attestation** (rejected). It would + supersede [ADR-0047](0047-transactional-background-job-runtime.md)'s quiescence rule + and let an unfenced external start run again. +6. **Admit nothing and ship a runbook** (rejected). An exhausted dead letter would have no remedy, and C15's stale-fence and sibling proofs would have no subject. ## Decision -LearnStack admits three operator transitions and a metadata-only inspection, and no +LearnStack admits a metadata-only inspection and two fenced transitions, and no dashboard. -1. **Inspection.** `platform.delivery.read` returns cursor-paged metadata for - dead-lettered or terminal-requested outbox rows, terminal delivery rows and - quarantined jobs with their reservation occupancy. An explicit column list makes the - projection free of envelope payloads, job parameters, plans and outcomes. Each row - returns the fence its transition needs. -2. **Targeted subscriber replay.** `platform.delivery.write` resets one +| Operation | Permission | Principal | Audit | +|---|---|---|---| +| `platform.delivery.inspect` | `platform.delivery.read` | platform scope, column grants | scope entry row | +| `platform.delivery.replay` | `platform.delivery.write` | outbox-role owner | result row, `delivery_replay` | +| `platform.delivery.reset` | `platform.delivery.write` | outbox-role owner | result row, `delivery_reset` | + +1. **Inspection.** Cursor-paged metadata for dead-lettered outbox rows, rows whose + terminal request is pending, terminal delivery rows and quarantined jobs with their + reservation occupancy. A migration gives `learnstack_platform` `SELECT` on named + metadata columns of `outbox_messages`, `event_deliveries`, `background_jobs` and + `background_job_reservations`, excluding every envelope, parameter, plan, outcome and + causal column, so the database refuses what the projection must not return. Grant + tests read column privileges. Each row returns the fence its transition needs. A row + whose terminal request is pending shows its state and is not actionable. +2. **Targeted subscriber replay.** `platform.delivery.replay` resets one `(tenant, subscription, event)` delivery. The request carries the fence read at - inspection: `replay_count`, `dead_lettered_at` and `terminal_reason`. The reset is - refused unless those still match, the row is dead-lettered and unleased, and the - subscription is an Active ordinary one. A completed delivery, its inbox row, every - sibling delivery and the producer row are untouched, and a privileged, unknown or - retired subscription is refused. -3. **Narrow producer reset.** The same permission resets a dead-lettered outbox row - whose `terminal_reason` is `retry_exhausted` and which is not processed, under the - fence `(attempts, dead_lettered_at)`. It clears the terminal fields and the lease, - resets attempts and sets `available_after` to now. `invalid_envelope`, `unknown_type` - and `retired_type` are refused, because an immutable envelope cannot become valid. - The reset deliberately renews the six-attempt budget. A publication that already - reached a subscriber is absorbed by stable event-id acceptance + inspection: `replay_count`, `dead_lettered_at` and `terminal_reason`. It is refused + unless the fence still matches, the row is dead-lettered and unleased, the + subscription is an Active ordinary one and the event's tenant is Active. A delivery + that ended `invalid_envelope` is always refused, because an immutable envelope cannot + become valid, and `unknown_type` and `retired_type` follow the registry at replay + time. A completed delivery, its inbox row, every sibling delivery and the producer + row are untouched, and a privileged subscription is refused. +3. **Narrow producer reset.** `platform.delivery.reset` resets a dead-lettered outbox + row whose `terminal_reason` is `retry_exhausted` and which is not processed, under + the fence `(attempts, dead_lettered_at)`. It clears the terminal fields and the + lease, resets attempts and sets `available_after` to now. Every other reason is + refused. The reset deliberately renews the six-attempt budget. A publication that + already reached a subscriber is absorbed by stable event-id acceptance ([ADR-0046](0046-durable-event-delivery-and-recovery.md): terminal state does not - prove that no subscriber accepted), and the next dispatch reaches every subscription - that is Active now. Producer reset is not a power of subscriber replay: the two are - separate requests with separate fences, and neither writes the other's table. + prove that no subscriber accepted). Acceptance never reopens an existing delivery + row, so the next dispatch reaches the Active subscriptions that have no delivery row, + and a delivery that already ended terminal needs its own subscriber replay. Producer + reset is not a power of subscriber replay: the two are separate requests with + separate fences and neither writes the other's table. 4. **Principal.** A new confined owner uses the outbox-role credential behind an - [ADR-0101](0101-platform-operator-authority.md) admission. No platform scope is - entered and no grant is added. + [ADR-0101](0101-platform-operator-authority.md) admission. It is a second writer of + outbox and delivery status beside the dispatcher, recorded by an + [ADR-0046](0046-durable-event-delivery-and-recovery.md) disclosure. `LearnStack_OutboxAdmin_Role_OnlyUsedBy_OutboxProcessor` gains exactly that owner, - `ReplayAsync` moves behind it with its new signature, and no HTTP path reaches the - dispatcher's store. -5. **Result audit.** The row is minted from the fenced `UPDATE ... RETURNING` witness, - the way a terminal witness is, on the same outbox-role transaction. It carries the - real event tenant, the closed reason slug, `metadata.operator` and `metadata.fence` - (before and after). A forced audit failure rolls the transition back and answers 503 - with no state change. A stale fence answers 409 with no change and no row. + `ReplayAsync` moves behind it with its new signature, and no HTTP path resolves the + dispatcher's store directly. The tenant lifecycle test reads the existing lifecycle + projection the outbox role already holds. +5. **Result audit.** A new witness kind, not the terminal witness, is minted from the + fenced `UPDATE ... RETURNING` on the same outbox-role transaction and writes the row + with the real event tenant, the closed reason slug, `metadata.operator` and + `metadata.fence` (before and after). The terminal witness demands the system actor, a + null reason and no metadata, so it cannot carry an operator. A forced audit failure + rolls the transition back and answers 503 with no state change. A stale fence answers + 409 `stale_fence`, a refused state 409 `not_recoverable`, and neither writes a row or + changes state. 6. **Not admitted: job recovery.** No job requeue, retry, probe re-arm, reservation or capacity release exists. A quarantined job stays frozen, retains its reservation and keeps `jobs` unhealthy, exactly as [ADR-0047](0047-transactional-background-job-runtime.md) says. The trigger to admit one is the first external definition whose adapter can supply provider fencing or - process-tree termination evidence. Its owning phase is the one that ships that - adapter, [Phase 08a](../roadmap/phase-08a-assessment-notifications.md) for - notification providers, with [Phase 11](../roadmap/phase-11-production-hardening.md) - owning operational reconciliation. The invitation path's remedy stays the reissue of - [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md). + process-tree termination evidence; none can today, and the phase that ships such an + adapter owns the decision, with + [Phase 11](../roadmap/phase-11-production-hardening.md) owning operational + reconciliation. For the invitation path, reissue helps only while a tenant slot is + free: it does not reconcile or release the old effect + ([ADR-0093](0093-verified-invitation-acceptance-and-handoff.md)), and four unresolved + effects can hold every slot with no operator remedy. That limit is stated, not + softened. 7. **Not admitted: recurrence recovery.** No recurrence, occurrence or recipient skip, abandon, pause or resume exists. No production recurrence exists; Phase 11 owns it. 8. **Dashboard.** `/admin/hangfire*` stays unmapped and answers 404 in every deployment - mode, and `BackgroundJob_Runtime_Has_No_Production_Definitions_Or_Dashboard` stays. - The inspection set is the operator's view. A dashboard write control is never - admitted. A read-only dashboard needs its own decision on authentication, the - dependency and the source borrower. -9. **Erasure floor.** No replay floor after erasure is invented here. P03-10 (G16) owns - it and re-verifies these transitions at its first writer. Until then the runbook - forbids replaying an event of a tenant in erasure. -10. **Runbook.** `docs/runbooks/operator-recovery.md` covers the signal, inspection, the - replay-versus-reset choice, what is not recoverable, the invitation reissue path and - how to verify that the row became due and the real executor completed it. + mode, and the catalogue's dashboard-absence rule stays. The inspection set is the + operator's view. A dashboard write control is never admitted. A read-only dashboard + needs its own decision on authentication, the dependency and the source borrower. +9. **Erasure.** The Active-tenant test in § 2 and § 3 is the guard until P03-10 (G16) + defines a replay floor after erasure, and P03-10 re-verifies these transitions at its + first writer. The runbook states the limit. +10. **Signals and runbook.** Counters record each operation by outcome and fence + refusals separately, so a monitoring owner can see a replay storm. + `docs/runbooks/operator-recovery.md` covers the signal, inspection, the + replay-versus-reset choice, what is not recoverable, the invitation limit and how to + verify that the row became due and the real executor completed it. ## Context The existing replay is correct in shape and unsafe in use: it checks the row state and nothing about which state the operator saw. A fence token is the smallest change that -makes a second operator's stale decision refuse instead of act. The producer side is -admitted narrowly because its one recoverable case is real. A burst of dispatch failures -longer than the six-attempt budget strands an event with no remedy, and acceptance is -idempotent by stable identity, so a deliberate redispatch is safe. The three invalid -reasons are not recoverable by any operator and are refused by the same code that proves -the fence. +makes a second operator's stale decision refuse instead of act. Inspection moves to the +platform scope because it is the only act that reads across tenants, and column grants +make the projection a database fact with the scope's entry row as its audit. The +transitions stay on the outbox role because they cross no tenant and need no new write +grant. + +The producer side is admitted narrowly because its one recoverable case is real. A burst +of dispatch failures longer than the six-attempt budget strands an event with no remedy, +and acceptance is idempotent by stable identity, so a deliberate redispatch is safe. Job recovery is left closed because the closing condition is evidence the runtime cannot -get from an operator. That is a real limit, not a deferral for convenience: with a lost -SMTP reply the four tenant invitation slots can stay occupied, and the remedy lives in -the invitation contract. Admitting an attested release would reopen -[ADR-0047](0047-transactional-background-job-runtime.md) and is a decision for the phase -that has a provider able to prove quiescence. +get from an operator. That is a real limit, not a deferral for convenience. The dashboard is the one place this ADR departs from the roadmap's wording of D13. The roadmap says the dashboard is admitted behind the Platform gate. The findings above show @@ -150,19 +182,19 @@ adapter that supplies quiescence proof, or a measured need to re-arm reconciliat ### Positive - C15's stale-fence, sibling, producer-versus-subscriber and audit proofs have real - subjects, with no new grant and no widened bypass role. + subjects, and the projection is enforced by grants. - An operator sees exactly what a transition will act on, and a stale decision refuses. - ADR-0015's false guidance is withdrawn with a dated disclosure. ### Negative +- A column-grant migration on a `BYPASSRLS` role, and a second outbox status writer. - The operator has no dashboard, only an API and a runbook, until a UI exists in the Hub operator portal. -- A stuck external job has no operator remedy beyond domain-level reissue, which is +- A stuck external job has no operator remedy, which is [ADR-0047](0047-transactional-background-job-runtime.md)'s rule restated, not softened. -- The producer reset renews the retry budget and may deliver a historical event to a - subscription activated since. The runbook states both. +- The producer reset renews the retry budget, and the runbook says so. ### Neutral @@ -171,34 +203,38 @@ adapter that supplies quiescence proof, or a measured need to re-arm reconciliat ## Implementation Notes -- Step 3 delivers the owner, routes, fences, the two witness-bound seams, census edits, - the ADR-0015 and ADR-0046 disclosures and the runbook. The pinned grant expectations - and the `DeliveryDispatchBoundaryTests` signature census change with the code. +- Step 4 delivers the grants migration with the canonical SQL, the owner, routes, + fences, the two witness kinds, census edits, the ADR-0015 and ADR-0046 disclosures and + the runbook. The grant expectations and the delivery-boundary signature census change + with the code. - Proof: a replay with a current fence completes and the real executor runs once; a - stale fence, a completed, live, pending, privileged and retired delivery each refuse; - the sibling, another tenant, another event, the inbox and the producer row are - byte-identical; a reset of each invalid reason and of a processed row refuses; a - forced audit fault leaves no change; a tenant token, a wrong-purpose token and a - different Platform permission fail before the outbox credential is resolved; - `/admin/hangfire` is 404 in every mode; quarantined job rows are byte-identical after - every act. The mutation targets are the fence comparison, the reason filter and the - result row. - -## Carriers owed at acceptance + stale fence, a completed, live, pending, privileged, retired, `invalid_envelope` and + inactive-tenant delivery each refuse; the sibling, another tenant, another event, the + inbox and the producer row are byte-identical; a reset of every other reason and of a + processed row refuses; a forced audit fault leaves no change; a tenant token, a + wrong-purpose token and a different Platform permission fail before any credential is + resolved; the platform role cannot select an excluded column; `/admin/hangfire` is 404 + in every mode; quarantined job rows are byte-identical after every act. The mutation + targets are the fence comparison, the reason filter, the tenant test and the result + row. + +## Carriers Dated disclosures in [ADR-0015](0015-api-gateway-apisix.md) (Amendment 2: the realm-role gate bullet quoted and withdrawn, the route stays absent), -[ADR-0046](0046-durable-event-delivery-and-recovery.md) (the replay and reset contract), -[ADR-0047](0047-transactional-background-job-runtime.md) (operator reconciliation is -inspection only), [ADR-0044](0044-audit-write-path.md) (the two witness kinds). +[ADR-0046](0046-durable-event-delivery-and-recovery.md) (the replay and reset contract +and the second writer), [ADR-0047](0047-transactional-background-job-runtime.md) +(operator reconciliation is inspection only, and the platform column grants), +[ADR-0044](0044-audit-write-path.md) (the two witness kinds). [Phase 11](../roadmap/phase-11-production-hardening.md)'s replay and requeue statements, -Standard 20's dashboard line, the Phase 03 D13 wording and the dangling fragment in -[Architecture 30](../architecture/30-api-gateway.md) follow. +Standards 05 and 20, the Tenancy audit matrix, the Phase 03 D13 wording, and the stray +fragment in the checklist of [Architecture 30](../architecture/30-api-gateway.md) +follow. ## References - [ADR-0101](0101-platform-operator-authority.md), - [ADR-0102](0102-production-tenant-onboarding-and-authority-rebind.md) + [ADR-0102](0102-production-tenant-onboarding.md) - [ADR-0015](0015-api-gateway-apisix.md), [ADR-0046](0046-durable-event-delivery-and-recovery.md), [ADR-0047](0047-transactional-background-job-runtime.md), diff --git a/docs/decisions/0104-controlled-issuer-rebind.md b/docs/decisions/0104-controlled-issuer-rebind.md new file mode 100644 index 00000000..622ad6e5 --- /dev/null +++ b/docs/decisions/0104-controlled-issuer-rebind.md @@ -0,0 +1,185 @@ +# ADR-0104: Controlled Issuer Rebind + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes the controlled issuer-rebind part of gate G13 together with +[ADR-0101](0101-platform-operator-authority.md) and +[ADR-0102](0102-production-tenant-onboarding.md), and authorizes the code it describes. +It is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) installs `identity_authority` + once and says P03-9 owns "a frozen-admission, privileged issuer rebind after proven + provider continuity, preserving AuthorityId, actors, keys and closed tombstones". + Until then rename is unsupported, and the installer refuses any conflicting anchor. +- Subject keys hash the stable `AuthorityId` and the exact opaque `sub`, never the + issuer URL ([Database Standards](../standards/05-database.md)). An origin change that + preserves both leaves every key valid, and a changed `AuthorityId` re-keys every + person and can resurrect a closed tombstone. +- The API qualifies `identity_authority` once per process in a read-only transaction and + refuses admission on a mismatch. The read takes no lock, so a process that starts + while a rebind runs can qualify against the old value and keep it until restart. +- The platform role runs in the API and worker hosts and bypasses row security. A column + grant on it would let any platform-scope code path change the issuer, and a + transaction-local setting is not a control, because any session can set it. +- The owner role used by the installer cannot write `audit_log`, so an owner-credential + change could not commit with its audit row. +- C14 asks for positive and denied proof, partial-commit proof and identity-continuity + proof, and says the dev seed authority is insufficient. + +## Considered Options + +1. **A dedicated rebind role used only by an offline tool that authenticates the human** + (chosen). The credential never reaches a runtime host, the change and its audit row + share one transaction, and the proof runs before the change. +2. **A column grant to the platform role guarded by a transaction setting** (rejected). + Every runtime platform connection holds it, and the setting is settable by any + session. +3. **The owner credential through the installer** (rejected). It cannot commit an audit + row with the change, and the installer is built to refuse a conflicting anchor. +4. **An HTTP operator act under a runtime admission freeze** (rejected). It adds a + database read to every authentication, and running processes keep the old issuer + because qualification is startup-only. + +## Decision + +1. **What changes.** Only the origin of `identity_authority.issuer`, under the same + realm path. `AuthorityId`, subject keys, actor ids and closed tombstones are + preserved, no realm rename is admitted, and the new realm must preserve each `sub`, + which a realm export and import does. +2. **The role.** A sixth login role, `learnstack_identity_rebind`, without `BYPASSRLS`, + holds exactly: `SELECT` and `UPDATE (issuer)` on `identity_authority`; `SELECT` of + `authority_id`, `subject_key`, `provider_subject` and `status` on `users`; and an + `INSERT` on `audit_log` that a policy limits to the platform sentinel, the identity + module and the two rebind operations, written only through the witness-bound methods + of [ADR-0101](0101-platform-operator-authority.md) § 10. Its connection string, + `ConnectionStrings:IdentityRebind`, exists only in the tool's environment, and an + architecture rule confines the key to the tool. +3. **The tool.** A new project, `LearnStack.Tools.IdentityAuthorityRebind`, separate + from the install-once installer. It reads the human's operator access token from + standard input or the environment, never an argument, validates it with the operator + validator of ADR-0101, and is the second sanctioned caller of the witness minter. The + operator must hold `platform.identity_authority.admin`. A refusal exits non-zero with + no change. +4. **A read-only realm credential.** The continuity proof enumerates users with a + `view-users` credential the operator supplies at run time. It is not a LearnStack + runtime or federation credential, and + [ADR-0099](0099-confined-tenant-federation.md)'s refusal of user-level authority for + LearnStack is unaffected. +5. **Freeze.** The tool runs in one transaction on a direct, non-pooled connection and + takes an exclusive transaction-level advisory lock on a fixed key as its first + statement. Authority qualification and the User-creation admission transaction take + the shared form of that lock, so a start or a new binding waits for the rebind and + then reads the new value. The tool also refuses while it sees a session of the + application, outbox or ingress role other than its own. A process that holds no + database connection is invisible to that check, so the runbook's stop step is the + control for it. Such a process keeps the old issuer only until it restarts, because + qualification then fails on the mismatch. +6. **Continuity proof.** Inside the lock, the tool reads the new issuer's discovery + document and key set and requires its `issuer` to equal the new value. It enumerates + the new realm's users completely or refuses. Every Active `provider_subject` must be + among the enumerated `sub` values. The canonical subject key of no enumerated `sub` + may equal a Closed user's key, so a closed person cannot reappear. A new-realm user + with no stored key is allowed, because that person has not bootstrapped. A refusal + reports counts and never identifiers. +7. **The change.** `UPDATE identity_authority SET issuer = @new WHERE id = 1`. A trigger + refuses any change to `id` or `authority_id`. The issuer grammar stays in the tool + and in qualification, which refuses a malformed or mismatched issuer, and is not + duplicated in SQL. +8. **Audit.** A short standalone transaction commits an intent row first, so an aborted + attempt is on record. The main transaction writes the MUST result row with the + change, and a forced audit failure rolls the change back. Both rows use the platform + sentinel and `metadata.operator`, and carry the ticket, because no tenant can read + them. +9. **Retry.** Every refusal leaves the state unchanged and a retry repeats the whole + proof. A tool run whose target already equals the stored issuer succeeds without + writing a row. An unknown COMMIT is reconciled by reading the issuer. +10. **After the change.** Processes configured with the old issuer fail qualification at + their next start. Deploying the new issuer configuration is the unfreeze. +11. **Signals.** Counters record each run by outcome and the continuity result by class. + +## Context + +A rebind is rare and dangerous, so it is shaped to be hard to do by accident. An HTTP +act would need a freeze on every authentication and still could not retire the issuer +that running processes hold. A dedicated role makes the strongest claim cheap to check: +no runtime host has the credential, so no runtime code path can change the issuer, +whatever it does. The cost is a sixth role, whose precedent is the fifth, +`learnstack_identity_ingress`, added the same way by +[ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md). + +The advisory lock closes the start race without a request-path read: qualification runs +once per process and user creation is rare, so a shared lock on each costs nothing +measurable. What it cannot close is a process that is running, idle and connectionless +when the tool runs. The honest statement is that the operator's stop step and the +restart requirement bound that case, not the database. + +The proof compares against the stored facts rather than trusting an attestation. Active +rows retain the exact subject, so presence is a direct comparison; Closed rows retain +only the key, so absence needs the canonical encoding. + +What would reopen this: a realm rename, a federated authority change, or a need to +rebind without a downtime window. + +## Consequences + +### Positive + +- No runtime role or host can change the issuer, and the change, its proof and its + result row are checkable. +- Starts and new bindings cannot straddle the change. +- Denied, partial and continuity cases have exact subjects. + +### Negative + +- A sixth database role, its provisioning, grants and census. +- A downtime window, and an operator-supplied read credential for the new realm. +- A connectionless survivor is bounded by procedure, not by the database. + +### Neutral + +- The install-once installer and its refusal of a conflicting anchor are unchanged. +- Development environments never need a rebind. + +## Implementation Notes + +- Step 3 delivers the role and its provisioning in the local stack and test fixtures, + the grants and trigger migration with the canonical SQL, the tool, the lock calls in + qualification and the creation transaction, the two audit methods and the runbook. + Grant tests read column privileges, not table privileges, because table-level views do + not show column grants. +- Proof: positive; no token, wrong audience, missing permission, stale authentication; + killed between the intent row and the main transaction, and before commit; an unknown + COMMIT; a forced audit failure; a missing Active subject; an extra new-realm user + allowed; a Closed key present refusing; a live second session refusing; a start that + blocks on the lock and then fails the mismatch; an unchanged `AuthorityId`; the + trigger refusing an `authority_id` change; the architecture rule on the + connection-string key. The mutation targets are the continuity comparison, the + Closed-key check, the lock and the rollback on audit failure. + +## Carriers + +Dated disclosures in [ADR-0003](0003-tenant-isolation-defense-in-depth.md) (the sixth +role), [ADR-0044](0044-audit-write-path.md) (the rebind rows), and +[ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the rebind +contract). Standards 05 and 11, the Identity module specification, the Phase 03 Status +and the runbook follow. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0102](0102-production-tenant-onboarding.md) +- [ADR-0003](0003-tenant-isolation-defense-in-depth.md), + [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md) +- [Database Standards](../standards/05-database.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 2b63cb2a..0530e17d 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -143,9 +143,10 @@ records hosted qualification. Phase 11 owns production qualification. | 0098 | [Session-Targeted Back-Channel Logout](0098-session-targeted-back-channel-logout.md) | Accepted 2026-11-12 after maintainer review: signed sid-targeted native notification, bounded replay/late-publication fences and owned callback-only TLS reachability; delivery/proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation (Steps 0–4, including the Keycloak pin move to 26.7.5) is delivered and merged in PR #45; the [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns packet state. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | | 0100 | [P03-8 Federation Contract Transition](0100-p038-federation-contract-transition.md) | Accepted 2026-11-18 after the maintainer's review, four independent reviews and the development-only/no-active-use confirmation: one exact snapshot-, finding- and comparator-bound incompatibility for registry v4, federation administration and the self `federationAlias`, one carrier per ADR and a stated end of the exception's basis; the later growth of the closed grant contract stays open as G20; delivery and proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | -| 0101 | [Platform Operator Authority](0101-platform-operator-authority.md) | Proposed 2026-11-19: one human operator population at a pinned issuer, a separate strict scheme on `/api/platform/v1`, per-act grants held by LearnStack, an admission witness, attributed result audit and the killswitch writer; closes nothing until Accepted. | -| 0102 | [Production Tenant Onboarding and Authority Rebind](0102-production-tenant-onboarding-and-authority-rebind.md) | Proposed 2026-11-19: operator-admitted tenant, Role-template, first-admin and recovery acts on the app role, and an offline admitted issuer rebind with a continuity proof; closes nothing until Accepted. | -| 0103 | [Operator Recovery of Asynchronous Work](0103-operator-recovery-of-asynchronous-work.md) | Proposed 2026-11-19: metadata inspection, fenced targeted subscriber replay and a narrow producer reset on a confined outbox-role owner; no job release, no dashboard; closes nothing until Accepted. | +| 0101 | [Platform Operator Authority](0101-platform-operator-authority.md) | Accepted 2026-11-19 after the maintainer's decisions and three independent reviews: one human operator population at a deployment-controlled issuer, a second strict scheme confined to `/api/platform/v1`, per-act grants held by LearnStack, an admission witness, attributed result audit and the killswitch writer. | +| 0102 | [Production Tenant Onboarding](0102-production-tenant-onboarding.md) | Accepted 2026-11-19: operator-admitted tenant, host, Role-template, first-administrator and recovery commands on the app role, with a confined operator source and target announcement; the seed stays seed-only. | +| 0103 | [Operator Recovery of Asynchronous Work](0103-operator-recovery-of-asynchronous-work.md) | Accepted 2026-11-19: metadata inspection on column grants, fenced targeted subscriber replay and a narrow producer reset on a confined outbox-role owner; no job release and no dashboard. | +| 0104 | [Controlled Issuer Rebind](0104-controlled-issuer-rebind.md) | Accepted 2026-11-19: an offline operator act through a dedicated rebind role, with advisory-lock freeze, a continuity proof over every stored subject key, intent and result audit rows. | ## Proposed ADRs diff --git a/docs/glossary.md b/docs/glossary.md index e6b57900..b583d3cf 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -11,8 +11,8 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Tenant** | A logical education platform or brand running on LearnStack. One LearnStack deployment can host many tenants. Each tenant has its own domain, branding, content, courses, and members. | | **Organization** | A sub-unit within a tenant — a branch, campus, studio, department, or cohort. Two-level hierarchy strict (`Tenant → Organization`, no nesting) per [ADR-0017](decisions/0017-tenant-organization-hierarchy.md). Every tenant has at least one default organization. | | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | -| **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm. Operates above tenants. | -| **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; finer-grained roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`). | +| **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | +| **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | | **Org Admin** | A user with administrative rights inside a single organization within a tenant. | | **Deployment Mode** | One of `Development` / `SaaS` / `Dedicated` / `SelfHostedOnline` / `SelfHostedAirGapped` per [ADR-0020](decisions/0020-triple-deployment-hybrid-license.md). Selected at composition root; module code never branches on it. The two `SelfHosted*` variants differ on phone-home availability (entitlement source). | diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index b29617d8..8b4cc3be 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -159,14 +159,14 @@ unmarked row is one a shipped command already raises. | `TenantSetting` | `tenancy.setting.soft_delete` `(planned)` | **MUST** | Removing a setting is a change to it, so the same baseline row covers it — and `ux_tenant_settings_tenant_id_organization_id_key` is partial on `deleted_at IS NULL`, so the key becomes free for a successor | | `Tenant` | `tenancy.locale.write` | SHOULD | Configuration; contained TenantLocale changes are captured with their owning Tenant root | | `TenantFeatureFlag` | `tenancy.feature_flag.write` `(planned)` | **MUST** | "Feature flag toggled" is on the same baseline row, and [Feature Flags § Audit](../../architecture/21-feature-flags.md) classes both flag surfaces as security events | -| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` `(planned)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`, which is what gives the row a real actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | +| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` `(planned)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | | `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, for the reason `tenancy.killswitch.toggle` carries both: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | | `platform_host_to_tenant` | `tenancy.hostmapping.write` | **MUST** | The resolution index — the row that decides whose data an anonymous request sees | | `platform_host_to_tenant` | `tenancy.hostmapping.delete` `(planned)` | **MUST** | The same row removed. The table carries no `deleted_at`, so the delete is a row gone and a host that resolves to nobody | | `TenantAssertion` | `tenancy.tenant_assertion.reject` `(off-path)` | **MUST** for admitted events (`security-event`) | A validated header/claim mismatch with an independently defended host tenant is recorded under that host tenant, never the asserted tenant or sentinel; row 14 is counted only. [ADR-0065](../../decisions/0065-bounded-tenant-assertion-diagnostics.md) admits 600 authenticated standalone write attempts per host tenant per API instance per first-request-anchored monotonic minute, shared across scoped recorders, actors, sources and dimensions. Failed writes consume permits; later occurrences make no audit-store call and retain their refusal, count and exactly one attributed Warning (4006 replaces normal 4001). An attacker can exhaust the allowance, so later actors lose durable evidence; aggregate log volume remains unbounded. Admitted events retain MUST failure/health behavior, tenant-wide organization scope, exact actor/correlation and trusted organization in metadata. No tenant `AuditConfig` override or independent tenant-registry cap exists. General mutation MUST durability is unchanged. Packet 9 owns the recorder/decorator path; P02b-5 Steps 3–4 implement JWT attribution and HTTP activation under ADR-0064. ADR-0065 acceptance precedes the dependent budget implementation; the [merge closeout](../../roadmap/phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) owns its final delivery status | | `TenantAssertion` | `tenancy.tenant_assertion.anonymous_burst` `(off-path)` | **MUST** (`security-event`) | The anonymous half of the same detector, written once per `(resolved tenant, dimension, window)` when the mismatch counter crosses its threshold. An anonymous mismatch is not itself an audited operation; the burst is — the precedent the baseline's "login failure burst" already sets ([ADR-0036 Amendment 7](../../decisions/0036-tenant-resolution-trusted-inputs.md)). Same writer, and `(off-path)` for the same reason. The window is **in-process** and never `ICacheService` — a cache outage must not decide whether a MUST-class security event is recorded — so the effective threshold is per instance, which errs toward more auditing. `Tenancy:AssertionBurst` sets it; the defaults are ten occurrences in five minutes | | Confirmed claim-context assertion | `tenancy.assertion.reject_claim_context` `(off-path)` | **MUST** (`security-event`) | A header conflicting with actual successful ClaimAndMembership resolution uses the confirmed tenant/actor, fixed dimension/reason and membership-confirmed source. No asserted UUID or host allowance. The production claim-context recorder and central evidence owner implement this path; [Phase 03](../../roadmap/phase-03-identity-admin.md) owns qualification. | -| any | `platform.admin_scope.enter` `(off-path)` | **MUST** (`security-event`) | Cross-tenant access is the one read worth a row; [Audit Coverage](../../standards/18-audit-coverage.md) puts every platform-bypass invocation on `security-event`. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships it: an admitted `PlatformAdminScope.EnterAsync` writes the row through `IAuditStore.WritePlatformScopeAsync` on the scope's own platform-role connection, in a transaction of its own that **commits before** the caller's begins — so work that later fails, throws or is abandoned cannot take the record with it — carrying `TenantId.PlatformSentinel` ([ADR-0044 § 1, § 10](../../decisions/0044-audit-write-path.md)). An entry the catalogue cannot classify, or whose row cannot be written, is **refused** — no transaction is handed out for it. The `Warning` log line stays beside the row, carrying its id, as the real-time signal the row is not. `EnterAsync` is a service method and not a MediatR request, and the catalogue is keyed by request type — so its catalogue entry is registered by slug rather than by request type. Its module segment is `platform` for the same reason: the scope belongs to no module's request path. The permission gate denies before opening a connection; those denied attempts write no entry row. Phase 03 must decide denied-entry evidence before its first privileged consumer | +| any | `platform.admin_scope.enter` `(off-path)` | **MUST** (`security-event`) | Cross-tenant access is the one read worth a row; [Audit Coverage](../../standards/18-audit-coverage.md) puts every platform-bypass invocation on `security-event`. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships it: an admitted `PlatformAdminScope.EnterAsync` writes the row through `IAuditStore.WritePlatformScopeAsync` on the scope's own platform-role connection, in a transaction of its own that **commits before** the caller's begins — so work that later fails, throws or is abandoned cannot take the record with it — carrying `TenantId.PlatformSentinel` ([ADR-0044 § 1, § 10](../../decisions/0044-audit-write-path.md)). An entry the catalogue cannot classify, or whose row cannot be written, is **refused** — no transaction is handed out for it. The `Warning` log line stays beside the row, carrying its id, as the real-time signal the row is not. `EnterAsync` is a service method and not a MediatR request, and the catalogue is keyed by request type — so its catalogue entry is registered by slug rather than by request type. Its module segment is `platform` for the same reason: the scope belongs to no module's request path. The permission gate denies before opening a connection; those denied attempts write no entry row. [ADR-0101 § 11](../../decisions/0101-platform-operator-authority.md) decides denied-entry evidence: a counter and a Warning log, no durable row | A feature flag that gates a **billed** capability is not a `tenant_feature_flags` row at all. It is plan-level, it is written only by diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 9c668aca..983865b2 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,8 +509,9 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 138 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 264 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines + - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines @@ -24306,3 +24307,129 @@ ADR-0099 (Amendment 10) and ADR-0100; Standards 04, 05, 11, 12, 13, 18, 19, 20 a Architecture 13, 28 and 30; the glossary; the Identity and Tenancy module specifications; and the Phase 03 and Phase 11 documents. This proposal edits none of them. + +### P03-9 package review dispositions and acceptance (2026-11-19) + +**Status: Accepted.** This record closes gates G13 (human operator authority, +production provisioning, first administrator, recovery and issuer rebind) and G14, and +accepts [ADR-0101](../decisions/0101-platform-operator-authority.md), +[ADR-0102](../decisions/0102-production-tenant-onboarding.md), +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md). Where it differs from the +[proposed package](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19), +this record governs: the proposal's single onboarding-and-rebind ADR is split, and its +four-step plan becomes five. + +#### Maintainer decisions + +The maintainer chose, on the four forks the proposal presented: no dashboard (the +inspection set replaces it, and D13's wording changes); the narrow producer reset is +included; the operator client is the served operator document plus runbooks, with no +screen and no command-line client in this repository; operator grants come from a +configuration adapter behind a port, with the table adapter on a named trigger. The +maintainer then supplied three independent reviews of the Proposed package, asked that +each finding be analysed against the code and the corpus because the reviewers did not +know the process, confirmed that the application is in development and not in use so +no backward compatibility is owed, and asked for acceptance and continued +implementation once the corrections were made. + +#### Verification of the findings + +The maintainer's session checked each claim that would change a decision against `HEAD` +before acting. The following were confirmed: the seed guard demands a single `Seed` +source, an exact trusted `Seed` source and the fixed declaration, and the API registers +deny-all seed continuation and foundation admissions; the first-admin command refuses +any Membership history; authority qualification reads once per process without a lock; +the route convention exempts only `api/internal`, and the tenant document includes only +`/api/v1` paths; ADR-0064 registers exactly one tenant bearer scheme; the platform role +holds no grant on `federation_connections`; the outbox role holds table-wide `SELECT` on +`outbox_messages` and a lifecycle-column `SELECT` on `tenants`; ADR-0093 says reissue +does not reconcile the old effect; the stray fragment in Architecture 30 existed; and +ADR-0040 counts ten logical tenant setters, four context writers and eight definers, not +eight setters. + +#### Dispositions + +| Finding (review labels) | Disposition | +|---|---| +| Rebind guard is not a control: a platform-role grant plus a settable setting (R2 B1, R1) | Fixed. A dedicated rebind role replaces the platform grant (ADR-0104 § 2) | +| Freeze window: qualification reads without a lock (R2 B2) | Fixed. Shared advisory lock on qualification and user creation (ADR-0104 § 5) | +| Seed policies "stay Seed" versus "alongside Seed" (R2 B3, R3 B1) | Fixed. Separate operator commands; the seed guards are untouched (ADR-0102 § 1, § 2) | +| Recovery is not the first-admin act (R3 B2, R2 M13) | Fixed. Two predicates, both under the ordered locks (ADR-0102 § 7, § 8) | +| First-admin could escalate a tenant that has administrators (R3 B7) | Fixed. First-admin refuses any Membership history (ADR-0102 § 7) | +| Target tenant contradicts the no-request-value rule (R3 B3, R2 M3) | Fixed. One confined eleventh setter, disclosed in ADR-0036 and ADR-0040 | +| Ordinary pipeline cannot carry operator attribution (R3 B4) | Fixed. The audit-composition branch is named (ADR-0102 § 9, ADR-0033 and ADR-0044) | +| Offline tool cannot mint the witness (R3 B5) | Fixed. One minter, two sanctioned callers (ADR-0101 § 7, ADR-0104 § 3) | +| Rebind needs `SELECT` and a user-reading credential (R3 B6, R2 M12, M14) | Fixed. Table `SELECT`, a read of four `users` columns, a run-time realm credential, a separate tool project | +| `/api/platform/v1` does not fit the route and OpenAPI mechanics (R3 B8, R2 M10) | Fixed. Prefix list, own document, census and classifier entries (ADR-0101 § 4); the gateway routes none | +| Subscriber replay does not filter terminal reasons (R3 B9, R2 M19) | Fixed. `invalid_envelope` always refused (ADR-0103 § 2) | +| Producer reset claim about every Active subscription is wrong (R3 B10) | Fixed. Only subscriptions with no delivery row are reached (ADR-0103 § 3) | +| Operator denial versus ADR-0077 and Standard 18 (R3 B11, R2 M1, R1) | Kept the decision, added the disclosures (ADR-0077 Amendment 2, Standard 18) | +| Ticket, reason, actor and `toggled_by` mapping (R3 B12, R2 M6) | Fixed. Ticket only in sentinel rows; business actor `SystemActor`; `toggled_by` NULL (ADR-0101 § 9) | +| Issuer may be any OIDC provider (R2 M2) | Fixed. Always a deployment-controlled issuer (ADR-0101 § 1, § 3) | +| Platform key set omits Standard 19's examples (R2 M4) | Examples stay unregistered; Standard 19 cites the catalogue | +| Federation keys have no owning ADR (R2 M5) | Fixed. ADR-0099 Amendment 10 | +| Sentinel class unnamed; "second caller" wrong (R2 M7, M8) | Fixed. The platform-scope class is extended by name; a new method, not a second caller (ADR-0044 Amendment 17) | +| Demo operator grant reachable in production (R2 M9) | Fixed. Refused unless Development (ADR-0101 § 6) | +| Tenant id is server-generated, so a lost reply loses it (R2 M11) | Fixed. The operator supplies a UUIDv7 and a slug; the act is idempotent on the pair | +| Host mapping is not an existing command; DNS unverified (R2 M15) | Fixed. A new operator command; the operator asserts ownership (ADR-0102 § 4) | +| Grant tests cannot see column privileges (R2 M16) | Fixed. Column-privilege tests are required (ADR-0103, ADR-0104) | +| No actor identity for operator acts (R2 M17) | Fixed. `SystemActor` in business columns; operator in audit | +| Inspection reads cross-tenant on a role with table-wide `SELECT` (R2 M18, M21) | Fixed. Inspection moves to the platform scope on named column grants | +| "Reissue" is not a remedy (R2 M20) | Fixed. Stated as a limit (ADR-0103 § 6) | +| Operations and routes missing in ADR-0103 (R2 M22) | Fixed. An operation table with permission, principal and audit | +| Erasure guard is runbook-only (R2 M23) | Fixed. An Active-tenant test until P03-10 | +| New outbox status writer versus CLAUDE.md (R2 M24) | Fixed. ADR-0046 Amendment 5 and the CLAUDE.md rule name the owner | +| Carrier lists incomplete or inconsistent (R2 M25, R3, R1) | Fixed. Each ADR lists its full set; the amendments are applied in this commit | +| ADR-0064 says exactly one scheme (R2 M26) | Fixed. Amendment 9 confines the second scheme | +| Rebind retry, enumeration time and reload mechanism (R1) | Fixed (ADR-0104 § 9; ADR-0101 § 6) | +| Permission table broken (R1, R2) | Fixed. My reflow script had wrapped an indented table; it now skips tables | +| Counters for replay and operator acts (R1) | Fixed. ADR-0101 § 14, ADR-0103 § 10 | +| Self-Hosted issuer must emit `acr` (R1) | Fixed. ADR-0101 § 3 and the runbook | +| Producer reset admits only `retry_exhausted` (R2) | Kept; `unknown_type` rows are not recoverable by reset | +| README placement of Proposed rows (R1) | Moot; all four are Accepted rows in the active table | +| Review severity labels | Not adopted; each finding was judged on its effect | + +Minor wording findings (key names, undefined terms, glossary terms, the 400 versus 403 +for a malformed ticket, "its MUST rows", the "one new realm client" count, the SQL +confinement wording, `OperationPolicyCatalog`, the dashboard-package wording, the rule +name) were corrected in the ADRs. The catalogue's dashboard-absence rule and the code +test that enforces it carry different names; Step 4 reconciles them. + +#### Accepted decisions + +- Operators authenticate at a deployment-controlled issuer through a second strict + scheme on `/api/platform/v1`, with MFA shown by `acr` and `auth_time`. Authority is a + LearnStack-held Platform grant evaluated per act. Admission is a witness, and results + commit with state. +- Production onboarding is five operator commands on the app role, a confined operator + source and an eleventh logical setter. The seed stays development-only. +- The issuer rebind is an offline operator act through a dedicated role, a lock, a + continuity proof, a guarded row and intent and result audit rows. +- Recovery is inspection on column grants, fenced subscriber replay and a narrow + producer reset. Job recovery, recurrence recovery and every dashboard form stay + absent. +- Federation operator steps are ADR-0099 Amendment 10. G20 is not triggered and stays + Open. + +#### Five implementation steps + +1. **Operator authority and killswitch** (ADR-0101). +2. **Production onboarding** (ADR-0102). +3. **Controlled issuer rebind** (ADR-0104). +4. **Operational recovery** (ADR-0103). +5. **Federation operator steps** (ADR-0099 Amendment 10). + +Each step ends with its own commit, a fresh independent review round and its verified +fixes, then a different fresh round and its verified fixes, before the next begins. +Closeout follows with Status, the register and the delivery record. + +#### Carriers applied in this commit + +Dated disclosures in ADR-0003, 0004, 0015, 0033, 0036, 0040, 0044, 0045, 0046, 0047, +0064, 0072, 0073, 0074, 0077, 0099 and 0100. Corrections to Standards 04, 11, 12, 13, 18 +and 19, Architecture 13, 28 and 30, the glossary, the Tenancy audit matrix, Phase 03 +(Status, register, section and deliverables), Phase 11 and the CLAUDE.md outbox rule. +Standard 05 grants and definers, Standard 19 key rows, Standard 21 rules, the permission +and audit matrices and the runbooks land with the steps that use them. No gate other +than G13 and G14 changes status, and no behavior is implemented by this record. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index a1375b17..82585b08 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -24,7 +24,7 @@ > [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) records > final-head `5eeba2c3` layout A (27/27, attempt 3). Opposite-layout B/pair > qualification stays open before P03-11 exit; manual accessibility was not performed. -> G12 is closed as Accepted; G20 stays Open. P03-9–11 remain unstarted. +> G12 is closed as Accepted; G20 stays Open. P03-10 and P03-11 remain unstarted. > > | Packet | Title | State | > |---|---|---| @@ -37,7 +37,7 @@ > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | -> | P03-9 | Platform authority and operational recovery | Not started | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | @@ -110,7 +110,7 @@ activation is not the only decision boundary. | P03-6 | Authenticated durable provider ingress and attributed, deduplicated Audit mirror | P03-1–2 | G10; G13 before any privileged/global intake the chosen mechanism requires | | P03-7 | Registered, authenticated back-channel logout with bounded provider/session indexes | P03-3 | G11; provider event mirroring is a distinct contract, not a prerequisite by filename | | P03-8 | Usable tenant SAML/OIDC configuration with safe linking and recovery | P03-3 | G12; G1/G4/G5 still bound issued identity and authority | -| P03-9 | Admitted Platform gate, production first-admin/issuer-rebind authority, killswitch, fenced recovery and dashboard | P03-2 | G13, G14; privileged execution remains closed until this contract ships; also owns the [ADR-0099](../decisions/0099-confined-tenant-federation.md) federation operator steps: the orphan-broker sweep, the operator disable of a broker the tenant cannot reach, and the delegated-account review | +| P03-9 | Admitted Platform gate, production first-admin/issuer-rebind authority, killswitch, fenced recovery and inspection (no dashboard) | P03-2 | G13, G14; privileged execution remains closed until this contract ships; also owns the [ADR-0099](../decisions/0099-confined-tenant-federation.md) federation operator steps: the orphan-broker sweep, the operator disable of a broker the tenant cannot reach, and the delegated-account review | | P03-10 | Subject-scoped DSAR, usable export, tenant erasure and separately authorized global closure/redaction | P03-3, P03-5, P03-9 | G15, G16; G10 only if this workflow consumes provider ingress; integrate all applicable delivered stores, including `federation_connections` and its broker ([ADR-0099](../decisions/0099-confined-tenant-federation.md)) | | P03-11 | Complete source-bound evidence, gateway scaffold correction and analyzer escalation | All implementation packets | G17, G18; no pending mandatory deliverable or unqualified production subject | @@ -150,14 +150,14 @@ named part, and the register links each explicit acceptance and vehicle. | G10 | What authenticated durable provider ingress is selected, and how are global events attributed? | Name producer, acknowledgement, stable provider-event dedup, ordering, tenantless/multi-membership routing, privacy and retention; enqueue through outbox, never direct business publication; no invented tenant or privileged app consumer | P03-6, or an earlier mechanism needing ingress | Provider-event ADR; ADR-0046/0057 boundaries, exact grants and Audit subscription | Accepted — 2026-11-11, [ADR-0097 and corrections](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11); [delivery and evidence record](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12) | | G11 | Which back-channel token profile, route and session targets are supported? | Separate OIDC purpose validation, signature/issuer/audience/time/events/no-nonce, replay retention, provider/session indexing and reachability; preserve late-work/accounting fences and unrelated/new session owners | P03-7 | ADR-0070 bounded extension; native route/provider configuration package | Accepted — 2026-11-12, [ADR-0098 and reviewed package](phase-03-delivery-log.md#p03-7-maintainer-review-corrections-and-acceptance-2026-11-12); implementation delivery is merged, with final-source evidence and the remaining pair qualification in the [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12) | | G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation delivery is merged, with evidence and follow-ups in the [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) | -| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Open for human/operator authority; machine-ingress slice only Accepted — 2026-11-11 under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) and its [acceptance](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11) | -| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Open | +| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Accepted — 2026-11-19, [ADR-0101](../decisions/0101-platform-operator-authority.md), [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); the machine-ingress slice was Accepted earlier under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md); implementation pending | +| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Accepted — 2026-11-19, [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); no dashboard is admitted; implementation pending | | G15 | Who may request which person's data in which tenant/org scope and for which recipient/purpose? | Separate self/admin/delegate authority, subject predicates and org boundaries; category is not disclosure authority; resolve third-party data, holds, eligibility and post-erasure status access | P03-10 request writer | Data Protection/Identity request contract and module matrices | Open | | G16 | How do exports, closure and privileged redaction finish durably? | Decide artifact delivery/reauthorization/expiry, job/storage prerequisites, participant inventory/write fence, last-membership case and provider finalization; exact erasure grants/order/immutable references, user-reference locators and result-audit/inbox reconciliation | P03-1 only for shared closure-fence invariants; P03-10 workflow | Data Protection and ADR-0044/0046 privileged contract; migrations, module participation and phase package | Accepted shared fence; P03-10 workflow Open | | G17 | Which real production subjects and product journeys prove complete phase exit? | All deliverables/criteria, inherited catalogue clauses, no skips/empty censuses, real provider/native/app-role paths, manual accessibility and complete source-bound CI; analyzer escalation stays at exit | P03-11; packets retain their own proof | Phase package, evidence index, catalogue and existing test owners | Open | | G18 | Which gateway scaffold corrections ship without activating the gateway? | Apply Architecture 30 Rules 1–3: explicit version paths/priorities and separated credentials; retain disabled OIDC; reviewed per-public-read allowlist, lint and activation stay Phase 11 | P03-11 config writer | Phase package and Architecture 30; ADR-0035 trigger unchanged | Open | | G19 | How is personal-data classification and diagnostic redaction established before the first identity writer? | Census current PII-bearing subjects and missing-annotation control; distinguish snapshot markers from logs/errors; fixed descriptors and value canaries, including arbitrary nested values; custom-field history remains G9 | P03-1 first personal-data writer; P03-5 extends it | Data Protection, ADR-0044/0057 boundaries and module PII/audit specs | Accepted; current/global/contextual model classification and actual Identity diagnostic sink controls implemented and reviewed; custom-field history remains G9 | -| G20 | How does the closed administration grant contract grow after P03-8, when the pinned OpenAPI gate refuses every further assignable permission key? | [ADR-0100](../decisions/0100-p038-federation-contract-transition.md) measures the candidates: a transition record per release, a standing registry-growth rule enforced by the gate, or an open-key grant contract. Appending new union branches removes the positional companion findings under any of them and needs a registry-release contract the OpenAPI document builder does not have today. It also decides whether review of the carrier, decision and gate files becomes mechanical, for example with an owners rule | The first packet after P03-8 that adds an assignable permission key or alters the grant unions' bytes; P03-9 or P03-10 earliest | Maintainer decision: an ADR and, where it changes the gate, its controls | Open | +| G20 | How does the closed administration grant contract grow after P03-8, when the pinned OpenAPI gate refuses every further assignable permission key? | [ADR-0100](../decisions/0100-p038-federation-contract-transition.md) measures the candidates: a transition record per release, a standing registry-growth rule enforced by the gate, or an open-key grant contract. Appending new union branches removes the positional companion findings under any of them and needs a registry-release contract the OpenAPI document builder does not have today. It also decides whether review of the carrier, decision and gate files becomes mechanical, for example with an owners rule | The first packet after P03-8 that adds an assignable permission key or alters the grant unions' bytes; P03-10 earliest, because P03-9 adds only non-assignable Platform keys | Maintainer decision: an ADR and, where it changes the gate, its controls | Open | ### Entry and activation boundaries @@ -508,7 +508,7 @@ and provider token refresh alone cannot establish application permission freshne [Phase 02a Packet 9](phase-02a-kernel-tenancy.md) as `DenyAllPlatformAdminGate`, which refuses everyone — so every operation that needs the scope is unreachable, every killswitch toggle included. This phase replaces it with a gate that reads a - Platform-scope permission, and ships with it the killswitch toggle command, its + Platform-scope permission, and ships with it the killswitch writer, its permission key and its incident runbook: the writer Packet 9 withheld on purpose ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). [Permissions](../standards/19-permissions.md) reserves no killswitch or entitlement key @@ -558,34 +558,32 @@ browser-supplied tenant/org authority is not admitted by adding an admin screen. ### Operator recovery and dashboard admission -P03-9/G13 also owns the production first-admin and controlled issuer-rebind -authority defined by ADR-0072/0073. Before production onboarding, -qualify an admitted operator creating the finite Role templates in separate -transactions, then the first tenant-wide admin Membership with MUST audit. -Specify authorized retry after partial setup, wrong-tenant/operator denial, -unknown-COMMIT reconciliation and recovery without the development seed -capability. Tenancy provisioning remains its Tenant/default Organization pair. -An issuer rebind needs proven provider continuity and frozen admission, preserving -AuthorityId, actor IDs and tombstones; no production rename path exists before -this contract is accepted and delivered. Seed-backed P03-3 journeys may be -qualified earlier; they are not production onboarding proof. - -Phase 02b supplies internal targeted subscriber replay and no operator route. -This phase owns the operator outbox/dead-letter/subscriber-replay and job-recovery -surface. Before its first writer, settle the URL space under ADR-0036, exact -Platform-scope permission, reason, fenced transition and MUST audit/runbook; -producer reset is not an implied power of targeted subscriber replay. - -This phase also owns the application `/admin/hangfire*` mapping and its -Platform-scope permission. Append the dated ADR-0015 disclosure before replacing -its historical realm-role gate. Keycloak roles are not LearnStack authority. -Keep the route absent until the application gate and denied-route controls ship. +P03-9 delivers G13 and G14 under [ADR-0101](../decisions/0101-platform-operator-authority.md), +[ADR-0102](../decisions/0102-production-tenant-onboarding.md), +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md); the +[acceptance record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19) lists their dispositions. + +Production onboarding is operator-admitted commands on the app role: provision a Tenant +with its default Organization and hosts, create the finite Role templates in separate +transactions, create the first tenant-wide administrator Membership with MUST audit, and +recover a tenant that has none, with authorized retry after partial setup, wrong-tenant +denial and unknown-COMMIT reconciliation. The development seed capability is +insufficient. The controlled issuer rebind is an offline operator act that preserves +AuthorityId, actor IDs and tombstones; no other rename path exists. Seed-backed P03-3 +journeys may be qualified earlier; they are not production onboarding proof. + +Phase 02b supplied internal targeted subscriber replay and no operator route. ADR-0103 +admits metadata inspection, fenced targeted subscriber replay and a narrow producer +reset that is not an implied power of subscriber replay. Job requeue, reservation +release and recurrence recovery are not admitted, and no dashboard is mapped: +`/admin/hangfire*` stays absent in every deployment mode, and ADR-0015 Amendment 2 +withdraws its realm-role gate guidance. Keycloak roles are not LearnStack authority. Phase 11 owns APISIX defense in depth and gateway activation. -The first Platform-admin consumer must decide denied-entry evidence and enforce -connection lifetime: a connection retained after scope completion must not permit -an autocommit bypass. The current deny-all gate exposes no privileged consumer; -an admitted scope's entry row is not evidence of a denied attempt. +ADR-0101 decides denied-entry evidence, a counter and a log with no durable row, and the +handle contract that stops a connection retained after scope completion from running an +autocommit bypass. An admitted scope's entry row is not evidence of a denied attempt. ### Gateway Configuration Corrections @@ -807,8 +805,8 @@ identifies observable proof; a later packet completes dependent end-to-end paths | D09 | Authenticated durable provider-event ingress, identifier-only outbox facts and deduplicated Audit mirror | P03-6 | C11, C19 | | D10 | Authenticated OIDC back-channel logout, provider/session indexes and fenced local revocation | P03-7 | C12 | | D11 | Confined tenant federation configuration, safe linking, test/activate/rollback and recovery | P03-8 | C13, C20 | -| D12 | Platform-scope identity/permission gate, production first-admin/issuer rebind, attributed bypass, killswitch writer and runbook | P03-9 | C14, C19 | -| D13 | Fenced operator recovery and application Hangfire dashboard admission, exact permissions/grants/audit/runbooks | P03-9 | C15, C19 | +| D12 | Platform-scope identity/permission gate, production first-admin/issuer rebind, attributed bypass, killswitch writer, federation operator steps and runbooks | P03-9 | C14, C19 | +| D13 | Fenced operator inspection, subscriber replay and narrow producer reset, with the Hangfire dashboard decided absent, exact permissions/grants/audit/runbooks | P03-9 | C15, C19 | | D14 | Self/admin tenant-scoped DSAR requests, usable export/erasure, separate person-authorized global closure and privileged redaction | P03-10 | C17, C18, C20 | | D15 | Trusted audit request/actor enrichment, sensitive-read/denied coverage and user-reference locators | P03-2; P03-10 locator/redaction completion | C19 | | D16 | Corrected inactive gateway scaffold, LS0001/LS0002 Error, complete catalogue and source-bound exit evidence | P03-11 | C21 | diff --git a/docs/roadmap/phase-11-production-hardening.md b/docs/roadmap/phase-11-production-hardening.md index ab3853d0..36d12220 100644 --- a/docs/roadmap/phase-11-production-hardening.md +++ b/docs/roadmap/phase-11-production-hardening.md @@ -321,6 +321,17 @@ bounds request *cost* once a request is inside. Neither substitutes for the othe - Confirm-link page copy. The realm ships no localization text or theme, so the page that confirms a link is Keycloak's own and does not state the delegation risk; this phase owns the production realm theme that does. +- Platform operator surface + ([ADR-0101](../decisions/0101-platform-operator-authority.md) to + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). This phase decides gateway + exposure of `/api/platform/v1`, which the scaffold does not route; enforces MFA for + the operator client in the production realm, because LearnStack checks the claim but + the realm must issue it; builds the database adapter for operator grants on its + trigger, audited runtime grant changes; pins the operator OpenAPI document under a + gate of its own; decides durable denial evidence if security monitoring requires it; + alerts on the operator counters; and owns the read-only dashboard decision, job + reconciliation and recurrence recovery that + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) leaves absent. - Secret management: Vault rotation cadence (90 days for provider keys, yearly for Hub HMAC shared secret + mTLS client certs), no secrets in repo, no secrets in env files committed. The Vault adapter itself lands in this phase — see @@ -460,7 +471,8 @@ not a request to add an unused module, adapter or port. `/healthz` proves liveness. Decide whether an unavailable IdP changes whole-instance readiness or authenticated-traffic admission, preserving the credential-free public contract. Keep IdP state, subject capacity and audit-store failure distinguishable. - Platform operations owns runbooks under `docs/runbooks/` for DNS/TLS/metadata failure, + Platform operations owns runbooks under `docs/runbooks/` (begun in Phase 03 for the + platform operator decisions) for DNS/TLS/metadata failure, signing-key rollout and withdrawal, authentication-volume spikes and capacity refusal. Each runbook names the signal, diagnostic access, safe recovery and an exercised recovery control before production activation. @@ -836,12 +848,15 @@ new erasure permission. and job alerts keep their own thresholds, and the three are asserted separately, with a runbook entry for each. - Each failure domain's recovery is asserted on its own path, because the two sides fail - independently and the job side is a third: a producer-side replay resets the row and - the next poll dispatches it, the consumer's guard absorbing the duplicate; a - subscriber-side replay resets one `(event, consumer)` pair, reaches that subscription - and no other, and a late success racing it is absorbed by `IInboxGuard`; and a - terminal job is recovered by requeue and runs once. Each case names the single effect - it expects, and each runs while a second pod holds the lease. + independently and the job side is a third: a producer-side reset + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), + `retry_exhausted` rows only) clears the row and the next poll dispatches it, the + consumer's guard absorbing the duplicate; a subscriber-side replay resets one + `(event, consumer)` pair, reaches that subscription and no other, and a late success + racing it is absorbed by `IInboxGuard`; and a terminal job has no operator requeue, + because ADR-0103 admits none until a provider can prove quiescence, so its recovery is + the domain's own, for example invitation reissue. Each case names the single effect it + expects, and each runs while a second pod holds the lease. - Each asynchronous-store purge writer satisfies its bounded decision and exact migration/grant contract, using a named principal admitted by the required audited gate. Existing Platform outbox DELETE is not inbox, delivery or job diff --git a/docs/standards/04-api-design.md b/docs/standards/04-api-design.md index 3c9908a3..ea16cc42 100644 --- a/docs/standards/04-api-design.md +++ b/docs/standards/04-api-design.md @@ -50,7 +50,9 @@ Examples: - `PATCH /api/v1/courses/{id}` - `POST /api/v1/courses/{id}/versions` -Platform-admin endpoints live under `/api/v1/platform/...` and require platform-admin scope. +Platform operator endpoints live under `/api/platform/v1/...`, outside the tenant +`/api/v1` contract and its OpenAPI document, and require a Platform-scope permission +([ADR-0101](../decisions/0101-platform-operator-authority.md)). **P02d-4 Accepted contract — 2026-10-03.** Steps 2–3 deliver all four GET/HEAD read pairs; Step 4 delivers the contract/SDK controls. Institution diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 83505520..ac6e127c 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -159,10 +159,13 @@ LearnStack runs **two Keycloak realms** per - `learnstack` — the tenant-facing realm. All tenant admins, instructors, and learners authenticate here. The realm includes the tenant id in token claims; the API re-validates against the resolved tenant context. -- `learnstack-hub` — the **operator realm**, used **only** by the Hub operator portal - (`hub.learnstack.dev`). Tenant-facing apps **never** accept `learnstack-hub` tokens; - the internal API (`/api/internal/*`) **only** accepts `learnstack-hub` tokens plus - the mTLS client certificate. +- `learnstack-hub` — the **operator realm**, used by the Hub operator portal + (`hub.learnstack.dev`) and by LearnStack's platform operator surface + (`/api/platform/v1/*`, [ADR-0101](../decisions/0101-platform-operator-authority.md)). + Tenant-facing apps and the tenant API **never** accept `learnstack-hub` tokens; the + internal API (`/api/internal/*`) **only** accepts `learnstack-hub` tokens plus the + mTLS client certificate; and the platform operator prefix accepts operator tokens + of its pinned issuer only, for its own audience. General rules: diff --git a/docs/standards/12-infrastructure.md b/docs/standards/12-infrastructure.md index 9649120f..d30550bf 100644 --- a/docs/standards/12-infrastructure.md +++ b/docs/standards/12-infrastructure.md @@ -362,7 +362,9 @@ Budgets are reviewed quarterly. Cost dashboards drive the next review. - RTO target: 4 hours for production restore. - RPO target: 15 minutes (WAL archiving cadence). -- Runbooks live in `docs/runbooks/` (Phase 11 deliverable). +- Runbooks live in `docs/runbooks/`. Phase 03 begins them with the platform operator + runbooks ([ADR-0101](../decisions/0101-platform-operator-authority.md) to + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md)); Phase 11 completes the set. - Annual full DR drill required. ## Forbidden diff --git a/docs/standards/13-documentation.md b/docs/standards/13-documentation.md index 457965c0..e90ab067 100644 --- a/docs/standards/13-documentation.md +++ b/docs/standards/13-documentation.md @@ -21,7 +21,7 @@ docs/ roadmap/ phase-NN-topic.md (with phase-NNa / phase-NNb splits for parallel tracks) phase-NN-delivery-log.md a phase's dated packet records (ADR-0069) standards/ NN-topic.md engineering rules - runbooks/ *.md operations procedures (Phase 11+) + runbooks/ *.md operations procedures (begun in Phase 03; Phase 11 completes) modules/ / per-module specs (one directory per module, created with its first spec) glossary.md terminology ``` diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index c99aad52..ad90126d 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -321,7 +321,9 @@ Rules: ([ADR-0044 § 5](../decisions/0044-audit-write-path.md); ADR-0016's `is_success boolean` is superseded, because a boolean cannot carry `denied`). `denied` is used when an authorisation check rejects the operation — these MUST be audited so we can detect - probing. `indeterminate` is the commit whose server-side outcome is unknown: the + probing. A Platform operator admission refusal is tenantless and outside that + population: it leaves a counter and a Warning log + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11). `indeterminate` is the commit whose server-side outcome is unknown: the standalone re-write carries the **same** `id` as the in-transaction attempt, and the pair is what a reviewer reads as one commit in doubt. `PostgresAuditStore` supplies `occurredAt` from `IClock` — the intent's declaration time in the transaction, a fresh @@ -329,7 +331,9 @@ Rules: composite primary key `(id, timestamp)`. This describes ordinary resource reconciliation; [trusted denial occurrences](#trusted-authorization-evidence) instead retain one fixed key, timestamp and draft. -- `reason` is required when the operator is a platform admin acting on a tenant they are not a member of. It is `EnterPlatformAdminScope(reason)`'s short operator-authored slug naming the operation — never caller-supplied text — and it is surfaced in the tenant admin's audit view. A refusal's cause is not a `reason`: it is the refusal's message key, in the `error_key` column. +- `reason` is required when the operator is a platform admin acting on a tenant they are not a member of. It is `EnterPlatformAdminScope(reason)`'s short operator-authored slug naming the operation — never caller-supplied text — and it is surfaced in the tenant admin's audit view when the row targets that tenant. + Rows under the platform sentinel are visible to no tenant + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 9, § 10). A refusal's cause is not a `reason`: it is the refusal's message key, in the `error_key` column. - `correlationId` matches the trace id in logs and the value in the Problem Details response for failures. - `changes` is always a JSON **array** of `{ path, before, after }`, never the polymorphic object-or-array shape ADR-0016 described. A reader that has to branch on the shape gets diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 911f0ad7..4f2e1e1a 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,16 +92,17 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.tenant.write`, `platform.feature_flag.admin`, `platform.audit.read` | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write` (the registered catalogue of [ADR-0101](../decisions/0101-platform-operator-authority.md); other `platform.*` names are unregistered) | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. An explicit eligible Tenant grant can independently authorize the declared -operation; same-key pairs never imply one another. Platform admission remains -P03-9 and requires its privileged authentication/audit contract (see -[18-audit-coverage.md](18-audit-coverage.md)). +operation; same-key pairs never imply one another. Platform admission is decided by +[ADR-0101](../decisions/0101-platform-operator-authority.md) (operator scheme, per-act +grants held by LearnStack, a separate non-assignable catalogue) and ships in P03-9 with +its audit contract (see [18-audit-coverage.md](18-audit-coverage.md)). Registered architecture obligation `Permission_Scope_Matches_Resource_Scope` requires permissions registered as From bfba12280f3e55a3709d9663361c188b9dd38963 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 11:53:22 +0300 Subject: [PATCH 04/28] feat(platform): add operator authority gate and killswitch writer P03-9 Step 1 under ADR-0101: a second bearer scheme confined to /api/platform, a per-act operator gate over LearnStack-held grants, a platform scope that takes an admission and exposes no connection, a witness-bound MUST result row, the killswitch toggle service and its route, the operator realm client with MFA step-up, and the runbooks. Closed architecture censuses are updated by exact type, not widened. Co-Authored-By: Claude Sonnet 5.5 --- .../OperationHttpClassification.cs | 6 +- .../PlatformOperatorAuthentication.cs | 230 +++++++++ .../PlatformOperatorSettings.cs | 86 ++++ .../PersistenceCompositionExtensions.cs | 7 +- .../PlatformOperatorCompositionExtensions.cs | 40 ++ .../Platform/PlatformOperatorEndpoints.cs | 112 +++++ backend/src/LearnStack.Api/Program.cs | 5 + .../Tenancy/HostClassificationMiddleware.cs | 3 + .../Versioning/ApiVersioningExtensions.cs | 24 + .../Versioning/VersionedRouteConvention.cs | 1 + .../appsettings.Development.json | 17 + .../PostgresAuditStore.cs | 53 ++ .../MultiTenancy/PlatformAdminScope.cs | 391 ++++++++------- ...onfigurationPlatformOperatorGrantSource.cs | 78 +++ .../PlatformOperator/PlatformOperatorGate.cs | 73 +++ .../PlatformOperatorGrantOptions.cs | 79 +++ .../PlatformOperatorMetrics.cs | 43 ++ .../Audit/IAuditStore.cs | 27 + .../Entitlements/IKillswitchToggle.cs | 40 ++ .../Entitlements/KillswitchKeys.cs | 10 +- .../Platform/IPlatformOperatorGate.cs | 96 ++++ .../Platform/PlatformAdmission.cs | 49 ++ .../Platform/PlatformOperation.cs | 56 +++ .../Platform/PlatformOperatorSubject.cs | 25 + .../Platform/PlatformOperatorWitness.cs | 76 +++ .../Platform/PlatformPermissions.cs | 36 ++ .../Tenancy/IPlatformAdminGate.cs | 72 --- .../Tenancy/IPlatformAdminScope.cs | 162 +++--- .../Audit/TenancyAuditCatalogSource.cs | 4 + .../PlatformProjections.cs | 12 +- .../KillswitchOverlay.cs | 14 +- .../KillswitchToggle.cs | 116 +++++ .../tests/Fixtures/TestPlatformAdmissions.cs | 38 ++ .../ApiConventionTests.cs | 2 +- .../AuditConventionTests.cs | 4 +- .../AuthenticatedHttpSurfaceTests.cs | 7 +- .../AuthenticationAuthorityTests.Shapes.cs | 8 + .../AuthenticationAuthorityTests.cs | 2 +- .../BackgroundJobManifestBoundaryTests.cs | 7 +- .../PlatformAdminScopeConventionTests.cs | 106 ++-- .../ConstructionOnlyApiFactory.cs | 9 + .../BackgroundJobAdmissionTests.Callbacks.cs | 3 - .../Database/BackgroundJobAdmissionTests.cs | 13 +- .../Database/PlatformAdminScopeTests.cs | 469 ++++++++++++++---- .../LearnStack.Tests.Integration.csproj | 1 + .../PlatformOperatorHttpTests.cs | 356 +++++++++++++ .../TenancyIdentity/KeycloakFixture.cs | 22 +- .../PlatformOperatorRealmTests.cs | 186 +++++++ .../TenantAuthenticationPipelineProof.cs | 3 +- .../Tenancy/HostClassificationScopeTests.cs | 2 +- .../MultiTenancy/PlatformAdminGateTests.cs | 295 +++++++---- .../LearnStack.Tests.Unit.csproj | 1 + docs/architecture/21-feature-flags.md | 19 +- docs/architecture/31-audit-subsystem.md | 14 +- docs/glossary.md | 3 +- docs/modules/tenancy/audit.md | 2 +- docs/modules/tenancy/permissions.md | 6 + docs/roadmap/phase-03-delivery-log.md | 111 ++++- docs/runbooks/README.md | 12 + docs/runbooks/killswitch.md | 63 +++ docs/runbooks/operator-access.md | 94 ++++ docs/standards/05-database.md | 17 +- docs/standards/19-permissions.md | 9 + .../21-architecture-tests-catalogue.md | 87 ++-- infra/keycloak/README.md | 17 +- infra/keycloak/realms/learnstack-hub.json | 149 ++++++ 66 files changed, 3484 insertions(+), 696 deletions(-) create mode 100644 backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs create mode 100644 backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs create mode 100644 backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs create mode 100644 backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/ConfigurationPlatformOperatorGrantSource.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGrantOptions.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs create mode 100644 backend/src/LearnStack.SharedKernel/Entitlements/IKillswitchToggle.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/IPlatformOperatorGate.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorSubject.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorWitness.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs delete mode 100644 backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs create mode 100644 backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs create mode 100644 backend/tests/Fixtures/TestPlatformAdmissions.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs create mode 100644 docs/runbooks/README.md create mode 100644 docs/runbooks/killswitch.md create mode 100644 docs/runbooks/operator-access.md diff --git a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs index bd10d1cb..36fc5873 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs @@ -39,9 +39,9 @@ internal sealed class OperationPolicyRequirement(OperationPolicy policy) : IAuth internal string Name => Prefix + Policy.Id; } -internal enum InfrastructureOperationKind { Health = 1, OpenApi = 2, Documentation = 3 } +internal enum InfrastructureOperationKind { Health = 1, OpenApi = 2, Documentation = 3, PlatformOperator = 4 } -/// Only the three actual infrastructure mapping owners can attach these fixed declarations. +/// Only the four actual infrastructure mapping owners can attach these fixed declarations. internal sealed class InfrastructureOperationMetadata { private InfrastructureOperationMetadata(InfrastructureOperationKind kind) => Kind = kind; @@ -49,6 +49,7 @@ internal sealed class InfrastructureOperationMetadata internal static InfrastructureOperationMetadata Health { get; } = new(InfrastructureOperationKind.Health); internal static InfrastructureOperationMetadata OpenApi { get; } = new(InfrastructureOperationKind.OpenApi); internal static InfrastructureOperationMetadata Documentation { get; } = new(InfrastructureOperationKind.Documentation); + internal static InfrastructureOperationMetadata PlatformOperator { get; } = new(InfrastructureOperationKind.PlatformOperator); } internal enum HttpOperationClassification { Unmatched = 0, Refused = 1, Application = 2, Infrastructure = 3 } @@ -70,6 +71,7 @@ internal HttpOperationClassification Classify(Endpoint? endpoint, out OperationP return ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.Health) || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.OpenApi) || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.Documentation) + || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.PlatformOperator) ? HttpOperationClassification.Infrastructure : HttpOperationClassification.Refused; } if (declarations.Count != 1 || endpoint.Metadata.GetMetadata() is not { } action diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs new file mode 100644 index 00000000..4c268582 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs @@ -0,0 +1,230 @@ +using System.Diagnostics; +using LearnStack.Api.Common; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Time; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Logging; +using Microsoft.IdentityModel.Tokens; + +namespace LearnStack.Api.Authentication; + +/// +/// The second bearer scheme, confined to the operator prefix (ADR-0101 § 2, ADR-0064 +/// Amendment 9). +/// +/// +/// +/// Not a default scheme. The tenant scheme stays the default and the only scheme on +/// /api/v1. This one authenticates only where an endpoint names it, and its +/// MessageReceived ignores any path outside /api/platform, so a tenant route +/// can never be authenticated by it. The tenant scheme in turn ignores the operator prefix: +/// it classifies by host and the prefix is unclassified. +/// +/// +/// Stock cryptographic validation, then a closed profile. Signature, exact issuer, +/// audience learnstack-platform, lifetime and algorithm come from the stock handler; +/// then requires an allow-listed +/// azp, a token lifetime of at most 15 minutes, an accepted acr and a recent +/// auth_time. Roles and every other claim carry no authority. +/// +/// +internal static class PlatformOperatorAuthentication +{ + internal const string Scheme = "PlatformOperator"; + + /// The named policy every operator endpoint requires. + /// + /// An explicit policy, not [Authorize(AuthenticationSchemes = ...)] alone: the host's + /// default and fallback policies carry only the declared-operation requirement and no + /// authenticated-user requirement, so a scheme-only attribute would authenticate the token + /// and then admit an anonymous caller. This policy requires an authenticated principal from + /// this scheme and nothing from the tenant scheme. + /// + internal const string PolicyName = "PlatformOperator"; + + internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( + this IServiceCollection services, PlatformOperatorSettings settings) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(settings); + IdentityModelEventSource.ShowPII = false; + IdentityModelEventSource.LogCompleteSecurityArtifact = false; + services.AddSingleton(settings); + services.TryAddSingleton(); + services.AddAuthentication().AddJwtBearer(Scheme, _ => { }); + services.AddAuthorization(options => options.AddPolicy( + PolicyName, policy => policy.AddAuthenticationSchemes(Scheme).RequireAuthenticatedUser())); + services.AddOptions(Scheme) + .Configure>((options, clock, logger) => + { + options.Authority = settings.Issuer; + options.MetadataAddress = settings.MetadataAddress; + options.RequireHttpsMetadata = new Uri(settings.Issuer).Scheme == Uri.UriSchemeHttps; + options.MapInboundClaims = false; + options.SaveToken = false; + options.IncludeErrorDetails = false; + options.AutomaticRefreshInterval = TimeSpan.FromMinutes(5); + options.RefreshInterval = TimeSpan.FromSeconds(30); + options.TokenValidationParameters = new TokenValidationParameters + { + RequireSignedTokens = true, + ValidateIssuerSigningKey = true, + ValidateIssuer = true, + ValidIssuer = settings.Issuer, + ValidateAudience = true, + RequireAudience = true, + ValidAudience = PlatformOperatorSettings.Audience, + RequireExpirationTime = true, + ValidateLifetime = true, + ClockSkew = PlatformOperatorSettings.ClockSkew, + ValidAlgorithms = [SecurityAlgorithms.RsaSha256], + ValidTypes = ["JWT"], + LogValidationExceptions = false, + LogTokenId = false, + IncludeTokenOnFailedValidation = false, + }; + options.Events = new PlatformOperatorEvents(settings, clock, logger); + }); + return services; + } +} + +/// The validated operator witness, attached to the request by the scheme. +internal sealed class PlatformOperatorFeature(PlatformOperatorWitness witness) +{ + internal PlatformOperatorWitness Witness { get; } = witness; +} + +/// The one minter the operator authentication boundary owns (ADR-0101 § 7). +internal sealed class PlatformOperatorWitnessMinter : PlatformOperatorWitness.Minter +{ + internal static PlatformOperatorWitness Create( + string issuer, string subjectDigest, string acr, DateTimeOffset authenticatedAt, string? correlationId) => + Mint(issuer, subjectDigest, acr, authenticatedAt, PlatformOperatorSettings.Executor, correlationId); +} + +/// Scopes the scheme to its prefix and applies the closed token profile. +internal sealed class PlatformOperatorEvents( + PlatformOperatorSettings settings, IClock clock, ILogger logger) : JwtBearerEvents +{ + public override Task MessageReceived(MessageReceivedContext context) + { + if (!context.Request.Path.StartsWithSegments(PlatformOperatorSettings.RoutePrefix, StringComparison.Ordinal)) + { + context.NoResult(); + return Task.CompletedTask; + } + + var values = context.Request.Headers.Authorization; + if (values.Count != 1 + || values[0] is not { } header + || !header.StartsWith("Bearer ", StringComparison.Ordinal) + || header.Length <= "Bearer ".Length) + { + context.NoResult(); + return Task.CompletedTask; + } + + context.Token = header["Bearer ".Length..]; + return Task.CompletedTask; + } + + public override Task TokenValidated(TokenValidatedContext context) + { + if (context.SecurityToken is not JsonWebToken token + || !PlatformOperatorTokenProfile.TryRead(token, settings, clock.UtcNow, Activity.Current?.Id, out var witness)) + { + context.Fail("Operator credential refused."); + return Task.CompletedTask; + } + + context.HttpContext.Features.Set(new PlatformOperatorFeature(witness!)); + return Task.CompletedTask; + } + + public override Task Challenge(JwtBearerChallengeContext context) + { + // One answer for a missing, malformed, expired or wrongly profiled credential: no + // detail a probing caller could use, a counter and a log an operator can alert on. + var cause = context.AuthenticateFailure is null ? "token_missing" : "token_invalid"; + PlatformOperatorMetrics.Unauthenticated(cause); + LogUnauthenticated(logger, cause, null); + context.HandleResponse(); + context.Response.Headers.WWWAuthenticate = "Bearer"; + return Respond(context.HttpContext, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); + } + + public override Task Forbidden(ForbiddenContext context) => + Respond(context.HttpContext, StatusCodes.Status403Forbidden, "lockey_forbidden"); + + internal static Task Respond(HttpContext http, int status, string key) + { + var error = new Error(new LocalizedMessage(key)); + http.Response.StatusCode = status; + return http.Response.WriteAsJsonAsync( + ProblemDetailsFactory.For(error, http), + options: null, + contentType: ProblemDetailsMediaType.Value, + cancellationToken: http.RequestAborted); + } + + private static readonly Action LogUnauthenticated = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(7103, nameof(LogUnauthenticated)), + "Platform operator credential refused: {Cause}."); +} + +/// +/// The closed profile a cryptographically valid operator token must also meet (ADR-0101 § 2, § 3). +/// +/// +/// A pure function of the validated token, the settings and the clock, so the scheme, the real-realm +/// proof and the offline rebind tool judge one definition. It admits an allow-listed azp, an +/// accepted acr, a lifetime of at most 15 minutes, and an auth_time that is neither in +/// the future nor older than the configured age. Nothing else in the token carries authority. +/// +internal static class PlatformOperatorTokenProfile +{ + internal static bool TryRead( + JsonWebToken token, + PlatformOperatorSettings settings, + DateTimeOffset now, + string? correlationId, + out PlatformOperatorWitness? witness) + { + witness = null; + if (string.IsNullOrWhiteSpace(token.Subject) + || !token.TryGetPayloadValue("azp", out var azp) || !settings.AuthorizedParties.Contains(azp) + || !token.TryGetPayloadValue("acr", out var acr) || !settings.AcceptedAcr.Contains(acr) + || !token.TryGetPayloadValue("iat", out var iat) + || !token.TryGetPayloadValue("auth_time", out var authTime) + || token.ValidTo == DateTime.MinValue) + { + return false; + } + + var issuedAt = DateTimeOffset.FromUnixTimeSeconds(iat); + var authenticatedAt = DateTimeOffset.FromUnixTimeSeconds(authTime); + var lifetime = new DateTimeOffset(token.ValidTo, TimeSpan.Zero) - issuedAt; + if (lifetime <= TimeSpan.Zero || lifetime > PlatformOperatorSettings.MaxTokenLifetime + || authenticatedAt > now + PlatformOperatorSettings.ClockSkew + || now - authenticatedAt > settings.MaxAuthenticationAge) + { + return false; + } + + witness = PlatformOperatorWitnessMinter.Create( + settings.Issuer, + PlatformOperatorSubject.Digest(settings.Issuer, token.Subject), + acr, + authenticatedAt, + correlationId); + return true; + } +} diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs new file mode 100644 index 00000000..b9981058 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs @@ -0,0 +1,86 @@ +using LearnStack.SharedKernel.Hosting; + +namespace LearnStack.Api.Authentication; + +/// +/// The validated, immutable operator-scheme configuration; absent when the issuer is not +/// configured, in which case no operator scheme and no operator route exists (ADR-0101 § 2, § 4). +/// +internal sealed class PlatformOperatorSettings +{ + internal const string SectionName = "PlatformOperator"; + internal const string Audience = "learnstack-platform"; + internal const string RoutePrefix = "/api/platform"; + internal const string Executor = "operator.api"; + + internal static TimeSpan ClockSkew { get; } = TimeSpan.FromSeconds(30); + + /// The longest exp - iat a token may carry. + internal static TimeSpan MaxTokenLifetime { get; } = TimeSpan.FromMinutes(15); + + private PlatformOperatorSettings( + string issuer, HashSet acceptedAcr, HashSet authorizedParties, TimeSpan maxAuthenticationAge) + { + Issuer = issuer; + MetadataAddress = issuer + "/.well-known/openid-configuration"; + AcceptedAcr = acceptedAcr; + AuthorizedParties = authorizedParties; + MaxAuthenticationAge = maxAuthenticationAge; + } + + internal string Issuer { get; } + internal string MetadataAddress { get; } + internal IReadOnlySet AcceptedAcr { get; } + internal IReadOnlySet AuthorizedParties { get; } + internal TimeSpan MaxAuthenticationAge { get; } + + /// Returns null when no issuer is configured; throws when the configuration is unsafe. + internal static PlatformOperatorSettings? FromConfiguration(IConfiguration configuration, DeploymentMode deploymentMode) + { + ArgumentNullException.ThrowIfNull(configuration); + var section = configuration.GetSection(SectionName); + var issuer = section["Issuer"]; + if (string.IsNullOrWhiteSpace(issuer)) + { + return null; + } + + if (!Uri.TryCreate(issuer, UriKind.Absolute, out var address) + || !address.IsWellFormedOriginalString() + || !string.Equals(address.AbsoluteUri, issuer, StringComparison.Ordinal) + || address.UserInfo.Length != 0 + || address.Query.Length != 0 + || address.Fragment.Length != 0 + || !(address.Scheme == Uri.UriSchemeHttps + || (address.Scheme == Uri.UriSchemeHttp && address.IsLoopback + && deploymentMode == DeploymentMode.Development))) + { + throw new InvalidOperationException( + "PlatformOperator:Issuer must be a canonical absolute HTTPS URL without userinfo, query or " + + "fragment. Loopback HTTP is allowed only in Development."); + } + + var acr = ReadSet(section.GetSection("AcceptedAcr")); + var parties = ReadSet(section.GetSection("AuthorizedParties")); + if (acr.Count == 0 || parties.Count == 0) + { + throw new InvalidOperationException( + "PlatformOperator needs at least one AcceptedAcr and one AuthorizedParties value when " + + "an Issuer is configured; assurance and client are never inferred."); + } + + var ageText = section["MaxAuthenticationAge"]; + var age = TimeSpan.FromMinutes(15); + if (ageText is not null && (!TimeSpan.TryParse(ageText, System.Globalization.CultureInfo.InvariantCulture, out age) + || age <= TimeSpan.Zero || age > TimeSpan.FromHours(1))) + { + throw new InvalidOperationException("PlatformOperator:MaxAuthenticationAge must be between 0 and 1 hour."); + } + + return new PlatformOperatorSettings(issuer, acr, parties, age); + } + + private static HashSet ReadSet(IConfigurationSection section) => + section.GetChildren().Select(child => child.Value).Where(value => !string.IsNullOrWhiteSpace(value)) + .Select(value => value!).ToHashSet(StringComparer.Ordinal); +} diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index bb1eb8a9..4983bc60 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -188,9 +188,9 @@ public static IServiceCollection AddLearnStackPersistence( services.AddLearnStackBackgroundJobContracts(); services.AddInvitationEmailDelivery(configuration); - // The gate first, so a reader sees that entry is refused before a connection is - // opened rather than after. Both are stateless singletons. - services.TryAddSingleton(); + // The scope is a stateless singleton. Admission is not its concern any more: the + // caller holds a PlatformAdmission from IPlatformOperatorGate, registered with the + // operator authority (ADR-0101), so a refused operator never reaches a connection. services.TryAddSingleton(); // Scoped: one connection per request, owned by this, shared by every @@ -301,6 +301,7 @@ public static IServiceCollection AddLearnStackPersistence( // and shares the one entry — and the load runs on its own connection, because the // cache flight that runs it outlives the caller that started it. services.TryAddScoped(); + services.TryAddScoped(); // The entitlement socket. A SINGLETON and registered in EVERY deployment mode, // not Development only: ADR-0035 names NullEntitlementProvider the working default diff --git a/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs new file mode 100644 index 00000000..ad7b46f4 --- /dev/null +++ b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs @@ -0,0 +1,40 @@ +using LearnStack.Api.Authentication; +using LearnStack.Api.Versioning; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; + +namespace LearnStack.Api.Composition; + +/// Registers the platform operator authority: gate, grants, scheme (ADR-0101). +internal static class PlatformOperatorCompositionExtensions +{ + internal static IServiceCollection AddLearnStackPlatformOperatorAuthority( + this IServiceCollection services, IConfiguration configuration, DeploymentMode deploymentMode) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + + // The gate and the grants are always registered: with no grant, or no issuer, every + // act is refused, which is the closed default. Only the scheme and the routes depend + // on the issuer being configured. + services.AddOptions() + .Bind(configuration.GetSection(PlatformOperatorGrantOptions.SectionName)) + .ValidateOnStart(); + services.AddSingleton>( + new PlatformOperatorGrantOptionsValidator(deploymentMode)); + services.TryAddSingleton(); + services.TryAddSingleton(); + + var settings = PlatformOperatorSettings.FromConfiguration(configuration, deploymentMode); + if (settings is not null) + { + services.AddLearnStackPlatformOperatorAuthentication(settings); + services.AddLearnStackPlatformOperatorOpenApiDocument(); + } + + return services; + } +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs new file mode 100644 index 00000000..e8f5f657 --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -0,0 +1,112 @@ +using LearnStack.Api.Authentication; +using LearnStack.Api.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Api.Platform; + +/// The body of a killswitch toggle. +/// The state to set; required. +/// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. +internal sealed record KillswitchToggleRequest(bool? Enabled, string? Ticket); + +/// What a toggle changed, with the correlation id the operator records. +internal sealed record KillswitchToggleResponse(string Key, bool Before, bool After, string? CorrelationId); + +/// +/// The platform operator surface: minimal endpoints under /api/platform/v1, present only +/// when an operator issuer is configured (ADR-0101 § 4). +/// +/// +/// +/// Absence is the default. With no issuer there is no operator scheme and nothing here +/// is mapped, so the prefix answers 404 like any unknown route. +/// +/// +/// Admission before work. Every handler asks before +/// it touches a connection. A malformed ticket is a 400; a missing permission or an unknown +/// operation is a 403; and neither opens a privileged connection or writes a row, only a +/// counter and a log (ADR-0101 § 11). +/// +/// +internal static class PlatformOperatorEndpoints +{ + internal const string Prefix = "/api/platform/v1"; + + internal static WebApplication MapLearnStackPlatformOperator(this WebApplication app) + { + ArgumentNullException.ThrowIfNull(app); + if (app.Services.GetService() is null) + { + return app; + } + + var group = app.MapGroup(Prefix) + .RequireAuthorization(PlatformOperatorAuthentication.PolicyName) + .WithMetadata(InfrastructureOperationMetadata.PlatformOperator); + + group.MapPut("/killswitches/{key}", ToggleKillswitchAsync) + .WithName("PlatformKillswitchToggle") + .WithSummary("Set a declared killswitch for every tenant.") + .Produces(StatusCodes.Status200OK, "application/json") + .ProducesProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status403Forbidden) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable); + return app; + } + + private static async Task ToggleKillswitchAsync( + string key, + KillswitchToggleRequest? body, + HttpContext http, + IPlatformOperatorGate gate, + IKillswitchToggle toggle, + CancellationToken cancellationToken) + { + var witness = http.Features.Get()?.Witness; + if (witness is null) + { + return Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); + } + + if (body?.Enabled is not { } enabled) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body.Ticket, cancellationToken); + if (!admission.IsAdmitted) + { + return admission.Refusal switch + { + PlatformRefusal.InvalidTicket => Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"), + PlatformRefusal.InvalidWitness => Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"), + _ => Problem(http, StatusCodes.Status403Forbidden, "lockey_forbidden"), + }; + } + + try + { + var result = await toggle.ToggleAsync(admission.Admission!, new KillswitchKey(key), enabled, cancellationToken); + return result.Outcome == KillswitchToggleOutcome.Applied + ? Results.Ok(new KillswitchToggleResponse(key, result.Before, result.After, admission.Admission!.Operator.CorrelationId)) + : Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"); + } + catch (AuditWriteFailedException) + { + return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); + } + } + + private static IResult Problem(HttpContext http, int status, string key) => + Results.Json( + ProblemDetailsFactory.For(new Error(new LocalizedMessage(key)), http), + options: null, + contentType: ProblemDetailsMediaType.Value, + statusCode: status); +} diff --git a/backend/src/LearnStack.Api/Program.cs b/backend/src/LearnStack.Api/Program.cs index a4786957..87ad7a23 100644 --- a/backend/src/LearnStack.Api/Program.cs +++ b/backend/src/LearnStack.Api/Program.cs @@ -1,6 +1,7 @@ using LearnStack.Api.Authentication; using LearnStack.Api.Common; using LearnStack.Api.Composition; +using LearnStack.Api.Platform; using LearnStack.Api.PublicReads; using LearnStack.Api.Tenancy; using LearnStack.Api.Versioning; @@ -58,6 +59,9 @@ // the explicit middleware order below owns both insertions and all guards. builder.Services.AddLearnStackTenantAuthentication( TenantAuthenticationOptions.FromConfiguration(builder.Configuration, deploymentMode)); +// ADR-0101: the operator gate, grants and, only when an issuer is configured, the second scheme +// confined to /api/platform. The tenant scheme above stays the default and the only scheme on /api/v1. +builder.Services.AddLearnStackPlatformOperatorAuthority(builder.Configuration, deploymentMode); builder.Services.AddLearnStackTenantSubjectAdmission(); builder.Services.AddLearnStackNativeSessionSource(builder.Configuration); builder.Services.AddLearnStackIdentitySelfEntry(); @@ -159,6 +163,7 @@ .WithMetadata(InfrastructureOperationMetadata.Health); app.MapControllers(); +app.MapLearnStackPlatformOperator(); app.Run(); diff --git a/backend/src/LearnStack.Api/Tenancy/HostClassificationMiddleware.cs b/backend/src/LearnStack.Api/Tenancy/HostClassificationMiddleware.cs index 805b25e3..b318856a 100644 --- a/backend/src/LearnStack.Api/Tenancy/HostClassificationMiddleware.cs +++ b/backend/src/LearnStack.Api/Tenancy/HostClassificationMiddleware.cs @@ -61,6 +61,9 @@ public sealed class HostClassificationMiddleware "/openapi", "/admin/hangfire", "/api/internal", + // The platform operator surface (ADR-0101 § 4): authenticated by its own scheme, and its + // target tenant is data of the act, never a resolution input. + "/api/platform", ]; /// Unknown hosts, unlabelled — the host itself is never a dimension. diff --git a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs index 8e76e7b0..e64b2aa6 100644 --- a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs +++ b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs @@ -152,6 +152,30 @@ public static IServiceCollection AddLearnStackOpenApiDocument( return services; } + /// + /// Registers the operator contract as its own document, platform-v1, outside the + /// pinned tenant document and the tenant SDK (ADR-0101 § 4). + /// + /// + /// Called only when an operator issuer is configured, so a deployment without one serves + /// no operator contract. The document includes only api/platform/v1 paths, and the + /// tenant document's filter includes only api/v1, so neither can carry the other's + /// operations. + /// + internal static IServiceCollection AddLearnStackPlatformOperatorOpenApiDocument(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + const string documentName = "platform-v1"; + RegistryFor(services).Add(documentName); + services.AddOpenApi(documentName, options => + { + options.ShouldInclude = api => + api.RelativePath?.StartsWith("api/platform/v1/", StringComparison.OrdinalIgnoreCase) == true; + options.AddSchemaTransformer(new StronglyTypedIdSchemaTransformer()); + }); + return services; + } + private static OpenApiDocumentRegistry RegistryFor(IServiceCollection services) { if (services.FirstOrDefault(d => d.ServiceType == typeof(OpenApiDocumentRegistry)) diff --git a/backend/src/LearnStack.Api/Versioning/VersionedRouteConvention.cs b/backend/src/LearnStack.Api/Versioning/VersionedRouteConvention.cs index bdaace1c..88e92a3d 100644 --- a/backend/src/LearnStack.Api/Versioning/VersionedRouteConvention.cs +++ b/backend/src/LearnStack.Api/Versioning/VersionedRouteConvention.cs @@ -64,6 +64,7 @@ public VersionedRouteConvention(IReadOnlyList? liveMajors = null) => public static readonly IReadOnlyList UnversionedRoutePrefixes = [ "api/internal", + "api/platform", ]; public void Apply(ApplicationModel application) diff --git a/backend/src/LearnStack.Api/appsettings.Development.json b/backend/src/LearnStack.Api/appsettings.Development.json index b57a182b..439d6d5b 100644 --- a/backend/src/LearnStack.Api/appsettings.Development.json +++ b/backend/src/LearnStack.Api/appsettings.Development.json @@ -14,6 +14,23 @@ "Issuer": "http://localhost:8080/realms/learnstack" } }, + "PlatformOperator": { + "Issuer": "http://localhost:8080/realms/learnstack-hub", + "AcceptedAcr": [ + "mfa" + ], + "AuthorizedParties": [ + "learnstack-operator" + ], + "Grants": [ + { + "Subject": "5a3c8f0e-2b1d-4c6a-9e47-0d1f6a2b7c93", + "Permissions": [ + "platform.killswitch.write" + ] + } + ] + }, "Tenancy": { "PlatformHosts": [ "localhost" diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index 88c676c7..da1dcc0c 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -11,6 +11,7 @@ using Microsoft.Extensions.Logging; using Npgsql; using NpgsqlTypes; +using LearnStack.SharedKernel.Platform; namespace LearnStack.Infrastructure.Audit; @@ -416,6 +417,58 @@ public async Task WritePlatformScopeAsync( } } + /// + public async Task WritePlatformOperatorResultAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(admission); + RefuseGlobalCapture(); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + + // The admission binds the row: the operation, the closed reason and the operator + // must be the admitted ones, the actor column stays NULL because an operator is not a + // user, and only a success is written here. A caller cannot present a different act. + if (!StronglyTypedId.IsAssigned(entry.TenantId) + || entry.ModuleName == "identity" + || !PlatformOperations.IsRegistered(admission.Operation) + || !string.Equals(entry.Operation, admission.Operation.AuditSlug, StringComparison.Ordinal) + || !string.Equals(entry.Reason, admission.Operation.ReasonSlug, StringComparison.Ordinal) + || entry.ActorUserId is not null + || entry.Outcome != AuditOutcome.Success + || entry.OperationClass != OperationClass.Must + || entry.Metadata is null + || !entry.Metadata.Contains(admission.Operator.SubjectDigest, StringComparison.Ordinal)) + { + throw new ArgumentException( + "The platform operator result row does not match its admission.", nameof(entry)); + } + + try + { + await using var command = connection.CreateCommand(); + command.CommandText = InsertSql; + command.Transaction = transaction; + + Bind(command.Parameters, entry); + + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbException failure) + { + throw new AuditWriteFailedException( + "The platform operator result row could not be written, so the act must not " + + "commit.", + failure); + } + } + /// public async Task WriteEventTerminalAsync( AuditEntryDraft entry, diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index d03e327a..fd45456b 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -1,10 +1,12 @@ using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Infrastructure.Persistence; using System.Data.Common; using System.Globalization; using System.Runtime.CompilerServices; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; using LearnStack.SharedKernel.Time; using Microsoft.Extensions.DependencyInjection; @@ -14,7 +16,7 @@ namespace LearnStack.Infrastructure.MultiTenancy; /// -/// Opens a learnstack_platform connection, on its own, for one bounded operation. +/// Opens a learnstack_platform connection, on its own, for one admitted operator act. /// /// /// @@ -34,8 +36,13 @@ namespace LearnStack.Infrastructure.MultiTenancy; /// No set_config('app.tenant_id', …), and no SET TRANSACTION READ ONLY. /// The first because there is no policy to announce to — the role bypasses them — which /// is also why this is not a ninth out-of-band setter. The second because nothing calls -/// this path read-only: both named consumers, GDPR redaction and the retention purge, -/// write. +/// this path read-only. +/// +/// +/// Admission before entry. The caller holds a that +/// minted after evaluating a grant, so a refused operator +/// never reaches a connection (ADR-0036, ADR-0101 § 7). Entry no longer asks a gate; the +/// admission is the proof. An act that needs only the app or outbox role never enters here. /// /// /// Entry is audited, and refusing to record it refuses the entry. Every @@ -46,13 +53,15 @@ namespace LearnStack.Infrastructure.MultiTenancy; /// (ADR-0044 § 10). /// The scope is a singleton and IAuditStore is scoped, which is why /// the store is resolved from a fresh scope per entry -/// rather than injected: this path is entered from background work as readily as from a -/// request, so there is not always an ambient scope to capture — and capturing one on a -/// singleton would hand every later entry the first caller's. +/// rather than injected. +/// +/// +/// The handle is a facade. It exposes no connection or transaction, because a +/// reference captured before the commit would run in autocommit on a connection that sees +/// every tenant. Completion and abandonment close the connection. /// /// public sealed class PlatformAdminScope( - IPlatformAdminGate gate, [FromKeyedServices(PlatformAdminScope.PlatformDataSourceKey)] PrivilegedDataSource dataSource, IAuditCatalog catalog, IServiceScopeFactory scopeFactory, @@ -78,8 +87,6 @@ public sealed class PlatformAdminScope( /// public const string EnterOperation = "platform.admin_scope.enter"; - private readonly IPlatformAdminGate _gate = gate ?? throw new ArgumentNullException(nameof(gate)); - private readonly PrivilegedDataSource _dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); @@ -100,43 +107,34 @@ public sealed class PlatformAdminScope( /// /// The [Caller*] attributes are restated here and not left to the interface. /// C# fills them in from the static type of the receiver, so a caller holding - /// the concrete — every test that constructs it - /// directly, and anything resolving it by implementation type — would otherwise get - /// the bare defaults and log <unknown> at <unknown>:0. - /// Losing the provenance silently is exactly what this record exists to prevent. + /// the concrete would otherwise get the bare defaults + /// and log <unknown> at <unknown>:0. /// public async Task EnterAsync( - string reason, + PlatformAdmission admission, CancellationToken cancellationToken = default, [CallerMemberName] string? callerMember = null, [CallerFilePath] string? callerFile = null, [CallerLineNumber] int callerLine = 0) { - ArgumentException.ThrowIfNullOrWhiteSpace(reason); - BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); - - // 1. The gate, before anything opens. ADR-0036 asks for the permission to be - // "checked before the scope opens", and a check after the connection exists - // would already have spent a BYPASSRLS connection on a refused caller. - if (!await _gate.IsPermittedAsync(reason, cancellationToken)) + ArgumentNullException.ThrowIfNull(admission); + if (!PlatformOperations.IsRegistered(admission.Operation) || !admission.Operation.NeedsPlatformRole) { - throw new PlatformAdminScopeDeniedException(reason); + throw new ArgumentException( + "The admission is for an operation that does not use the platform role.", nameof(admission)); } - // 2. The catalogue's own declaration, before the connection. It is what fixes the - // tier and the operation type, so the row and `docs/modules/tenancy/audit.md` - // cannot say different things — and an absent declaration is refused here - // rather than papered over with a hard-coded MUST, because a deployment whose - // catalogue lost this slug must not enter a cross-tenant scope unrecorded. - if (!_catalog.TryGetOffPath(EnterOperation, out var declared)) - { - throw new AuditWriteFailedException( - $"'{EnterOperation}' is not in the audit catalogue, so entry into a " - + "cross-tenant scope cannot be recorded and must not happen. It is " - + "declared off-path by the Tenancy source (ADR-0044 § 10)."); - } + BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); - // 3. The credential. Opening through the guarded facade here is where an absent + // 1. The catalogue's own declarations, before the connection. They fix the tier and + // the operation type, so the rows and `docs/modules/tenancy/audit.md` cannot say + // different things, and an absent declaration is refused here rather than papered + // over with a hard-coded MUST: a deployment whose catalogue lost either slug must + // not enter a cross-tenant scope unrecorded. + var declaredEntry = Declared(EnterOperation); + var declaredResult = Declared(admission.Operation.AuditSlug); + + // 2. The credential. Opening through the guarded facade here is where an absent // ConnectionStrings:PlatformAdmin surfaces — on entry, at the first call, with // a message naming the key rather than a container error naming a type. var connection = await _dataSource.OpenConnectionAsync(cancellationToken); @@ -144,54 +142,47 @@ public async Task EnterAsync( try { - // 4. The row, BEFORE the privileged work can begin and in a transaction of its + // 3. The row, BEFORE the privileged work can begin and in a transaction of its // OWN that commits first — so an operation that later fails, throws, or is - // simply abandoned is still on the record, which is the sentence ADR-0044 - // § 10 writes. It rode the business transaction until the review of this - // packet: a caller that read across every tenant on the handle and then threw - // took the only record of that read down with its rollback. Reading one's own - // transaction back is not durability. - // - // learnstack_app cannot write under the platform sentinel at all, which is - // why the row cannot ride the request's connection (ADR-0044 § 10). A failure - // here throws out of EnterAsync and the catch below disposes the connection: - // an unrecordable entry is a refused entry, and no business transaction has - // been begun for it. - var entry = Compose(reason, declared, callerMember, callerFile, callerLine); + // simply abandoned is still on the record (ADR-0044 § 10). Reading one's own + // transaction back is not durability. learnstack_app cannot write under the + // platform sentinel at all, which is why the row cannot ride the request's + // connection. A failure here throws out of EnterAsync and the catch below + // disposes the connection: an unrecordable entry is a refused entry. + var entry = ComposeEntry(admission, declaredEntry, callerMember, callerFile, callerLine); await RecordAsync(entry, connection, cancellationToken); - // 5. Only now the transaction the caller works in. A row whose entry then failed + // 4. Only now the transaction the caller works in. A row whose entry then failed // to begin one records a permitted, recorded entry that handed nothing out — - // the rarer and the honest side of the trade: the other side is a handed-out - // BYPASSRLS connection with no durable record behind it. + // the honest side of the trade: the other side is a handed-out BYPASSRLS + // connection with no durable record behind it. transaction = await connection.BeginTransactionAsync(cancellationToken); - // 6. And the log line as well, which the row does not replace operationally. - // The row is the durable record a compliance reviewer reads afterwards; - // this is the line an operator alerting at Warning sees while it is - // happening. It carries the row's id, so the two are one another's index. + // 5. And the log line as well, which the row does not replace operationally. LogEntered( _logger, - reason, + admission.Operation.ReasonSlug, callerMember ?? "", ShortPath(callerFile), callerLine, entry.Id.Value, null); - return new Handle(connection, transaction, _logger); + var current = transaction; + return new Handle( + connection, + current, + (result, token) => WriteResultAsync(admission, declaredResult, result, connection, current, token), + _logger); } catch { - // The business transaction exists here only if something after its BEGIN threw - // — the log line, in practice never — and its disposal is NOT independently - // observable, which is better said than implied: disposing the connection rolls - // back and clears whatever transaction is open on it. What it buys is not - // depending on that, because the rollback-on-close is Npgsql's own behaviour - // rather than anything DbTransaction promises. The connection disposal below is - // the one the refused-entry case kills, and it is in the same catch because an - // entry that threw must not keep the one connection that sees every tenant. + // The work transaction exists here only if something after its BEGIN threw, and + // its disposal is not independently observable: disposing the connection rolls + // back whatever is open on it. The connection disposal below is the one the + // refused-entry case kills, and it is in the same catch because an entry that + // threw must not keep the one connection that sees every tenant. if (transaction is not null) { await transaction.DisposeAsync(); @@ -202,14 +193,21 @@ public async Task EnterAsync( } } + private AuditCatalogEntry Declared(string slug) => + _catalog.TryGetOffPath(slug, out var declared) + ? declared + : throw new AuditWriteFailedException( + $"'{slug}' is not in the audit catalogue, so a cross-tenant act cannot be recorded " + + "and must not happen. It is declared off-path by the Tenancy source (ADR-0044 § 10)."); + /// /// Writes the entry row on the scope's connection, in a transaction of its own, and /// commits it. /// /// /// Disposing the recording transaction uncommitted rolls it back, so a write that fails - /// leaves nothing behind — and nothing has been handed out, because the business - /// transaction is begun only after this returns. + /// leaves nothing behind — and nothing has been handed out, because the work transaction + /// is begun only after this returns. /// private async Task RecordAsync( AuditEntryDraft entry, NpgsqlConnection connection, CancellationToken cancellationToken) @@ -227,28 +225,80 @@ await services.ServiceProvider } /// - /// The row one entry writes: the sentinel tenant, the catalogue's tier, and the - /// caller's provenance. + /// Writes the act's MUST result row on the work transaction, through the witness-bound + /// method (ADR-0101 § 10). + /// + private async Task WriteResultAsync( + PlatformAdmission admission, + AuditCatalogEntry declared, + PlatformResult result, + NpgsqlConnection connection, + NpgsqlTransaction transaction, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(result); + if (!StronglyTypedId.IsAssigned(result.TenantId)) + { + throw new ArgumentException("A result row needs an assigned tenant.", nameof(result)); + } + + // The ticket stays out of a row a tenant can read: it appears only under the sentinel. + var isSentinel = result.TenantId == TenantId.PlatformSentinel; + var draft = new AuditEntryDraft + { + Id = AuditEntryId.From(_guidFactory.NewUuidV7()), + TenantId = result.TenantId, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = declared.ModuleName, + Operation = declared.Operation, + OperationType = declared.OperationType, + OperationClass = declared.OperationClass, + EntityType = result.EntityType ?? declared.EntityType?.Name, + EntityId = result.EntityId, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = result.BeforeState, + AfterState = result.AfterState, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = _clock.UtcNow, + Metadata = OperatorMetadata(admission, includeTicket: isSentinel, provenance: null), + }; + + await using var services = _scopeFactory.CreateAsyncScope(); + await services.ServiceProvider + .GetRequiredService() + .WritePlatformOperatorResultAsync(draft, admission, connection, transaction, cancellationToken); + PlatformOperatorMetrics.Result(admission.Operation); + } + + /// + /// The row one entry writes: the sentinel tenant, the catalogue's tier, the operator and + /// the caller's provenance. /// /// /// - /// The only class of row that carries . - /// It is a platform-scope operation with no resolvable tenant, and it is written - /// standalone on the scope's own platform-role connection — which is the one place the - /// sentinel is legal, every other announcement site refusing it (ADR-0044 § 1, § 10). + /// The platform-scope class of ADR-0044 § 1. It is a platform-scope operation + /// with no resolvable tenant, written standalone on the scope's own platform-role + /// connection — the one place the sentinel is legal, every other announcement site + /// refusing it. /// /// - /// No actor and no correlation id. Tenant authentication is live, but this - /// scope accepts no operator identity and its platform-permission gate denies all - /// callers until Phase 03. Compiler-supplied provenance lands in metadata - /// rather than being flattened into reason: the reason is an operator-authored - /// slug that a query groups by, and appending a file and a line to it would make every - /// group of one. The correlation id is scoped state, and this scope is entered from - /// background work as readily as from a request. + /// No actor user id, and the operator in metadata. An operator is not a + /// users row (ADR-0101 § 9), so the actor column stays NULL and + /// metadata.operator carries the issuer, the subject digest, the kind, the + /// accepted acr and the executor. Compiler-supplied provenance lands in + /// metadata rather than in reason: the reason is a closed slug that a + /// query groups by. /// /// - private AuditEntryDraft Compose( - string reason, + private AuditEntryDraft ComposeEntry( + PlatformAdmission admission, AuditCatalogEntry declared, string? callerMember, string? callerFile, @@ -268,34 +318,40 @@ private AuditEntryDraft Compose( EntityId = null, Outcome = AuditOutcome.Success, ErrorKey = null, - Reason = reason, + Reason = admission.Operation.ReasonSlug, BeforeState = null, AfterState = null, Changes = null, - CorrelationId = null, + CorrelationId = admission.Operator.CorrelationId, IpAddress = null, UserAgent = null, Timestamp = _clock.UtcNow, - Metadata = Provenance(callerMember, callerFile, callerLine), + Metadata = OperatorMetadata(admission, includeTicket: true, Provenance(callerMember, callerFile, callerLine)), }; - /// The calling site, as the row's metadata document. + private static string OperatorMetadata(PlatformAdmission admission, bool includeTicket, string? provenance) + { + var op = admission.Operator; + var json = "{" + + (provenance is null ? string.Empty : "\"caller\":" + provenance + ",") + + "\"operator\":{" + + "\"issuer\":" + AuditJson.Quote(op.Issuer) + + ",\"subjectDigest\":" + AuditJson.Quote(op.SubjectDigest) + + ",\"kind\":\"human\"" + + ",\"acr\":" + AuditJson.Quote(op.Acr) + + ",\"executor\":" + AuditJson.Quote(op.Executor) + + (includeTicket && admission.Ticket is not null ? ",\"ticket\":" + AuditJson.Quote(admission.Ticket) : string.Empty) + + "}}"; + return AuditJson.CapObject(json); + } + private static string Provenance(string? callerMember, string? callerFile, int callerLine) => - AuditJson.CapObject( - "{\"caller\":{" - + "\"member\":" + AuditJson.Quote(callerMember ?? "") - + ",\"file\":" + AuditJson.Quote(ShortPath(callerFile)) - + ",\"line\":" + callerLine.ToString(CultureInfo.InvariantCulture) - + "}}"); + "{" + + "\"member\":" + AuditJson.Quote(callerMember ?? "") + + ",\"file\":" + AuditJson.Quote(ShortPath(callerFile)) + + ",\"line\":" + callerLine.ToString(CultureInfo.InvariantCulture) + + "}"; - /// - /// The last two segments of a compile-time path. - /// - /// - /// CallerFilePath is the absolute path on the machine that compiled the - /// assembly, so logging it whole puts a build-agent directory layout into every - /// forwarded line and tells a reader nothing the file name does not. - /// private static string ShortPath(string? path) { if (string.IsNullOrWhiteSpace(path)) @@ -307,14 +363,6 @@ private static string ShortPath(string? path) return segments.Length <= 2 ? string.Join('/', segments) : string.Join('/', segments[^2..]); } - // Warning, because a cross-tenant bypass is not an ordinary event and an operator - // filtering at Information must still see it. Still no tenant id: every one of these - // rows carries TenantId.PlatformSentinel, so logging it would be a constant. - // - // The audit entry id is what the line gained in Packet 9. The row is the durable - // record and this is the real-time signal, and without the id an operator alerting on - // the line has no key to find the row it is about — which is the whole of what the - // two are worth together. private static readonly Action LogEntered = LoggerMessage.Define( LogLevel.Warning, @@ -322,56 +370,59 @@ private static string ShortPath(string? path) "Platform-admin scope entered: {Reason} (from {Member} at {File}:{Line}). " + "Cross-tenant access under learnstack_platform, audit row {AuditEntryId}."); - /// One entry's connection and transaction. private sealed class Handle( - NpgsqlConnection connection, DbTransaction transaction, ILogger logger) + NpgsqlConnection connection, + NpgsqlTransaction transaction, + Func writeResult, + ILogger logger) : IPlatformAdminScopeHandle { private bool _resolved; private bool _disposed; - public DbConnection Connection + public async Task ExecuteAsync( + string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) { - get - { - EnsureUsable(); - return connection; - } + EnsureUsable(); + await using var command = Build(sql, parameters); + return await command.ExecuteNonQueryAsync(cancellationToken); } - public DbTransaction Transaction + public async Task> QueryAsync( + string sql, + IReadOnlyList? parameters, + Func map, + CancellationToken cancellationToken = default) { - get + EnsureUsable(); + ArgumentNullException.ThrowIfNull(map); + await using var command = Build(sql, parameters); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + var rows = new List(); + while (await reader.ReadAsync(cancellationToken)) { - EnsureUsable(); - return transaction; + rows.Add(map(reader)); } + + return rows; + } + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + { + EnsureUsable(); + return writeResult(result, cancellationToken); } public async Task CommitAsync(CancellationToken cancellationToken = default) { EnsureUsable(); - // Marked resolved BEFORE the await. Two things depend on the ordering and - // only one of them is observable, which is worth saying rather than - // implying. A COMMIT that faults at the server — - // a deferred constraint, a serialization failure — leaves the outcome - // genuinely unknown, and ADR-0033 calls that state Indeterminate rather - // than failed. Setting the flag afterwards would leave it false, so - // disposal would issue ROLLBACK on a transaction that is already over, - // which throws, which skips both disposals, which strands a BYPASSRLS - // connection outside the pool for the life of the process — measured, and - // it also replaces the caller's real PostgresException with a bookkeeping - // one. NpgsqlUnitOfWork nulls its transaction before the same await for the - // same reason. - // - // The catch in DisposeAsync makes that leak impossible on its own, so with - // both present this ordering is not independently observable — no test here - // fails if it is reverted, and none pretends to. What it still buys is the - // semantics: a faulted commit is Indeterminate, and attempting to undo an - // outcome nobody knows is a different claim from declining to. _resolved = true; await transaction.CommitAsync(cancellationToken); + + // The connection closes at completion, not at disposal: nothing may run on a + // connection that sees every tenant once its transaction is over. + await CloseAsync(); } public async ValueTask DisposeAsync() @@ -381,20 +432,8 @@ public async ValueTask DisposeAsync() return; } - _disposed = true; - try { - // Only an ABANDONED frame is rolled back. A frame that ended without - // resolving has failed, and leaving its writes for a later decision is - // how a partial cross-tenant mutation ships. A faulted commit is not - // that case and is deliberately left alone. - // - // The explicit rollback stays rather than relying on disposal: this - // field is a DbTransaction, whose base DisposeAsync delegates to an - // empty Dispose(bool). Rolling back on dispose is NpgsqlTransaction's - // own override, so dropping the line would make a cross-tenant rollback - // depend on the runtime type behind a base-class reference. if (!_resolved) { try @@ -403,36 +442,49 @@ public async ValueTask DisposeAsync() } catch (Exception failure) when (failure is InvalidOperationException or NpgsqlException) { - // A connection already broken by the failure being cleaned up - // after is the ordinary way here. Logged and swallowed, because - // throwing from disposal replaces whatever the caller was - // actually failing on. LogRollbackFailed(logger, failure); } } + } + finally + { + await CloseAsync(); + } + } + + private async ValueTask CloseAsync() + { + if (_disposed) + { + return; + } + _disposed = true; + try + { await transaction.DisposeAsync(); } finally { - // In a finally. Nothing above may strand the one connection in this - // process that sees every tenant. await connection.DisposeAsync(); } } - /// - /// Refuses a handle that is disposed or already resolved. - /// - /// - /// Resolved is terminal, and fencing Connection is the half that - /// matters. Measured: after a successful commit the connection is still - /// open, so a statement issued on it runs in autocommit — on a - /// BYPASSRLS connection, with no transaction to undo it. A write there - /// survives DisposeAsync, which is the exact opposite of what this - /// type's contract promises. Fencing only Transaction would leave that - /// hole open. - /// + private NpgsqlCommand Build(string sql, IReadOnlyList? parameters) + { + ArgumentException.ThrowIfNullOrWhiteSpace(sql); + var command = new NpgsqlCommand(sql, connection, transaction); + if (parameters is not null) + { + foreach (var parameter in parameters) + { + command.Parameters.AddWithValue(parameter.Name, parameter.Value ?? DBNull.Value); + } + } + + return command; + } + private void EnsureUsable() { ObjectDisposedException.ThrowIf(_disposed, this); @@ -442,8 +494,7 @@ private void EnsureUsable() throw new InvalidOperationException( "This platform-admin scope has been resolved and is no longer usable. " + "A caller needing further cross-tenant work takes a fresh scope: the " - + "connection bypasses Row Level Security, and a statement issued after " - + "the commit runs in autocommit, so disposal cannot roll it back."); + + "connection bypasses Row Level Security and is closed at completion."); } } } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/ConfigurationPlatformOperatorGrantSource.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/ConfigurationPlatformOperatorGrantSource.cs new file mode 100644 index 00000000..73f66041 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/ConfigurationPlatformOperatorGrantSource.cs @@ -0,0 +1,78 @@ +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// The shipped grant adapter: grants read from configuration, evaluated on every act +/// (ADR-0101 § 6). +/// +/// +/// +/// Evaluated per act, never cached beyond the options monitor. A removed grant takes +/// effect on the next act once the configuration provider reloads. A provider that cannot +/// reload needs a restart, and the operator-access runbook says so. +/// +/// +/// Fail closed. A reload that fails validation throws from the monitor; the adapter +/// answers "not granted" for everyone and logs once per failure rather than keeping a stale +/// answer. +/// +/// +public sealed class ConfigurationPlatformOperatorGrantSource( + IOptionsMonitor monitor, + ILogger logger) : IPlatformOperatorGrantSource +{ + private readonly IOptionsMonitor _monitor = + monitor ?? throw new ArgumentNullException(nameof(monitor)); + + private readonly ILogger _logger = + logger ?? throw new ArgumentNullException(nameof(logger)); + + /// + public ValueTask IsGrantedAsync( + string subjectDigest, string permissionKey, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(subjectDigest); + ArgumentException.ThrowIfNullOrWhiteSpace(permissionKey); + + PlatformOperatorGrantOptions current; + try + { + current = _monitor.CurrentValue; + } + catch (OptionsValidationException failure) + { + LogInvalidReload(_logger, failure); + return ValueTask.FromResult(false); + } + + if (string.IsNullOrWhiteSpace(current.Issuer)) + { + return ValueTask.FromResult(false); + } + + foreach (var grant in current.Grants) + { + if (string.IsNullOrWhiteSpace(grant.Subject) + || !string.Equals( + PlatformOperatorSubject.Digest(current.Issuer, grant.Subject), subjectDigest, StringComparison.Ordinal)) + { + continue; + } + + return ValueTask.FromResult( + grant.Permissions.Contains(permissionKey, StringComparer.Ordinal)); + } + + return ValueTask.FromResult(false); + } + + private static readonly Action LogInvalidReload = + LoggerMessage.Define( + LogLevel.Error, + new EventId(7101, nameof(LogInvalidReload)), + "PlatformOperator grants failed validation on reload; every operator act is refused " + + "until the configuration is valid."); +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs new file mode 100644 index 00000000..4e42415f --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs @@ -0,0 +1,73 @@ +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// The operator gate: it checks the witness, the registered operation, the ticket grammar and +/// a grant evaluated now, then mints the admission (ADR-0101 § 7). +/// +/// +/// +/// The one admission minter. It derives from , +/// and an architecture rule closes that census to this class. +/// +/// +/// Before any connection. It resolves no privileged credential. A refused operator +/// costs no bypass connection, which is what C14 asks of a tenant or wrong-purpose credential. +/// The refusal is a counter and a Warning log carrying the operation slug and the subject +/// digest; no durable row is written (ADR-0101 § 11). +/// +/// +public sealed partial class PlatformOperatorGate( + IPlatformOperatorGrantSource grants, + ILogger logger) : PlatformAdmission.Minter, IPlatformOperatorGate +{ + private readonly IPlatformOperatorGrantSource _grants = grants ?? throw new ArgumentNullException(nameof(grants)); + private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + /// + public async ValueTask AdmitAsync( + PlatformOperatorWitness operatorWitness, + PlatformOperation operation, + string? ticket, + CancellationToken cancellationToken = default) + { + if (operatorWitness is null) + { + return Refuse(PlatformRefusal.InvalidWitness, operation, null); + } + + if (!PlatformOperations.IsRegistered(operation)) + { + return Refuse(PlatformRefusal.UnknownOperation, null, operatorWitness); + } + + if (!PlatformTicket.IsValid(ticket)) + { + return Refuse(PlatformRefusal.InvalidTicket, operation, operatorWitness); + } + + if (!await _grants.IsGrantedAsync(operatorWitness.SubjectDigest, operation.Permission.Key, cancellationToken)) + { + return Refuse(PlatformRefusal.MissingPermission, operation, operatorWitness); + } + + PlatformOperatorMetrics.Admitted(operation); + return PlatformAdmissionResult.Admit(Mint(operatorWitness, operation, ticket)); + } + + private PlatformAdmissionResult Refuse( + PlatformRefusal refusal, PlatformOperation? operation, PlatformOperatorWitness? operatorWitness) + { + PlatformOperatorMetrics.Refused(refusal, operation); + LogRefused(_logger, refusal, operation?.AuditSlug ?? "unknown", operatorWitness?.SubjectDigest ?? "none"); + return PlatformAdmissionResult.Refuse(refusal); + } + + [LoggerMessage( + EventId = 7102, + Level = LogLevel.Warning, + Message = "Platform operator act refused: {Refusal} for {Operation} by operator {SubjectDigest}.")] + private static partial void LogRefused(ILogger logger, PlatformRefusal refusal, string operation, string subjectDigest); +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGrantOptions.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGrantOptions.cs new file mode 100644 index 00000000..0ce69b00 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGrantOptions.cs @@ -0,0 +1,79 @@ +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Options; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// One operator and the Platform permissions LearnStack holds for them. +public sealed class PlatformOperatorGrant +{ + /// The operator's opaque sub at the configured issuer. + public string? Subject { get; set; } + + /// The Platform permission keys granted, each registered in the catalogue. + public IList Permissions { get; init; } = []; +} + +/// +/// The configuration the shipped grant adapter binds: the issuer and the held grants +/// (ADR-0101 § 6). +/// +public sealed class PlatformOperatorGrantOptions +{ + /// The configuration section both the scheme and the grants read. + public const string SectionName = "PlatformOperator"; + + /// + /// The `sub` of the exported demo operator, pinned in the learnstack-hub realm + /// export. A grant for it is valid in Development only. + /// + public const string DemoOperatorSubject = "5a3c8f0e-2b1d-4c6a-9e47-0d1f6a2b7c93"; + + /// The pinned operator issuer; grants are meaningless without it. + public string? Issuer { get; set; } + + /// The held grants. + public IList Grants { get; init; } = []; +} + +/// Refuses to start on any grant that names an unregistered key or the demo operator outside Development. +public sealed class PlatformOperatorGrantOptionsValidator(DeploymentMode deploymentMode) + : IValidateOptions +{ + /// + public ValidateOptionsResult Validate(string? name, PlatformOperatorGrantOptions options) + { + ArgumentNullException.ThrowIfNull(options); + if (options.Grants.Count == 0) + { + return ValidateOptionsResult.Success; + } + + // Grants without an issuer are inert, not an error: with no issuer there is no operator + // scheme and the grant source answers "not granted" for everyone, so the surface stays + // closed. Every other rule below still applies to them. + var seen = new HashSet(StringComparer.Ordinal); + foreach (var grant in options.Grants) + { + if (string.IsNullOrWhiteSpace(grant.Subject) || !seen.Add(grant.Subject)) + { + return ValidateOptionsResult.Fail("A PlatformOperator grant needs a distinct, nonempty Subject."); + } + + if (grant.Permissions.Count == 0 || grant.Permissions.Any(key => !PlatformPermissions.TryGet(key, out _))) + { + return ValidateOptionsResult.Fail( + "A PlatformOperator grant lists only registered Platform permission keys."); + } + + if (string.Equals(grant.Subject, PlatformOperatorGrantOptions.DemoOperatorSubject, StringComparison.Ordinal) + && deploymentMode != DeploymentMode.Development) + { + return ValidateOptionsResult.Fail( + "The exported demo operator may hold a grant in Development only."); + } + } + + return ValidateOptionsResult.Success; + } +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs new file mode 100644 index 00000000..2d33d342 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -0,0 +1,43 @@ +using System.Diagnostics.Metrics; +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// Counters a monitoring owner can alert on without searching logs (ADR-0101 § 14). +public static class PlatformOperatorMetrics +{ + /// The meter name; covered by the host's learnstack.* subscription. + public const string MeterName = "learnstack.platform_operator"; + + private static readonly Meter Meter = new(MeterName); + + private static readonly Counter Admissions = + Meter.CreateCounter("learnstack.platform_operator.admissions", description: "Operator admissions by outcome and operation."); + + private static readonly Counter Refusals = + Meter.CreateCounter("learnstack.platform_operator.refusals", description: "Operator refusals by cause."); + + private static readonly Counter Results = + Meter.CreateCounter("learnstack.platform_operator.results", description: "MUST result rows written by operation."); + + /// Counts an admission. + public static void Admitted(PlatformOperation operation) => + Admissions.Add(1, new KeyValuePair("outcome", "admitted"), + new KeyValuePair("operation", operation.AuditSlug)); + + /// Counts a refusal by its cause. + public static void Refused(PlatformRefusal refusal, PlatformOperation? operation) + { + Admissions.Add(1, new KeyValuePair("outcome", "refused"), + new KeyValuePair("operation", operation?.AuditSlug ?? "unknown")); + Refusals.Add(1, new KeyValuePair("cause", refusal.ToString())); + } + + /// Counts a pre-authentication refusal, which never reaches the gate. + public static void Unauthenticated(string cause) => + Refusals.Add(1, new KeyValuePair("cause", cause)); + + /// Counts a written result row. + public static void Result(PlatformOperation operation) => + Results.Add(1, new KeyValuePair("operation", operation.AuditSlug)); +} diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index c2b3b98e..d8e07b9f 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -1,5 +1,6 @@ using System.Data.Common; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; namespace LearnStack.SharedKernel.Audit; @@ -143,6 +144,32 @@ Task WritePlatformScopeAsync( DbTransaction transaction, CancellationToken cancellationToken = default); + /// + /// Writes a platform operator act's MUST result row on the scope's work transaction, so it + /// commits with the state change or not at all (ADR-0101 § 10). + /// + /// + /// + /// A new witness-bound method, not a second caller of , + /// which keeps its single entry-row caller. The binds the + /// row: its operation slug, closed reason and operator digest must match the draft, the + /// actor user id is NULL because an operator is not a user, and the outcome is success. + /// The scope is the only caller. + /// + /// + /// The draft carries the real target tenant for a tenant-targeted act and the platform + /// sentinel for a platform-wide one. Like the entry row it is written on the platform-role + /// connection, which is why the request's own connection is the wrong place for it. + /// + /// + Task WritePlatformOperatorResultAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + throw new InvalidOperationException("This audit store cannot write a platform operator result."); + /// Inserts a MUST terminal audit on the successful transition's live transaction. /// /// The producer transition store is the only caller in P02b-2. The operation diff --git a/backend/src/LearnStack.SharedKernel/Entitlements/IKillswitchToggle.cs b/backend/src/LearnStack.SharedKernel/Entitlements/IKillswitchToggle.cs new file mode 100644 index 00000000..7b244176 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Entitlements/IKillswitchToggle.cs @@ -0,0 +1,40 @@ +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.SharedKernel.Entitlements; + +/// How a toggle request ended. +public enum KillswitchToggleOutcome +{ + /// The switch was set and recorded. + Applied = 1, + + /// The key is not in , so nothing was written. + UnknownKey = 2, +} + +/// What a toggle changed. +/// How the request ended. +/// The key the request named. +/// The state before the request; the registry default when no row existed. +/// The state after the request. +public sealed record KillswitchToggleResult( + KillswitchToggleOutcome Outcome, KillswitchKey Key, bool Before, bool After); + +/// +/// The killswitch writer: the service ADR-0045 Amendment 1 withheld until a Platform gate +/// existed (ADR-0101 § 13). +/// +/// +/// It is a service entered with a gate admission, not a MediatR request, so there is no +/// request type to key a catalogue entry on and the matrix row stays off-path. The caller +/// holds an admission for and no other. +/// +public interface IKillswitchToggle +{ + /// Sets to for every tenant. + Task ToggleAsync( + PlatformAdmission admission, + KillswitchKey key, + bool enabled, + CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs b/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs index 72512b7d..b4a747d2 100644 --- a/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs +++ b/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs @@ -13,12 +13,10 @@ namespace LearnStack.SharedKernel.Entitlements; /// true: a cache outage must not disable every gated path platform-wide. /// /// -/// Nothing flips one in this packet. Every toggle runs inside -/// EnterPlatformAdminScope(reason), whose registered gate is -/// DenyAllPlatformAdminGate, so -/// Phase 03 owns the -/// toggle command, its permission and its runbook. Every gated read honours a flipped -/// switch the day one exists; what is absent is the flipping +/// One writer flips them. The killswitch toggle service +/// (ADR-0101 § 13) +/// sets a key from this registry only, inside an admitted platform scope. Every gated read +/// honours a flipped switch /// (ADR-0045 /// Amendment 1 § 4). /// diff --git a/backend/src/LearnStack.SharedKernel/Platform/IPlatformOperatorGate.cs b/backend/src/LearnStack.SharedKernel/Platform/IPlatformOperatorGate.cs new file mode 100644 index 00000000..d2c44931 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IPlatformOperatorGate.cs @@ -0,0 +1,96 @@ +using System.Text.RegularExpressions; + +namespace LearnStack.SharedKernel.Platform; + +/// Why the gate refused an act. +public enum PlatformRefusal +{ + /// No refusal: the act is admitted. + None = 0, + + /// The witness is absent or is not a current operator principal. + InvalidWitness = 1, + + /// The operation is not one of the registered instances. + UnknownOperation = 2, + + /// The ticket does not match its grammar. + InvalidTicket = 3, + + /// The operator holds no grant for the operation's permission. + MissingPermission = 4, +} + +/// The gate's answer: an admission, or the reason it refused. +public sealed class PlatformAdmissionResult +{ + private PlatformAdmissionResult(PlatformAdmission? admission, PlatformRefusal refusal) + { + Admission = admission; + Refusal = refusal; + } + + /// The admission, when the act is admitted. + public PlatformAdmission? Admission { get; } + + /// The refusal, or . + public PlatformRefusal Refusal { get; } + + /// Whether the act is admitted. + public bool IsAdmitted => Admission is not null; + + /// An admitted result. + public static PlatformAdmissionResult Admit(PlatformAdmission admission) + { + ArgumentNullException.ThrowIfNull(admission); + return new(admission, PlatformRefusal.None); + } + + /// A refused result. + public static PlatformAdmissionResult Refuse(PlatformRefusal refusal) + { + if (refusal == PlatformRefusal.None) + { + throw new ArgumentOutOfRangeException(nameof(refusal), "A refusal needs a cause."); + } + + return new(null, refusal); + } +} + +/// +/// Decides, per act, whether an operator may perform one registered operation +/// (ADR-0101 § 7). +/// +/// +/// Admission runs before any privileged credential or connection is resolved, so a refused +/// operator costs no bypass connection. The gate reads a grant on every call and never reads +/// a claim. +/// +public interface IPlatformOperatorGate +{ + /// Admits or refuses for . + ValueTask AdmitAsync( + PlatformOperatorWitness operatorWitness, + PlatformOperation operation, + string? ticket, + CancellationToken cancellationToken = default); +} + +/// The held grants of the operator population (ADR-0101 § 6). +public interface IPlatformOperatorGrantSource +{ + /// Whether the operator holds the Platform permission, evaluated now. + ValueTask IsGrantedAsync( + string subjectDigest, string permissionKey, CancellationToken cancellationToken = default); +} + +/// The optional ticket grammar: 1 to 64 characters of [A-Za-z0-9._:/#-]. +public static partial class PlatformTicket +{ + /// Whether is absent or well formed. + public static bool IsValid(string? ticket) => ticket is null || TicketPattern().IsMatch(ticket); + + [GeneratedRegex(@"^[A-Za-z0-9._:/#-]{1,64}\z", RegexOptions.CultureInvariant)] + private static partial Regex TicketPattern(); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs new file mode 100644 index 00000000..796edd59 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs @@ -0,0 +1,49 @@ +namespace LearnStack.SharedKernel.Platform; + +/// +/// Proof that one operator may perform one registered operation now, minted only by the gate. +/// +/// +/// +/// It binds the operator, the operation, the optional ticket and the correlation id, so the +/// scope, the audit rows and the result method take them from here and no caller can supply +/// or forge them. It is short lived: the gate mints it at the act and nothing stores it. +/// +/// +/// The census is closed to the operator gate by an architecture rule. +/// +/// +public sealed class PlatformAdmission +{ + private PlatformAdmission(PlatformOperatorWitness operatorWitness, PlatformOperation operation, string? ticket) + { + ArgumentNullException.ThrowIfNull(operatorWitness); + ArgumentNullException.ThrowIfNull(operation); + Operator = operatorWitness; + Operation = operation; + Ticket = ticket; + } + + /// The authenticated operator. + public PlatformOperatorWitness Operator { get; } + + /// The registered operation admitted. + public PlatformOperation Operation { get; } + + /// The optional, grammar-checked ticket; it appears only in sentinel-tenant rows. + public string? Ticket { get; } + + /// + public override string ToString() => nameof(PlatformAdmission); + + /// The only constructor of an admission; the gate is its one subclass. +#pragma warning disable CA1034 // Nested type: the private constructor and the minter census close this set. + public abstract class Minter +#pragma warning restore CA1034 + { + /// Mints an admission after the gate has evaluated the grant. + protected static PlatformAdmission Mint( + PlatformOperatorWitness operatorWitness, PlatformOperation operation, string? ticket) => + new(operatorWitness, operation, ticket); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs new file mode 100644 index 00000000..7beebcba --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -0,0 +1,56 @@ +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.SharedKernel.Platform; + +/// One closed registry entry: what an operator act is, and what it needs. +/// +/// The reason is this entry's slug and never caller text, so the audit reason column +/// stays a value a query can group by (Standard 18). Construction is internal: the registry +/// in is the only place an operation exists. +/// +public sealed record PlatformOperation +{ + internal PlatformOperation( + string auditSlug, string reasonSlug, PermissionDefinition permission, bool needsPlatformRole) + { + ArgumentException.ThrowIfNullOrWhiteSpace(auditSlug); + ArgumentException.ThrowIfNullOrWhiteSpace(reasonSlug); + ArgumentNullException.ThrowIfNull(permission); + if (permission.Scope != PermissionScope.Platform) + { + throw new ArgumentException("A platform operation needs a Platform permission.", nameof(permission)); + } + + AuditSlug = auditSlug; + ReasonSlug = reasonSlug; + Permission = permission; + NeedsPlatformRole = needsPlatformRole; + } + + /// The audit operation slug of the result row. + public string AuditSlug { get; } + + /// The closed reason slug every row of this act carries. + public string ReasonSlug { get; } + + /// The Platform permission an operator must hold, evaluated per act. + public PermissionDefinition Permission { get; } + + /// Whether the act enters the platform scope (the BYPASSRLS role). + public bool NeedsPlatformRole { get; } +} + +/// The closed set of operator operations (ADR-0101 § 7). +public static class PlatformOperations +{ + /// Toggle a declared killswitch (ADR-0101 § 13). + public static PlatformOperation KillswitchToggle { get; } = new( + "tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true); + + /// Every registered operation. + public static IReadOnlyList All { get; } = [KillswitchToggle]; + + /// Whether is one of the registered instances. + public static bool IsRegistered(PlatformOperation? operation) => + operation is not null && All.Any(registered => ReferenceEquals(registered, operation)); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorSubject.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorSubject.cs new file mode 100644 index 00000000..474b65ba --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorSubject.cs @@ -0,0 +1,25 @@ +using System.Security.Cryptography; +using System.Text; + +namespace LearnStack.SharedKernel.Platform; + +/// The stable, non-reversible handle of one operator at one issuer. +/// +/// The unpadded base64url SHA-256 of learnstack.operator.subject.v1, a line feed, the +/// issuer, a line feed and the opaque sub. Audit rows and configuration grants carry +/// this digest, never the raw subject (ADR-0101 § 9). It is distinct from the identity +/// subject key: an operator is not a users row. +/// +public static class PlatformOperatorSubject +{ + private const string Domain = "learnstack.operator.subject.v1"; + + /// Computes the digest for an issuer and subject. + public static string Digest(string issuer, string subject) + { + ArgumentException.ThrowIfNullOrWhiteSpace(issuer); + ArgumentException.ThrowIfNullOrWhiteSpace(subject); + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes($"{Domain}\n{issuer}\n{subject}")); + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorWitness.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorWitness.cs new file mode 100644 index 00000000..88b26532 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorWitness.cs @@ -0,0 +1,76 @@ +namespace LearnStack.SharedKernel.Platform; + +/// +/// A validated operator principal, minted only by the operator authentication boundary. +/// +/// +/// +/// Nothing but a validated token produces one. The nested is the only +/// way to construct a witness, and the closed census of its subclasses is an architecture +/// rule: the operator scheme handler, and from Step 3 the offline rebind tool, which +/// validates the same token through the same validator (ADR-0101 § 7). +/// +/// +/// A witness is evidence of authentication and nothing more. It carries no authority; the +/// gate evaluates a grant per act. +/// +/// +public sealed class PlatformOperatorWitness +{ + private PlatformOperatorWitness( + string issuer, + string subjectDigest, + string acr, + DateTimeOffset authenticatedAt, + string executor, + string? correlationId) + { + ArgumentException.ThrowIfNullOrWhiteSpace(issuer); + ArgumentException.ThrowIfNullOrWhiteSpace(subjectDigest); + ArgumentException.ThrowIfNullOrWhiteSpace(acr); + ArgumentException.ThrowIfNullOrWhiteSpace(executor); + Issuer = issuer; + SubjectDigest = subjectDigest; + Acr = acr; + AuthenticatedAt = authenticatedAt; + Executor = executor; + CorrelationId = correlationId; + } + + /// The pinned operator issuer that authenticated the token. + public string Issuer { get; } + + /// The of the operator. + public string SubjectDigest { get; } + + /// The accepted acr value the token carried. + public string Acr { get; } + + /// When the operator last authenticated (auth_time). + public DateTimeOffset AuthenticatedAt { get; } + + /// The component that took the request, recorded as metadata.operator.executor. + public string Executor { get; } + + /// The correlation id of the request, when one exists. + public string? CorrelationId { get; } + + /// + public override string ToString() => nameof(PlatformOperatorWitness); + + /// The only constructor of a witness; its subclass census is closed by an architecture rule. +#pragma warning disable CA1034 // Nested type: the private constructor and the minter census close this set. + public abstract class Minter +#pragma warning restore CA1034 + { + /// Mints a witness from an already validated operator principal. + protected static PlatformOperatorWitness Mint( + string issuer, + string subjectDigest, + string acr, + DateTimeOffset authenticatedAt, + string executor, + string? correlationId) => + new(issuer, subjectDigest, acr, authenticatedAt, executor, correlationId); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs new file mode 100644 index 00000000..e5a21d7e --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -0,0 +1,36 @@ +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.SharedKernel.Platform; + +/// +/// The Platform permission catalogue: a closed set, kept apart from the tenant registry. +/// +/// +/// +/// A Platform definition is never assignable to a tenant Role and never enters the +/// administration grant union, so adding one changes neither the served tenant document nor +/// the OpenAPI gate (ADR-0101 § 5, ADR-0100 Amendment 1). The set grows one packet at a +/// time: a key is registered with the operation that has a denied proof for it, never +/// ahead of it. +/// +/// +/// Registration grants nothing. Authority is a grant held by LearnStack and evaluated per act +/// by . +/// +/// +public static class PlatformPermissions +{ + /// Toggle a declared killswitch. + public static PermissionDefinition KillswitchWrite { get; } = + new(PermissionScope.Platform, "platform.killswitch.write"); + + /// Every registered Platform permission. + public static IReadOnlyList All { get; } = [KillswitchWrite]; + + /// Finds a registered Platform permission by its key. + public static bool TryGet(string? key, out PermissionDefinition definition) + { + definition = All.FirstOrDefault(candidate => string.Equals(candidate.Key, key, StringComparison.Ordinal))!; + return definition is not null; + } +} diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs deleted file mode 100644 index 79e3f3b5..00000000 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace LearnStack.SharedKernel.Tenancy; - -/// -/// Decides whether the caller may enter the platform-admin scope at all. -/// -/// -/// A separate port, and not a check inlined into , -/// because -/// ADR-0036 -/// § The platform-admin override is not a resolution source requires the -/// permission to be "checked before the scope opens" — a collaborator makes that a -/// real call rather than a -/// comment. Phase 03 replaces the shipped implementation with one that reads the actor's -/// platform-scope permission. -/// -public interface IPlatformAdminGate -{ - /// Whether entry is permitted, for the stated reason. - ValueTask IsPermittedAsync(string reason, CancellationToken cancellationToken = default); -} - -/// The gate that permits nobody. -/// -/// -/// This is correct, and it will look like a bug — the same shape and the same -/// argument as . P02b-5 authenticates tenant -/// principals but no application permission exists until Phase 03, so "nobody holds -/// a platform-scope permission" is the true answer rather than a placeholder, and a gate -/// that were permissive in Development would reproduce exactly the configuration -/// inversion the composition root argues against elsewhere: the demo passes and -/// production refuses. -/// -/// -/// Callers still inherit a closed gate. Redaction and other privileged -/// operations cannot use tenant authentication as a platform-scope permission. -/// Phase 03 owns the permission-aware replacement. -/// -/// -public sealed class DenyAllPlatformAdminGate : IPlatformAdminGate -{ - /// - public ValueTask IsPermittedAsync( - string reason, CancellationToken cancellationToken = default) => - ValueTask.FromResult(false); -} - -/// Thrown when refuses entry. -/// -/// An exception rather than a Result: a caller that asked for a cross-tenant -/// bypass and was refused has no second path to take, and there is no request pipeline -/// here to render a failure into. It carries no tenant, no actor and no connection -/// detail — only that entry was refused and why the caller said it wanted in. -/// -public sealed class PlatformAdminScopeDeniedException : Exception -{ - public PlatformAdminScopeDeniedException(string reason) - : base($"Platform-admin scope entry was refused for reason '{reason}'.") => - Reason = reason; - - public PlatformAdminScopeDeniedException() - : base("Platform-admin scope entry was refused.") - { - } - - public PlatformAdminScopeDeniedException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// The reason the caller gave. Never a connection detail. - public string? Reason { get; } -} diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs index a84930af..3c4461e4 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs @@ -1,131 +1,99 @@ using System.Data.Common; using System.Runtime.CompilerServices; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; namespace LearnStack.SharedKernel.Tenancy; /// -/// The one sanctioned path to a connection that bypasses Row Level Security. +/// Opens an audited, bounded scope on the learnstack_platform role for one admitted +/// operator act. /// /// /// -/// A second connection, never SET ROLE. -/// ADR-0003 -/// gives three reasons and each rules the alternative out on its own: -/// learnstack_app is not a member of learnstack_platform, and a membership -/// grant would make the bypass a standing capability of the application role reachable -/// from any code path that emits raw SQL; a plain SET ROLE survives COMMIT -/// and would persist on a PgBouncer transaction-pooled server connection into the next -/// tenant's request; and per-role settings such as statement_timeout are applied -/// at login and do not follow a role switch. +/// Admission first. The caller holds a from +/// , so the permission was evaluated before this call +/// and a refused operator never reaches a connection (ADR-0036, ADR-0101 § 7). The reason, +/// the operator and the correlation id come from the admission, and the compiler-supplied +/// caller attributes record where the scope was entered. /// /// -/// It is not one of the tenant-context writers, and not a setter of -/// app.tenant_id. It sets no tenant context at all — there is no policy to -/// announce to, because the role bypasses them — so it is outside both closed sets: -/// the four writers of ITenantContextAccessor.Current -/// (ADR-0036 -/// § Rules, which names it as explicitly not one) and the eight out-of-band -/// setters (ADR-0040 -/// Amendments 3 and 7, whose closing property is that every one of them connects -/// as learnstack_app). +/// Entry is audited, and refusing to record it refuses the entry. One +/// platform.admin_scope.enter row is written on the scope's own connection in a +/// transaction that commits before the caller's work begins (ADR-0044 § 10), so an act that +/// later fails or is abandoned is still on the record. It carries the operator in +/// metadata.operator and no actor user id, because an operator is not a user. /// /// -/// Entry is audited, and an entry that cannot be recorded does not happen. Every -/// permitted entry writes one platform.admin_scope.enter row — the slug the -/// Tenancy catalogue source declares off-path at MUST / SecurityEvent — through -/// IAuditStore.WritePlatformScopeAsync, as learnstack_platform, on the -/// scope's own connection and in a transaction of its own that commits before the -/// handle is returned, so an operation that later fails — or is abandoned, or reads across -/// every tenant and then throws — is still on the record -/// (ADR-0044 § 10). -/// It is the one class of row carrying TenantId.PlatformSentinel. The row used to -/// ride the handle's transaction, so rolling the work back erased the only record that -/// privileged access had happened; the review of Packet 9 measured it, and an entry is now -/// recorded whatever the work then does. -/// The permission gate runs first; a refused attempt opens no privileged connection and -/// writes no entry row. -/// -/// -/// The Warning log line stays, and it is not the record. The row is what a -/// compliance reviewer reads afterwards; the log line is what an operator alerting at -/// Warning sees while it is happening, and it carries the row's id so the two are -/// one another's index. Packet 7 shipped the line alone and said so; Packet 9 added the -/// row it stood in for. +/// The handle exposes no connection. A reference to a BYPASSRLS connection +/// captured before the commit would run in autocommit afterwards, so the handle offers a +/// bounded facade instead. Completion and abandonment close the connection (ADR-0101 § 8). /// /// public interface IPlatformAdminScope { - /// - /// Opens a platform-role connection and transaction, or refuses. - /// - /// - /// Why this cross-tenant access is happening. Required, non-blank, and the value - /// the entry row writes durably — so it is a short operator-authored slug naming the - /// operation, never a caller-supplied string and never anything carrying personal - /// data beyond the identifier the operation is already about. - /// - /// Cancels the open, not an operation already inside. - /// Supplied by the compiler; do not pass. - /// Supplied by the compiler; do not pass. - /// Supplied by the compiler; do not pass. - /// - /// The three Caller* parameters record the calling code. Tenant principals - /// do not authorize this bypass: the shipped platform gate denies everyone, and - /// this scope accepts no operator identity. Phase 03 owns permission-aware entry - /// and actor attribution. Compiler provenance remains distinct from that identity. - /// + /// Enters the scope for an admitted act. + /// The gate's proof for one operation that needs the platform role. + /// Cancellation. + /// Compiler supplied. + /// Compiler supplied. + /// Compiler supplied. Task EnterAsync( - string reason, + PlatformAdmission admission, CancellationToken cancellationToken = default, [CallerMemberName] string? callerMember = null, [CallerFilePath] string? callerFile = null, [CallerLineNumber] int callerLine = 0); } +/// A positional SQL parameter for the scope's bounded facade. +/// The parameter name, without a prefix. +/// The value; null binds SQL NULL. +public sealed record PlatformSqlParameter(string Name, object? Value); + +/// The state change one act records as its MUST result row. +/// +/// The real target tenant, or for a platform-wide act. +/// +/// The affected entity type, when there is one. +/// The affected entity id, when there is one. +/// The before state as JSON, when there is one. +/// The after state as JSON, when there is one. +public sealed record PlatformResult( + TenantId TenantId, + string? EntityType, + string? EntityId, + string? BeforeState, + string? AfterState); + /// -/// An open platform-role connection and its transaction, for as long as it is held. +/// The work one scope entry allows: a transaction on the platform role, as a facade. /// /// -/// -/// A connection, not a DbContext. ADR-0003 and -/// architecture/09 -/// both say "a second connection"; two editable carriers said "a DI scope whose -/// DbContext is built on that data source" and have been corrected to match, -/// because only this shape compiles against what is already shipped — every module -/// DbContext is bound to IUnitOfWork.Connection, which comes from the -/// application data source that the composition root guards to be -/// learnstack_app by name. Nothing is foreclosed: EF can be built on this -/// connection by whoever needs it. -/// -/// -/// Disposing without committing rolls back, and the connection is returned whatever -/// happens. The same posture the ambient unit of work takes, and it matters more -/// here: a leaked handle holds the one BYPASSRLS connection in the process, and -/// stranding it outside the pool costs the process rather than the request. -/// -/// -/// System.Data.Common types rather than Npgsql ones because this assembly -/// references no database driver — the same reason IUnitOfWork.Connection is a -/// . -/// +/// One scope, one transaction, one commit. After or disposal +/// the handle refuses every call and the underlying connection is closed, so nothing a +/// caller captured can run an autocommit statement on a connection that sees every tenant. +/// Disposing without committing rolls back. /// public interface IPlatformAdminScopeHandle : IAsyncDisposable { - /// The open connection, authenticated as the platform role. - DbConnection Connection { get; } + /// Executes one non-query statement on the work transaction. + Task ExecuteAsync( + string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default); - /// The transaction every command in this scope runs on. - DbTransaction Transaction { get; } + /// Runs one query on the work transaction and maps each row before the reader closes. + Task> QueryAsync( + string sql, + IReadOnlyList? parameters, + Func map, + CancellationToken cancellationToken = default); + + /// + /// Writes the act's MUST result row on the work transaction, so it commits with the + /// state change or not at all. + /// + Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default); - /// Commits, and ends the handle's usefulness. - /// - /// An abandoned frame — disposed without this — is rolled back. A - /// faulted commit is not: the server-side outcome is genuinely unknown, and - /// ADR-0033 calls that state Indeterminate rather than failed. Either way the handle - /// is finished: reading or - /// afterwards throws, because the connection is still open and a statement issued on - /// it would run in autocommit, on a credential that sees every tenant, with nothing - /// left to undo it. - /// + /// Commits the work transaction and closes the scope. Task CommitAsync(CancellationToken cancellationToken = default); } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 05c310da..43483b17 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -110,6 +110,10 @@ public void Describe(IAuditCatalogBuilder builder) // to name the same one. .DeclareOffPath( "platform.admin_scope.enter", OperationType.SecurityEvent, OperationClass.Must) + // The killswitch flip is written inside an admitted platform scope on its work + // transaction (ADR-0101 § 13); the scope is a service, so there is no request type. + .DeclareOffPath( + "tenancy.killswitch.toggle", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.outbox.dead_letter", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs index 135ca010..05864a88 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs @@ -244,14 +244,10 @@ public static PlatformHostMapping Create( /// § 5). /// /// -/// No writer ships with it, and that is reachability rather than scheduling. Every -/// toggle runs inside EnterPlatformAdminScope(reason) whose registered gate is -/// DenyAllPlatformAdminGate, so nothing can enter that scope until the -/// Platform-scope permission arrives with the registry in -/// Phase 03, -/// which owns the toggle command, its permission and its runbook. A command shipped now -/// would be unreachable code keyed on a permission nothing registers. Every gated read -/// honours a flipped switch the day one exists; what is absent is the flipping. +/// The writer is the killswitch toggle service, which runs inside an admitted platform +/// scope and records a MUST row on the same transaction +/// (ADR-0101 § 13). +/// Every gated read honours a flipped switch. /// /// public sealed class PlatformKillswitch diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs index 44102f67..58b38ba4 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs @@ -17,12 +17,10 @@ namespace LearnStack.Modules.Tenancy.Infrastructure; /// can see it. /// /// -/// No writer, and that is reachability rather than scheduling. Every toggle runs -/// inside EnterPlatformAdminScope(reason) whose registered gate is -/// DenyAllPlatformAdminGate, so -/// Phase 03 owns -/// the toggle command, its permission and its runbook. This type reads a table nothing in -/// this packet can write, and every gated read honours a flipped switch the day one exists. +/// One writer. The killswitch toggle service flips a key inside an admitted platform scope +/// and drops this cache entry after the commit +/// (ADR-0101 § 13). +/// This type only reads, and every gated read honours a flipped switch. /// /// /// @@ -57,8 +55,8 @@ public sealed class KillswitchOverlay( /// Stated here rather than inherited. Standards 20 fixes this family at the /// 60-second hot-path default, and it IS the staleness bound an operator sees: a /// killswitch flipped during an incident takes at most this long to take effect on an - /// instance whose cache is warm, because Packet 9 ships no writer to invalidate it - /// eagerly. Phase 03's toggle command ships the invalidation with it. + /// instance whose cache is warm, on an instance other than the one that flipped it, because the writer + /// drops only its own process's entry. The flipping instance sees the change at once. /// public static readonly TimeSpan OverlayTtl = TimeSpan.FromSeconds(60); diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs new file mode 100644 index 00000000..286e6b86 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs @@ -0,0 +1,116 @@ +using LearnStack.SharedKernel.Caching; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Modules.Tenancy.Infrastructure; + +/// +/// Writes platform_killswitches inside an admitted platform scope and records the +/// flip as a MUST row on the same transaction (ADR-0101 § 13). +/// +/// +/// +/// Order. Resolve the key from only, enter the scope +/// (which records its entry first), read the before state, upsert, write the MUST result row +/// on the work transaction, commit, and only then remove the overlay cache entry. Removing +/// before the commit would let a concurrent load repopulate the stale value; removing after +/// a commit whose outcome is unknown still happens, because the flip may have landed. +/// +/// +/// What it does not do. It cannot reach other instances: the cache is process-local +/// and the overlay refreshes within . The runbook +/// states that lag. Concurrent toggles are last writer wins; the row has no version. +/// +/// +public sealed class KillswitchToggle( + IPlatformAdminScope scope, + ICacheService cache, + IClock clock) : IKillswitchToggle +{ + private const string SelectBefore = "SELECT is_enabled FROM platform_killswitches WHERE key = @key FOR UPDATE"; + + private const string Upsert = + "INSERT INTO platform_killswitches (key, is_enabled, reason, toggled_at, toggled_by) " + + "VALUES (@key, @enabled, @reason, @at, NULL) " + + "ON CONFLICT (key) DO UPDATE SET is_enabled = EXCLUDED.is_enabled, " + + "reason = EXCLUDED.reason, toggled_at = EXCLUDED.toggled_at, toggled_by = NULL"; + + /// + public async Task ToggleAsync( + PlatformAdmission admission, KillswitchKey key, bool enabled, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, PlatformOperations.KillswitchToggle)) + { + throw new ArgumentException("The admission is not for a killswitch toggle.", nameof(admission)); + } + + if (!KillswitchKeys.All.TryGetValue(key, out var registryDefault)) + { + return new KillswitchToggleResult(KillswitchToggleOutcome.UnknownKey, key, true, true); + } + + var commitAttempted = false; + try + { + await using var handle = await scope.EnterAsync(admission, cancellationToken); + + var rows = await handle.QueryAsync( + SelectBefore, + [new PlatformSqlParameter("key", key.Value)], + reader => reader.GetBoolean(0), + cancellationToken); + var before = rows.Count == 0 ? registryDefault : rows[0]; + + await handle.ExecuteAsync( + Upsert, + [ + new PlatformSqlParameter("key", key.Value), + new PlatformSqlParameter("enabled", enabled), + new PlatformSqlParameter("reason", admission.Ticket), + new PlatformSqlParameter("at", clock.UtcNow), + ], + cancellationToken); + + await handle.WriteResultAsync( + new PlatformResult( + TenantId.PlatformSentinel, + "PlatformKillswitch", + key.Value, + State(before), + State(enabled)), + cancellationToken); + + commitAttempted = true; + await handle.CommitAsync(cancellationToken); + return new KillswitchToggleResult(KillswitchToggleOutcome.Applied, key, before, enabled); + } + finally + { + if (commitAttempted) + { + // Including an indeterminate commit: the flip may have landed, and a stale + // cache entry must not outlive it. A failure here is not the caller's to + // handle; the entry expires within the overlay TTL regardless. + await RemoveCacheAsync(); + } + } + } + + private static string State(bool enabled) => enabled ? "{\"isEnabled\":true}" : "{\"isEnabled\":false}"; + + private async Task RemoveCacheAsync() + { + try + { + await cache.RemoveAsync(CacheKey.ForKillswitchOverlay(), CancellationToken.None); + } + catch (InvalidOperationException) + { + // The cache is an optimisation here; the overlay TTL bounds the lag. + } + } +} diff --git a/backend/tests/Fixtures/TestPlatformAdmissions.cs b/backend/tests/Fixtures/TestPlatformAdmissions.cs new file mode 100644 index 00000000..89363cb3 --- /dev/null +++ b/backend/tests/Fixtures/TestPlatformAdmissions.cs @@ -0,0 +1,38 @@ +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.Tests.Fixtures; + +/// +/// Test-only mints of operator witnesses and admissions. Production owns the closed minter +/// census (the operator scheme and the gate); a test mints through its own nested subclasses, +/// which the census architecture test does not scan. +/// +internal static class TestPlatformAdmissions +{ + internal const string Issuer = "https://operator.test/realms/learnstack-hub"; + + internal static PlatformOperatorWitness Witness(string subject = "operator-1", string? correlationId = "00-test-trace-01") => + WitnessMinter.Create( + Issuer, PlatformOperatorSubject.Digest(Issuer, subject), "mfa", DateTimeOffset.UtcNow, "operator.test", correlationId); + + internal static PlatformAdmission Admission( + PlatformOperation? operation = null, + string? ticket = null, + string subject = "operator-1", + string? correlationId = "00-test-trace-01") => + AdmissionMinter.Create(Witness(subject, correlationId), operation ?? PlatformOperations.KillswitchToggle, ticket); + + private sealed class WitnessMinter : PlatformOperatorWitness.Minter + { + internal static PlatformOperatorWitness Create( + string issuer, string digest, string acr, DateTimeOffset at, string executor, string? correlationId) => + Mint(issuer, digest, acr, at, executor, correlationId); + } + + private sealed class AdmissionMinter : PlatformAdmission.Minter + { + internal static PlatformAdmission Create( + PlatformOperatorWitness witness, PlatformOperation operation, string? ticket) => + Mint(witness, operation, ticket); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs index 19bbb9a1..9d1e412e 100644 --- a/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs @@ -105,6 +105,6 @@ public void Unversioned_Route_Prefixes_Are_Declared_Once() // its contents keeps a silent widening — someone adding "api" to make // a route work — visible as a failing test rather than as a hole. VersionedRouteConvention.UnversionedRoutePrefixes - .Should().Equal("api/internal"); + .Should().Equal("api/internal", "api/platform"); } } diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index e98ac41f..e0258d67 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -516,7 +516,7 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046, ADR-0047, ADR-0072 and ADR-0077 authorize ten writes and no update; another method would + // ADR-0046, ADR-0047, ADR-0072, ADR-0077 and ADR-0101 authorize eleven writes and no update; another method would // make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) @@ -524,7 +524,7 @@ public void IAuditStore_Exposes_No_Update_Method() "WritePendingAsync", "WriteStandaloneAsync", "WriteBestEffortAsync", "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync", - "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync"); + "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs index 40e5df01..b458c984 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs @@ -1027,7 +1027,12 @@ private static bool IsRouteAttribute(TypeReference attribute, Dictionary MappingSites(IEnumerable modules, Func? predicate = null) => - Types(modules).SelectMany(type => type.Methods).Where(method => method.HasBody) + // The platform operator surface is a separate closed surface with its own scheme and its own exact + // census (PlatformOperatorHttpTests: the endpoint set, methods and policy). It is not part of the + // tenant surface this rule closes, and excluding it is by exact type, so a mapping added anywhere else + // is still an offender. + Types(modules).Where(type => type.FullName != "LearnStack.Api.Platform.PlatformOperatorEndpoints") + .SelectMany(type => type.Methods).Where(method => method.HasBody) .SelectMany(method => method.Body.Instructions.Where(instruction => instruction.Operand is MethodReference target && (predicate ?? IsEndpointMapping)(target) && !EndpointComposition.IsFixedInfrastructureMetadata(method, instruction)) .Select(instruction => new Mapping(method, instruction, (MethodReference)instruction.Operand))); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 032f9de5..14d4cea8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -356,6 +356,14 @@ private static bool IsClosedInvitationForwarding(Method method, Instruction inst "LearnStack.SharedKernel.Permissions.OperationInvocation", "System.Threading.CancellationToken"); } + /// + /// The operator token profile is its own authority (ADR-0101 § 2, § 3) and reads the validated + /// operator token's claims by design. It is exempt by exact type and method, so a raw read in any + /// other method of that type, or anywhere else, is still an offender. + /// + private static bool IsOperatorTokenProfileRead(Call call) => + call.Source.Owner.FullName == Authentication + "PlatformOperatorTokenProfile" && call.Source.Name == "TryRead"; + private static bool IsClosedRolesAbsenceCheck(Call call) { if (call.Source.Site != Signature(Authentication + "OperationHttpClassifier", "Classify", Authentication + "HttpOperationClassification", diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs index 68c05c5f..2900ecca 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs @@ -88,7 +88,7 @@ private static SortedSet Offenders(ModuleDefinition[] modules, foreach (var call in calls.Where(call => (rawReader ?? IsRawAuthorityRead)(call.Target) && !(call.Source.Site == ExpectedSite(Events + ".TokenValidated") && call.Target.FullName == "System.String Microsoft.IdentityModel.JsonWebTokens.JsonWebToken::get_EncodedToken()") - && !IsClosedRolesAbsenceCheck(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls))) + && !IsClosedRolesAbsenceCheck(call) && !IsOperatorTokenProfileRead(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls))) errors.Add("Raw claim/role authority: " + call.Source.Site + " -> " + call.Target.FullName); // Object virtual dispatch and generic formatting can export a positional // record without an identity-declared call. Close acquisition, holders diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs index b1736b88..2a128949 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs @@ -248,7 +248,12 @@ private static SortedSet JobManifestOffenders(ProductionCensus census) if (offenders.Count != 0) return offenders; var bodies = OwnedBodies(census).ToArray(); - var sites = bodies.SelectMany(item => item.Body.Body.Instructions + // The platform operator surface (ADR-0101 § 4) is its own closed surface with its own scheme, and it + // maps minimal endpoints (a group, one verb, one policy, one fixed metadata) rather than controllers. + // It is excluded by exact type, so any other body that registers an endpoint is still counted here; + // the operator surface's own population is asserted in PlatformOperatorHttpTests. + var sites = bodies.Where(item => item.Owner.DeclaringType.FullName != "LearnStack.Api.Platform.PlatformOperatorEndpoints") + .SelectMany(item => item.Body.Body.Instructions .Where(instruction => instruction.Operand is MethodReference) .Select(instruction => (item.Owner, Instruction: instruction, Target: (MethodReference)instruction.Operand))).ToArray(); var invitation = types[("LearnStack.Modules.Identity.Infrastructure", typeof(InvitationEmailRegistration).FullName!)]; diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 55d9ec3a..8f3d3b65 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -2,6 +2,8 @@ using FluentAssertions; using LearnStack.Api.Messaging; using LearnStack.Infrastructure.Messaging; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; using Microsoft.Extensions.DependencyInjection; using Xunit; @@ -150,46 +152,82 @@ public void No_IgnoreQueryFilters_Outside_PlatformAdminScope() } [Fact] - public async Task PlatformAdminScope_Entry_Requires_Platform_Permission() + public void PlatformAdminScope_Entry_Requires_Platform_Permission() { - // Conjunct A — live. The gate port exists, the registered implementation refuses - // everyone, and the scope consults it. That last part is what makes ADR-0036's - // "checked before the scope opens" a call rather than a sentence; the ORDER — - // before the credential is touched — is asserted behaviourally in - // PlatformAdminGateTests, which a structural test cannot see. - typeof(IPlatformAdminGate).Should().BeAssignableTo(); - - (await new DenyAllPlatformAdminGate().IsPermittedAsync("any", CancellationToken.None)) - .Should().BeFalse("the shipped gate permits nobody until Phase 03"); - - SourceScan.FilesContaining(SourceScan.SourceRoot, "IsPermittedAsync", except: null) - .Should().Contain(ScopeFile, "the scope must actually consult the gate"); - - // Conjunct B — VACUOUS, and doubly so. The permission key itself does not exist: - // there is no permission system until Phase 03, and no production caller enters - // the scope at all. What can be asserted now is that no second gate - // implementation has appeared to sit beside the deny-all one, because that is how - // a permissive default arrives — registered somewhere else, for a demo. - // Swept across every production assembly, not just the one declaring the - // interface. The first version scanned typeof(IPlatformAdminGate).Assembly — - // SharedKernel — so a permissive gate in Infrastructure or Api, which is exactly - // where "registered elsewhere for a demo" would put one, was invisible to the - // rule whose own message names that scenario. The mutation that was supposed to - // prove this leg passed only because the probe was planted in SharedKernel too. - var gates = ProductionAssemblies() - .SelectMany(assembly => assembly.GetTypes()) - .Where(type => type is { IsAbstract: false, IsInterface: false }) - .Where(typeof(IPlatformAdminGate).IsAssignableFrom) - .Select(type => type.Name) + // Conjunct A — the scope takes an admission and nothing else. ADR-0036 asks for the + // permission to be "checked before the scope opens"; ADR-0101 § 7 makes that a type: + // the only way to hold a PlatformAdmission is to have passed the gate, so entry + // cannot happen unadmitted. The ORDER — before the credential is touched — is asserted + // behaviourally in PlatformAdminGateTests, which a structural test cannot see. + typeof(IPlatformAdminScope).GetMethod(nameof(IPlatformAdminScope.EnterAsync))! + .GetParameters()[0].ParameterType.Should().Be( + "entry takes the gate's proof and no caller-supplied reason or flag"); + + // Conjunct B — the admission census is closed. Swept across every production + // assembly, not just the one declaring the types: a permissive minter or gate would + // be registered somewhere else, for a demo, and that is exactly where a narrowed scan + // would not look. Test assemblies are not scanned, so a test double does not widen it. + var types = ProductionAssemblies().SelectMany(assembly => assembly.GetTypes()) + .Where(type => type is { IsAbstract: false, IsInterface: false }).ToList(); + + Names(types, typeof(PlatformAdmission.Minter)).Should().BeEquivalentTo( + [nameof(PlatformOperatorGate)], + "only the gate mints an admission, after it has evaluated a grant"); + Names(types, typeof(PlatformOperatorWitness.Minter)).Should().BeEquivalentTo( + ["PlatformOperatorWitnessMinter"], + "only the operator authentication boundary mints a witness; the rebind tool joins in " + + "Step 3 by an edit to this list, not by accident"); + Names(types, typeof(IPlatformOperatorGate)).Should().BeEquivalentTo( + [nameof(PlatformOperatorGate)], "a second gate is how a permissive default ships"); + Names(types, typeof(IPlatformOperatorGrantSource)).Should().BeEquivalentTo( + [nameof(ConfigurationPlatformOperatorGrantSource)], + "a second grant source is how a permissive grant ships; the table adapter joins on its trigger"); + } + + [Fact] + public void Only_The_Operator_Services_Hold_The_Platform_Scope() + { + // The scope is reachable from the services that perform an admitted operator act and + // from nowhere else. A request handler holding it would enter a cross-tenant scope + // from a tenant request path, which the marker rules forbid for a platform entry. + SourceScan.FilesContaining(SourceScan.SourceRoot, "IPlatformAdminScope", except: null) + .Select(Path.GetFileName) + .Should().BeEquivalentTo( + [ + "IPlatformAdminScope.cs", + "PlatformAdminScope.cs", + "PersistenceCompositionExtensions.cs", + "KillswitchToggle.cs", + ], + "each new operator service is added here deliberately, with its denied proof"); + } + + [Fact] + public void Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer() + { + // ADR-0101 § 13: the overlay reads the table, so a rule on every mention would be + // wrong; the confinement is on the write verbs. The writer upserts, so INSERT is the + // literal that must be present and UPDATE/DELETE the ones that must stay absent. + var writers = KillswitchWriteVerbs + .SelectMany(verb => SourceScan.FilesContaining(SourceScan.SourceRoot, verb, except: null)) + .Select(Path.GetFileName) .Distinct() .ToList(); - gates.Should().BeEquivalentTo( - [nameof(DenyAllPlatformAdminGate)], - "Phase 03 replaces this one; a second implementation appearing before then is " - + "how 'permissive to unblock a demo' gets shipped"); + writers.Should().BeEquivalentTo(["KillswitchToggle.cs"], "the writer alone writes the table"); } + private static readonly string[] KillswitchWriteVerbs = + [ + "INSERT INTO platform_killswitches", + "UPDATE platform_killswitches", + "DELETE FROM platform_killswitches", + "TRUNCATE platform_killswitches", + ]; + + private static List Names(IEnumerable types, Type baseType) => + types.Where(baseType.IsAssignableFrom).Select(type => type.Name).Distinct().ToList(); + [Fact] public void The_Platform_Scope_Writes_No_Tenant_Context_And_Sets_No_Session_Variable() { diff --git a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs index fad7a5b5..c6a19df9 100644 --- a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs +++ b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs @@ -25,6 +25,15 @@ protected sealed override void ConfigureWebHost(IWebHostBuilder builder) { ArgumentNullException.ThrowIfNull(builder); InvitationEmailFixtureConfiguration.AddTo(builder); + // Development configuration carries an operator issuer for the real developer stack + // (ADR-0101 § 12). A test host starts without one, so the tenant boundary is judged on its + // own; a case about the operator surface sets the issuer itself, after this line. + builder.UseSetting("PlatformOperator:Issuer", string.Empty); + // Development also grants the exported demo operator, which the grant validator refuses + // outside Development, and these hosts run under several modes. Pointing the one entry at a + // subject nobody holds keeps the grant list valid and matches no one. + builder.UseSetting("PlatformOperator:Grants:0:Subject", "test-host-matches-no-operator"); + builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", "platform.killswitch.write"); ConfigureTestHost(builder); builder.ConfigureTestServices(services => { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs index b236ed30..93d3c627 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs @@ -18,7 +18,6 @@ public async Task DTO_construction_and_attempt_ID_factory_cannot_open_ordinary_o await BackgroundJobSchemaSeed.SeedTenantsAsync(database.AppConnectionString); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); var probe = new BackgroundJobFixtureProbe(); - var gate = new PermissiveGate(); var ids = new CallbackGuidFactory(); var callbacks = 0; var constructor = Fixture.ParameterType.GetField("OnConstruction")!; @@ -46,7 +45,6 @@ Action For(IServiceProvider services) => () => { observation.Configure(services); services.AddSingleton(ids); - services.AddSingleton(gate); }); try { @@ -55,7 +53,6 @@ Action For(IServiceProvider services) => () => result.Outcome.Should().Be(JobStartExecutionOutcome.Started); callbacks.Should().BeGreaterThan(0, "the callback must actually run in the production DTO/factory path"); probe.Constructions.Should().BeEmpty(); - gate.Calls.Should().Be(0, "privileged refusal precedes the deliberately permissive gate"); (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(1); } finally diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs index 4c165671..ba366e59 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs @@ -110,7 +110,6 @@ public async Task The_preread_is_physically_readonly_RLS_scoped_and_framework_au BackgroundJobRuntimeFixture.OrganizationKey, SchemaFixture.OrgA2); var otherTenant = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, tenant: SchemaFixture.TenantB); var probe = new BackgroundJobFixtureProbe(); - var gate = new PermissiveGate(); var reads = 0; var starts = 0; var observation = new BackgroundJobAdmissionObservation @@ -136,16 +135,13 @@ public async Task The_preread_is_physically_readonly_RLS_scoped_and_framework_au await using var host = Fixture.Host(database, probe, configure: services => { observation.Configure(services); - services.AddSingleton(gate); }); - (await gate.IsPermittedAsync("positive-control")).Should().BeTrue(); var claim = (await host.Services.GetRequiredService().TryClaimAsync(job, 1))!; (await host.Services.GetRequiredService().ExecuteAsync(claim, BackgroundJobTestRun.Create())).Outcome.Should().Be(JobStartExecutionOutcome.Started); reads.Should().Be(1); starts.Should().Be(1); observation.ReadScopeDisposed.Should().BeTrue(); observation.StartScopeDisposed.Should().BeTrue(); - gate.Calls.Should().Be(1, "the sticky ceiling refuses privileged scope entry before even a permissive gate"); probe.Constructions.Should().BeEmpty(); } @@ -293,7 +289,7 @@ private static async Task AssertFrameworkCeilingAsync(IServiceProvider services, unit.IsRollbackOnly.Should().BeFalse(); (await Fixture.SendAsync(services)).IsFailure.Should().BeTrue("accessor replacement cannot remove framework confinement"); probe.Constructions.Should().BeEmpty("ordinary handler construction follows admission"); - await FluentActions.Awaiting(() => services.GetRequiredService().EnterAsync("framework-proof")) + await FluentActions.Awaiting(() => services.GetRequiredService().EnterAsync(LearnStack.Tests.Fixtures.TestPlatformAdmissions.Admission())) .Should().ThrowAsync().WithMessage("*background-job authority*"); var privileged = services.GetRequiredKeyedService(OutboxDispatcherDataSource.Key); await FluentActions.Awaiting(async () => await privileged.OpenConnectionAsync()) @@ -311,13 +307,6 @@ private static async Task ProveReadOnlyWriteRefusalAsync(IUnitOfWork unit, Backg await SchemaQueries.ExecuteAsync(unit.Connection, unit.Transaction, "ROLLBACK TO SAVEPOINT readonly_probe"); } - private sealed class PermissiveGate : IPlatformAdminGate - { - internal int Calls { get; private set; } - public ValueTask IsPermittedAsync(string reason, CancellationToken cancellationToken = default) - { Calls++; return ValueTask.FromResult(true); } - } - private sealed class ProvisioningProbe : IProvisionsTenant { public TenantId ProvisioningTenantId => TenantId.From(SchemaFixture.TenantA); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index 98423005..ba52c99a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -12,6 +12,10 @@ using Microsoft.Extensions.Logging; using Npgsql; using Xunit; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using LearnStack.Modules.Tenancy.Infrastructure; +using LearnStack.SharedKernel.Entitlements; namespace LearnStack.Tests.Integration.Database; @@ -64,10 +68,9 @@ public async Task The_Scope_Sees_What_An_Application_Connection_Cannot() await using var platformSource = PlatformSource(_schema.Postgres.PlatformConnectionString); await using var appSource = NpgsqlDataSource.Create(_schema.Postgres.AppConnectionString); - await using var handle = await Build(platformSource).EnterAsync( - "test:cross-tenant-visibility", CancellationToken.None); + await using var handle = await Build(platformSource).EnterAsync(Admission(), CancellationToken.None); - var seenByPlatform = await CountOrganizationsAsync(handle.Connection, handle.Transaction); + var seenByPlatform = await ScalarAsync(handle, "SELECT count(*) FROM organizations"); await using var appConnection = await appSource.OpenConnectionAsync(CancellationToken.None); var seenByApplication = await CountOrganizationsAsync(appConnection, transaction: null); @@ -91,11 +94,10 @@ public async Task The_Scope_Connects_As_The_Platform_Role_On_Its_Own_Connection( var appBackend = await ScalarAsync(appConnection, null, "SELECT pg_backend_pid()"); var appUser = await ScalarAsync(appConnection, null, "SELECT current_user"); - await using var handle = await Build(platformSource).EnterAsync( - "test:provenance", CancellationToken.None); + await using var handle = await Build(platformSource).EnterAsync(Admission(), CancellationToken.None); - var scopeUser = await ScalarAsync(handle.Connection, handle.Transaction, "SELECT current_user"); - var scopeBackend = await ScalarAsync(handle.Connection, handle.Transaction, "SELECT pg_backend_pid()"); + var scopeUser = await ScalarAsync(handle, "SELECT current_user"); + var scopeBackend = await ScalarAsync(handle, "SELECT pg_backend_pid()"); appUser.Should().Be("learnstack_app"); scopeUser.Should().Be("learnstack_platform"); @@ -113,27 +115,17 @@ public async Task Disposing_Without_Committing_Rolls_Back() var scope = Build(dataSource); var host = $"rollback-{Guid.NewGuid():N}.example.com"; - await using (var handle = await scope.EnterAsync( - "test:rollback", CancellationToken.None)) + await using (var handle = await scope.EnterAsync(Admission(), CancellationToken.None)) { - await using var insert = handle.Connection.CreateCommand(); - insert.Transaction = handle.Transaction; - insert.CommandText = - """ - INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) - VALUES (@host, @tenant, true, true) - """; - insert.Parameters.Add(new NpgsqlParameter("host", host)); - insert.Parameters.Add(new NpgsqlParameter("tenant", SchemaFixture.TenantA)); - await insert.ExecuteNonQueryAsync(CancellationToken.None); + await handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); } - await using var check = await scope.EnterAsync( - "test:rollback-check", CancellationToken.None); + await using var check = await scope.EnterAsync(Admission(), CancellationToken.None); var survivors = await ScalarAsync( - check.Connection, - check.Transaction, - "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", + check, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", [("host", (object)host)]); survivors.Should().Be(0, "disposal without a commit rolls the transaction back"); @@ -148,13 +140,12 @@ public async Task Two_Concurrent_Entries_Get_Independent_Connections() await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); var scope = Build(dataSource); - await using var first = await scope.EnterAsync("test:one", CancellationToken.None); - await using var second = await scope.EnterAsync("test:two", CancellationToken.None); + await using var first = await scope.EnterAsync(Admission(), CancellationToken.None); + await using var second = await scope.EnterAsync(Admission(), CancellationToken.None); - first.Connection.Should().NotBeSameAs(second.Connection); - (await ScalarAsync(first.Connection, first.Transaction, "SELECT pg_backend_pid()")) + (await ScalarAsync(first, "SELECT pg_backend_pid()")) .Should().NotBe( - await ScalarAsync(second.Connection, second.Transaction, "SELECT pg_backend_pid()")); + await ScalarAsync(second, "SELECT pg_backend_pid()")); } [Fact] @@ -239,27 +230,33 @@ await _schema.Postgres.ExecuteAsSuperuserAsync( } [Fact] - public async Task A_Resolved_Handle_Cannot_Be_Used_Again() + public async Task A_Resolved_Handle_Cannot_Be_Used_Again_And_Exposes_No_Connection() { - // Measured before the fence existed: after a successful commit the connection is - // still Open, so a plain SELECT on it returned every tenant's rows — in - // autocommit, on a BYPASSRLS credential, with no transaction left to undo - // anything. A write issued there SURVIVED DisposeAsync, which is the exact - // opposite of what this type's contract promises. + // The hazard the facade closes: a connection reference captured before the commit + // would run in autocommit afterwards on a role that sees every tenant. The handle + // therefore has no Connection or Transaction member to capture, refuses every call once + // resolved, and closes the underlying connection at completion (ADR-0101 § 8). + typeof(IPlatformAdminScopeHandle).GetProperties().Select(property => property.PropertyType) + .Should().NotContain(type => typeof(System.Data.Common.DbConnection).IsAssignableFrom(type) + || typeof(System.Data.Common.DbTransaction).IsAssignableFrom(type), + "a raw provider object is exactly what could be captured"); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - await using var handle = await Build(dataSource).EnterAsync( - "test:terminal", CancellationToken.None); + await using var handle = await Build(dataSource).EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(handle, "SELECT pg_backend_pid()")).Should().BeGreaterThan(0); await handle.CommitAsync(CancellationToken.None); - var readConnection = () => handle.Connection; - var readTransaction = () => handle.Transaction; + var execute = async () => await handle.ExecuteAsync("SELECT 1", null, CancellationToken.None); + var query = async () => await ScalarAsync(handle, "SELECT 1"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, null, null, null, null), CancellationToken.None); var commitAgain = async () => await handle.CommitAsync(CancellationToken.None); - readConnection.Should().Throw( - "fencing Transaction alone would leave the autocommit hole open"); - readTransaction.Should().Throw(); - await commitAgain.Should().ThrowAsync(); + await execute.Should().ThrowAsync("a statement after the commit would be an autocommit bypass"); + await query.Should().ThrowAsync(); + await result.Should().ThrowAsync(); + await commitAgain.Should().ThrowAsync(); } [Fact] @@ -274,40 +271,27 @@ public async Task Committing_Persists_And_Disposal_Leaves_It_Alone() try { - await using (var handle = await scope.EnterAsync( - "test:commit", CancellationToken.None)) + await using (var handle = await scope.EnterAsync(Admission(), CancellationToken.None)) { - await using var insert = handle.Connection.CreateCommand(); - insert.Transaction = handle.Transaction; - insert.CommandText = - """ - INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) - VALUES (@host, @tenant, true, true) - """; - insert.Parameters.Add(new NpgsqlParameter("host", host)); - insert.Parameters.Add(new NpgsqlParameter("tenant", SchemaFixture.TenantA)); - await insert.ExecuteNonQueryAsync(CancellationToken.None); + await handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); await handle.CommitAsync(CancellationToken.None); } - await using var check = await scope.EnterAsync("test:check", CancellationToken.None); + await using var check = await scope.EnterAsync(Admission(), CancellationToken.None); (await ScalarAsync( - check.Connection, - check.Transaction, - "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", + check, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", [("host", (object)host)])) .Should().Be(1, "a committed write survives the handle that made it"); } finally { // The schema fixture is shared and other classes assert exact row counts. - await using var cleanup = await scope.EnterAsync("test:cleanup", CancellationToken.None); - await using var delete = cleanup.Connection.CreateCommand(); - delete.Transaction = cleanup.Transaction; - delete.CommandText = "DELETE FROM platform_host_to_tenant WHERE host = @host"; - delete.Parameters.Add(new NpgsqlParameter("host", host)); - await delete.ExecuteNonQueryAsync(CancellationToken.None); + await using var cleanup = await scope.EnterAsync(Admission(), CancellationToken.None); + await cleanup.ExecuteAsync("DELETE FROM platform_host_to_tenant WHERE host = @host", [new PlatformSqlParameter("host", host)], CancellationToken.None); await cleanup.CommitAsync(CancellationToken.None); } } @@ -338,14 +322,12 @@ public async Task A_Faulted_Commit_Returns_The_Connection_And_Is_Left_Indetermin for (var attempt = 0; attempt < 5; attempt++) { - var handle = await scope.EnterAsync("test:faulted", CancellationToken.None); + var handle = await scope.EnterAsync(Admission(), CancellationToken.None); await using (handle) { - await using (var suicide = handle.Connection.CreateCommand()) + var suicide = new Terminator(handle); { - suicide.Transaction = handle.Transaction; - suicide.CommandText = "SELECT pg_terminate_backend(pg_backend_pid())"; try { @@ -368,8 +350,8 @@ await commit.Should().ThrowAsync( // Five entries through a pool of three: without the disposal in a finally, this // line blocks until the pool timeout. - await using var afterwards = await scope.EnterAsync("test:after", CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open); + await using var afterwards = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1); } [Fact] @@ -397,12 +379,10 @@ public async Task An_Abandoned_Handle_On_A_Dead_Connection_Still_Returns_It() for (var attempt = 0; attempt < 5; attempt++) { - var handle = await scope.EnterAsync("test:abandoned", CancellationToken.None); + var handle = await scope.EnterAsync(Admission(), CancellationToken.None); - await using (var suicide = handle.Connection.CreateCommand()) + var suicide = new Terminator(handle); { - suicide.Transaction = handle.Transaction; - suicide.CommandText = "SELECT pg_terminate_backend(pg_backend_pid())"; try { @@ -420,8 +400,8 @@ await dispose.Should().NotThrowAsync( "throwing from disposal replaces whatever the caller was actually failing on"); } - await using var afterwards = await scope.EnterAsync("test:after", CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open, + await using var afterwards = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1, "every abandoned entry returned its connection through the finally"); logger.Entries.Should().Contain(entry => entry.EventId == 7002, @@ -445,13 +425,13 @@ public async Task Entry_Is_Recorded_At_Warning_With_The_Reason_And_The_Caller() var logger = new CapturingLogger(); var scope = Build(dataSource, logger); - await using var handle = await scope.EnterAsync("test:recorded", CancellationToken.None); + await using var handle = await scope.EnterAsync(Admission(), CancellationToken.None); var entry = logger.Entries.Should().ContainSingle(line => line.EventId == 7001).Subject; entry.Level.Should().Be(LogLevel.Warning, "an operator filtering at Information must still see a cross-tenant bypass"); - entry.Message.Should().Contain("test:recorded"); + entry.Message.Should().Contain(PlatformOperations.KillswitchToggle.ReasonSlug); entry.Message.Should().Contain(nameof(Entry_Is_Recorded_At_Warning_With_The_Reason_And_The_Caller), "the calling member is how 'the caller' is known at all with no principal"); // The property, not a substring of one machine's layout. CallerFilePath is the @@ -537,7 +517,8 @@ public async Task Entry_Is_On_The_Record_Before_The_Operation_Runs() // literal repeated here, except the ones that ARE the decision — the sentinel // tenant, the outcome, and the provenance. await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - await using var handle = await Build(dataSource).EnterAsync("test:recorded-row"); + var correlation = $"corr-{Guid.NewGuid():N}"; + await using var handle = await Build(dataSource).EnterAsync(Admission(correlation)); await using var independent = await PostgresFixture.OpenAsync( _schema.Postgres.PlatformConnectionString); @@ -546,7 +527,8 @@ public async Task Entry_Is_On_The_Record_Before_The_Operation_Runs() "SELECT tenant_id, organization_id, module, operation, operation_type, " + "operation_class, outcome, actor_user_id, " + "metadata #>> '{caller,member}', metadata #>> '{caller,file}' " - + "FROM audit_log WHERE reason = 'test:recorded-row'"; + + "FROM audit_log WHERE correlation_id = @correlation"; + read.Parameters.Add(new NpgsqlParameter("correlation", correlation)); await using var reader = await read.ExecuteReaderAsync(); @@ -588,14 +570,14 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin // fails is still recorded. Checked on an independent connection, after the handle // is gone, because that is what durable means. await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - var reason = "test:survives-" + ending; + var correlation = $"corr-{Guid.NewGuid():N}"; var act = async () => { - await using var handle = await Build(dataSource).EnterAsync(reason); + await using var handle = await Build(dataSource).EnterAsync(Admission(correlation)); // Privileged work first, in every ending: the access happened. - (await CountOrganizationsAsync(handle.Connection, handle.Transaction)) + (await ScalarAsync(handle, "SELECT count(*) FROM organizations")) .Should().BeGreaterThanOrEqualTo(0); switch (ending) @@ -621,7 +603,7 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin _schema.Postgres.PlatformConnectionString); var survivors = await ScalarAsync( - afterwards, null, "SELECT count(*) FROM audit_log WHERE reason = @reason", ("reason", reason)); + afterwards, null, "SELECT count(*) FROM audit_log WHERE correlation_id = @correlation", ("correlation", correlation)); survivors.Should().Be(1, "entry into a cross-tenant scope is recorded whatever the work then does"); } @@ -646,16 +628,15 @@ public async Task An_Entry_That_Cannot_Be_Recorded_Is_Not_Entered() for (var attempt = 0; attempt < 5; attempt++) { - var act = async () => await scope.EnterAsync("test:unrecordable", CancellationToken.None); + var act = async () => await scope.EnterAsync(Admission(), CancellationToken.None); await act.Should().ThrowAsync( "a cross-tenant scope that cannot be recorded must not be entered"); } - await using var afterwards = await Build(dataSource).EnterAsync( - "test:after-unrecordable", CancellationToken.None); + await using var afterwards = await Build(dataSource).EnterAsync(Admission(), CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open, + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1, "every refused entry returned its connection through the catch"); } @@ -670,6 +651,288 @@ await act.Should().ThrowAsync( /// swapping that initializer for the application one, which refuses every bypassing /// role, left all six cases green. /// + [Fact] + public async Task A_Result_Row_Commits_With_The_Work_And_Carries_The_Operator_But_Not_The_Ticket_For_A_Tenant() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + var admission = TestPlatformAdmissions.Admission(ticket: "INC-7", correlationId: correlation); + + await using (var handle = await Build(dataSource).EnterAsync(admission)) + { + await handle.WriteResultAsync(new PlatformResult( + TenantId.From(SchemaFixture.TenantA), "PlatformKillswitch", "key-1", "{\"isEnabled\":true}", "{\"isEnabled\":false}")); + await handle.CommitAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Rows(read, correlation); + + rows.Should().HaveCount(2, "the entry row and the result row"); + var entry = rows.Single(row => row.Operation == PlatformAdminScope.EnterOperation); + entry.Tenant.Should().Be(TenantId.PlatformSentinel.Value); + entry.Metadata.Should().Contain("INC-7", "the sentinel row is invisible to every tenant, so it carries the ticket"); + entry.Actor.Should().BeNull("an operator is not a users row"); + + var result = rows.Single(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug); + result.Tenant.Should().Be(SchemaFixture.TenantA, "a tenant-targeted act is recorded under the real tenant"); + result.Reason.Should().Be(PlatformOperations.KillswitchToggle.ReasonSlug); + result.Actor.Should().BeNull(); + using var metadata = System.Text.Json.JsonDocument.Parse(result.Metadata); + var op = metadata.RootElement.GetProperty("operator"); + op.GetProperty("subjectDigest").GetString().Should().Be(admission.Operator.SubjectDigest); + op.GetProperty("kind").GetString().Should().Be("human"); + op.GetProperty("acr").GetString().Should().Be("mfa"); + op.TryGetProperty("ticket", out _).Should().BeFalse( + "a row a tenant administrator can read never carries the operator's ticket"); + result.After.Should().Contain("false"); + } + + [Fact] + public async Task A_Result_Row_Rolls_Back_With_The_Work_While_The_Entry_Stays() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + + await using (var handle = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission(correlationId: correlation))) + { + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, null)); + // Disposed without a commit: the work and its MUST row go together. + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Rows(read, correlation); + + rows.Should().ContainSingle().Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, + "the entry is on the record whatever the work then did, and the result is not"); + } + + [Fact] + public async Task A_Result_Row_That_Cannot_Be_Written_Fails_The_Act_And_Leaves_No_State() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource, NullLogger.Instance, FailingResultStore()); + var key = KillswitchKeys.EmailDispatchEnabled; + var removals = new RecordingCache(); + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var before = await ScalarAsync(read, null, + "SELECT coalesce((SELECT is_enabled::text FROM platform_killswitches WHERE key = @k), 'absent')", ("k", key.Value)); + + var act = async () => await new KillswitchToggle(scope, removals, new SystemClock()) + .ToggleAsync(TestPlatformAdmissions.Admission(), key, before != "false", CancellationToken.None); + + await act.Should().ThrowAsync(); + removals.Removed.Should().Be(0, "nothing committed, so nothing is stale"); + (await ScalarAsync(read, null, + "SELECT coalesce((SELECT is_enabled::text FROM platform_killswitches WHERE key = @k), 'absent')", ("k", key.Value))) + .Should().Be(before, "the state change rolled back with the failed MUST row"); + } + + [Fact] + public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_Drops_The_Cache() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource); + var key = KillswitchKeys.AnalyticsIngestEnabled; + var cache = new RecordingCache(async () => + { + await using var independent = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + return await ScalarAsync(independent, null, + "SELECT is_enabled::text FROM platform_killswitches WHERE key = @k", ("k", key.Value)); + }); + var toggle = new KillswitchToggle(scope, cache, new SystemClock()); + var correlation = $"corr-{Guid.NewGuid():N}"; + + try + { + var off = await toggle.ToggleAsync( + TestPlatformAdmissions.Admission(ticket: "INC-9", correlationId: correlation), key, false); + var back = await toggle.ToggleAsync( + TestPlatformAdmissions.Admission(correlationId: correlation), key, true); + + off.Outcome.Should().Be(KillswitchToggleOutcome.Applied); + (off.Before, off.After).Should().Be((true, false), "no row yet means the registry default"); + (back.Before, back.After).Should().Be((false, true)); + cache.Removed.Should().Be(2, "one removal after each commit"); + cache.Observed.Should().Equal(["false", "true"], + "each removal happens after its commit, so a concurrent reload cannot repopulate the stale value"); + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT is_enabled FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().BeTrue(); + (await ScalarAsync(read, null, + "SELECT count(*) FROM platform_killswitches WHERE key = @k AND toggled_by IS NULL", ("k", key.Value))) + .Should().Be(1, "an operator is not a users row, so toggled_by stays NULL"); + (await Rows(read, correlation)).Count(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug) + .Should().Be(2, "one MUST result row per flip"); + } + finally + { + await using var cleanup = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission()); + await cleanup.ExecuteAsync("DELETE FROM platform_killswitches WHERE key = @k", [new PlatformSqlParameter("k", key.Value)]); + await cleanup.CommitAsync(); + } + } + + [Fact] + public async Task An_Undeclared_Killswitch_Key_Enters_No_Scope_And_Writes_Nothing() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + var cache = new RecordingCache(); + + var result = await new KillswitchToggle(Build(dataSource), cache, new SystemClock()).ToggleAsync( + TestPlatformAdmissions.Admission(correlationId: correlation), new KillswitchKey("killswitch.not.declared"), false); + + result.Outcome.Should().Be(KillswitchToggleOutcome.UnknownKey); + cache.Removed.Should().Be(0); + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await Rows(read, correlation)).Should().BeEmpty("an undeclared key is refused before a cross-tenant scope is entered"); + } + + [Fact] + public async Task A_Result_Row_Cannot_Name_A_Different_Operation_Than_Its_Admission() + { + // The audit seam is witness-bound: a draft for another operation, a non-null actor or a + // missing operator digest is refused, whatever the caller composed. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = TestPlatformAdmissions.Admission(); + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + AuditEntryDraft Draft(string operation, UserId? actor, string metadata) => new() + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = actor, + ActorEmail = null, + ModuleName = "tenancy", + Operation = operation, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = "c", + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = metadata, + }; + + var good = "{\"operator\":{\"subjectDigest\":\"" + admission.Operator.SubjectDigest + "\"}}"; + foreach (var draft in new[] + { + Draft("tenancy.other.operation", null, good), + Draft(admission.Operation.AuditSlug, UserId.From(Guid.CreateVersion7()), good), + Draft(admission.Operation.AuditSlug, null, "{}"), + }) + { + var act = async () => await audit.WritePlatformOperatorResultAsync(draft, admission, connection, transaction); + await act.Should().ThrowAsync(); + } + } + + private static async Task> Rows(System.Data.Common.DbConnection connection, string correlation) + { + await using var command = connection.CreateCommand(); + command.CommandText = + "SELECT tenant_id, operation, reason, actor_user_id, metadata::text, after_state::text " + + "FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id"; + command.Parameters.Add(new NpgsqlParameter("c", correlation)); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new AuditRow( + reader.GetGuid(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? string.Empty : reader.GetString(4), + reader.IsDBNull(5) ? string.Empty : reader.GetString(5))); + } + + return rows; + } + + private sealed record AuditRow(Guid Tenant, string Operation, string? Reason, Guid? Actor, string Metadata, string After); + + private sealed class RecordingCache(Func>? observe = null) : LearnStack.SharedKernel.Caching.ICacheService + { + public int Removed { get; private set; } + + /// What an independent connection saw at the moment of each removal. + public List Observed { get; } = []; + + public async Task RemoveAsync(string key, CancellationToken cancellationToken = default) + { + Removed++; + if (observe is not null) + { + Observed.Add(await observe()); + } + } + + public Task GetAsync(string key, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task GetOrSetAsync( + string key, Func> factory, LearnStack.SharedKernel.Caching.CacheOptions? options = null, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task SetAsync( + string key, T value, LearnStack.SharedKernel.Caching.CacheOptions? options = null, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + } + + private static IServiceScopeFactory FailingResultStore() => + new ServiceCollection() + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// Writes the entry row for real and fails the result row, as an outage between them would. + private sealed class ResultFailingAuditStore : IAuditStore + { + private readonly IAuditStore _inner = AuditStoreScopeFactory().CreateScope().ServiceProvider.GetRequiredService(); + + public Task WritePlatformScopeAsync( + AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + _inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorResultAsync( + AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + throw new AuditWriteFailedException("forced result failure"); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + private static NpgsqlDataSource PlatformSource(string connectionString) => LearnStack.Api.Composition.PersistenceCompositionExtensions .BuildPlatformDataSource(connectionString); @@ -698,8 +961,7 @@ private static PlatformAdminScope Build( NpgsqlDataSource dataSource, ILogger logger, IServiceScopeFactory? auditStore = null) => - new(new PermissiveGate(), - new PrivilegedDataSource(() => dataSource), + new(new PrivilegedDataSource(() => dataSource), new AuditCatalog([new TenancyAuditCatalogSource()]), auditStore ?? AuditStoreScopeFactory(), new SystemClock(), @@ -800,11 +1062,26 @@ private static async Task ScalarAsync( return (T)(await command.ExecuteScalarAsync())!; } - /// Permits entry, so the connection is what the case observes. - private sealed class PermissiveGate : IPlatformAdminGate + private static PlatformAdmission Admission(string? correlation = null) => + correlation is null + ? TestPlatformAdmissions.Admission() + : TestPlatformAdmissions.Admission(correlationId: correlation); + + private static async Task ScalarAsync( + IPlatformAdminScopeHandle handle, string sql, params (string Name, object Value)[] parameters) + { + var rows = await handle.QueryAsync( + sql, + parameters.Select(parameter => new PlatformSqlParameter(parameter.Name, parameter.Value)).ToList(), + reader => (T)reader.GetValue(0), + CancellationToken.None); + return rows[0]; + } + + /// Kills the scope's own backend through the facade, as an operator-side fault would. + private sealed class Terminator(IPlatformAdminScopeHandle handle) { - public ValueTask IsPermittedAsync( - string reason, CancellationToken cancellationToken = default) => - ValueTask.FromResult(true); + public Task ExecuteNonQueryAsync(CancellationToken cancellationToken) => + handle.ExecuteAsync("SELECT pg_terminate_backend(pg_backend_pid())", null, cancellationToken); } } diff --git a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj index 3d19ac15..ad5ae13a 100644 --- a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj +++ b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj @@ -40,6 +40,7 @@ + diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs new file mode 100644 index 00000000..885fb67e --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -0,0 +1,356 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The operator surface through the production Program and the stock bearer handler, with a +/// controlled issuer signing real RS256 tokens (ADR-0101). +/// +/// +/// +/// Protocol refusals are isolated with controlled signed tokens, as the tenant suite does; the +/// real-realm proof is a separate case against pinned Keycloak. The killswitch writer is a +/// recording double here, so these cases decide admission and mapping only and never reach a +/// database; the writer's own transaction semantics are asserted against real PostgreSQL. +/// +/// +/// What a refusal must show is the same in every case: the double was never called, so no +/// privileged connection was acquired, and the answer carries no detail a probing caller could use. +/// +/// +[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", + Justification = "xUnit disposes the fields through IAsyncLifetime.DisposeAsync.")] +public sealed class PlatformOperatorHttpTests : IAsyncLifetime +{ + private const string Path = "/api/platform/v1/killswitches/killswitch.classroom.recording"; + private const string Subject = "operator-sub-1"; + + private TenantAuthenticationIssuer _tenant = null!; + private TenantAuthenticationIssuer _operator = null!; + private PlatformOperatorApiFactory _factory = null!; + private RecordingToggle _toggle = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + _tenant = await TenantAuthenticationIssuer.StartAsync(); + _operator = await TenantAuthenticationIssuer.StartAsync(); + _toggle = new RecordingToggle(); + _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject); + _client = _factory.CreateClient(); + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _factory.DisposeAsync(); + await _operator.DisposeAsync(); + await _tenant.DisposeAsync(); + } + + [Fact] + public async Task A_Valid_Operator_With_The_Grant_Toggles_And_The_Admission_Carries_Them() + { + var response = await Put(Valid(), """{"enabled":false,"ticket":"INC-42"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + var body = await response.Content.ReadFromJsonAsync(); + body.GetProperty("key").GetString().Should().Be("killswitch.classroom.recording"); + body.GetProperty("after").GetBoolean().Should().BeFalse(); + _toggle.Calls.Should().ContainSingle(); + var admission = _toggle.Calls[0]; + admission.Operator.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_operator.Issuer, Subject)); + admission.Operator.Issuer.Should().Be(_operator.Issuer); + admission.Operator.Acr.Should().Be("mfa"); + admission.Ticket.Should().Be("INC-42"); + admission.Operation.Should().BeSameAs(PlatformOperations.KillswitchToggle); + } + + [Fact] + public async Task No_Credential_Is_Refused_Without_Detail() + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Content = JsonContent.Create(new { enabled = false }), + }; + + var response = await _client.SendAsync(request); + + await AssertUnauthorized(response); + } + + [Theory] + [InlineData("audience")] + [InlineData("azp")] + [InlineData("acr")] + [InlineData("acr-missing")] + [InlineData("auth-time-old")] + [InlineData("auth-time-missing")] + [InlineData("auth-time-future")] + [InlineData("lifetime")] + [InlineData("expired")] + [InlineData("subject-missing")] + public async Task A_Wrongly_Profiled_Token_Is_Refused_And_Nothing_Is_Called(string defect) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var token = defect switch + { + "audience" => Sign(("aud", "learnstack-api")), + "azp" => Sign(("azp", "learnstack-web")), + "acr" => Sign(("acr", "0")), + "acr-missing" => SignWithout("acr"), + "auth-time-old" => Sign(("auth_time", now - 3600)), + "auth-time-missing" => SignWithout("auth_time"), + "auth-time-future" => Sign(("auth_time", now + 600)), + "lifetime" => Sign(("iat", now - 5), ("exp", now + 3600)), + "expired" => Sign(("iat", now - 7200), ("exp", now - 3600)), + _ => SignWithout("sub"), + }; + + var response = await Put(token, """{"enabled":false}"""); + + await AssertUnauthorized(response); + _toggle.Calls.Should().BeEmpty("a refused credential reaches no operator service"); + } + + [Fact] + public async Task A_Tenant_Realm_Token_Is_Refused_On_The_Operator_Surface() + { + // Signed by the tenant issuer with the tenant audience and client: the operator scheme + // validates its own pinned issuer and audience, so it cannot be admitted here. + var tenantToken = _tenant.Token(_tenant.Payload()); + + var response = await Put(tenantToken, """{"enabled":false}"""); + + await AssertUnauthorized(response); + _toggle.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task An_Authenticated_Operator_Without_The_Grant_Is_Forbidden_And_Nothing_Is_Called() + { + var response = await Put(Sign(("sub", "someone-else")), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _toggle.Calls.Should().BeEmpty("admission is refused before any operator service, so before any bypass connection"); + } + + [Theory] + [InlineData("has space")] + [InlineData("semi;colon")] + [InlineData("this-ticket-is-far-too-long-to-be-a-ticket-reference-it-exceeds-sixty-four")] + public async Task A_Malformed_Ticket_Is_A_Validation_Failure_Not_A_Permission_One(string ticket) + { + var response = await Put(Valid(), JsonSerializer.Serialize(new { enabled = false, ticket })); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + await AssertProblem(response, "validation_failed"); + _toggle.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"ticket":"INC-1"}""")] + [InlineData("""{"enabled":null}""")] + public async Task A_Body_Without_The_State_Is_A_Validation_Failure(string body) + { + var response = await Put(Valid(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _toggle.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task An_Unknown_Killswitch_Key_Is_Not_Found() + { + _toggle.Outcome = KillswitchToggleOutcome.UnknownKey; + + var response = await Put(Valid(), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task A_Failed_Audit_Write_Is_A_Retryable_503_Not_A_Success() + { + _toggle.Failure = new AuditWriteFailedException("forced"); + + var response = await Put(Valid(), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + await AssertProblem(response, "audit_unavailable"); + } + + [Fact] + public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Document_Does_Not_Carry_It() + { + var operatorDocument = await _client.GetStringAsync("/openapi/platform-v1.json"); + var tenantDocument = await _client.GetStringAsync("/openapi/v1.json"); + + operatorDocument.Should().Contain("/api/platform/v1/killswitches/{key}"); + tenantDocument.Should().NotContain("/api/platform", "the tenant contract is pinned and untouched (ADR-0101 § 4)"); + } + + [Fact] + public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() + { + await using var absent = new PlatformOperatorApiFactory(_tenant, _operator, new RecordingToggle(), configured: false); + using var client = absent.CreateClient(); + + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = JsonContent.Create(new { enabled = false }), + }; + var response = await client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound, "no issuer means no operator route"); + (await client.GetAsync("/openapi/platform-v1.json")).StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_Stays_The_Only_One_Without_An_Issuer() + { + var withIssuer = await _factory.Services.GetRequiredService() + .GetAllSchemesAsync(); + withIssuer.Select(scheme => scheme.Name).Should().BeEquivalentTo([TenantAuthenticationRegistration.Scheme, "PlatformOperator"]); + (await _factory.Services.GetRequiredService() + .GetDefaultAuthenticateSchemeAsync())!.Name.Should().Be(TenantAuthenticationRegistration.Scheme, + "the tenant scheme stays the default and the only scheme on /api/v1 (ADR-0064 Amendment 9)"); + + await using var absent = new PlatformOperatorApiFactory(_tenant, _operator, new RecordingToggle(), configured: false); + (await absent.Services.GetRequiredService() + .GetAllSchemesAsync()).Select(scheme => scheme.Name).Should().Equal(TenantAuthenticationRegistration.Scheme); + } + + [Fact] + public void The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_Its_Prefix() + { + // The tenant surface census excludes this surface by exact type (it has its own scheme), so + // its population is closed here instead: every routed endpoint under /api/platform, its verb, + // and the policy that guards it. A second endpoint, another verb or a missing policy fails. + var endpoints = _factory.Services.GetServices() + .SelectMany(source => source.Endpoints).OfType() + .Where(endpoint => endpoint.RoutePattern.RawText!.StartsWith("/api/platform", StringComparison.Ordinal)) + .ToList(); + + var only = endpoints.Should().ContainSingle().Subject; + only.RoutePattern.RawText.Should().Be("/api/platform/v1/killswitches/{key}"); + only.Metadata.GetMetadata()!.HttpMethods.Should().Equal("PUT"); + only.Metadata.GetOrderedMetadata() + .Select(data => data.Policy).Should().Contain(PlatformOperatorAuthentication.PolicyName, + "an operator endpoint without the authenticated-operator policy would admit an anonymous caller"); + only.Metadata.GetMetadata().Should().BeNull(); + } + + private string Valid() => Sign(); + + private string Sign(params (string Name, object? Value)[] replacements) => _operator.Token(Payload(replacements)); + + private string SignWithout(string name) + { + using var baseline = JsonDocument.Parse(Payload([])); + return _operator.Token("{" + string.Join(",", baseline.RootElement.EnumerateObject() + .Where(property => property.Name != name) + .Select(property => JsonSerializer.Serialize(property.Name) + ":" + property.Value.GetRawText())) + "}"); + } + + private string Payload((string Name, object? Value)[] replacements) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = _operator.Issuer, + ["sub"] = Subject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) + { + claims[name] = value; + } + + return JsonSerializer.Serialize(claims); + } + + private async Task Put(string token, string json) + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + token } }, + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"), + }; + return await _client.SendAsync(request); + } + + private static async Task AssertUnauthorized(HttpResponseMessage response) + { + var diagnostics = response.Headers + await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, diagnostics); + response.Headers.WwwAuthenticate.Should().ContainSingle(diagnostics).Which.Scheme.Should().Be("Bearer"); + await AssertProblem(response, "unauthorized"); + } + + private static async Task AssertProblem(HttpResponseMessage response, string code) + { + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain($"\"code\":\"{code}\""); + } + + private sealed class RecordingToggle : IKillswitchToggle + { + public List Calls { get; } = []; + public KillswitchToggleOutcome Outcome { get; set; } = KillswitchToggleOutcome.Applied; + public Exception? Failure { get; set; } + + public Task ToggleAsync( + PlatformAdmission admission, KillswitchKey key, bool enabled, CancellationToken cancellationToken = default) + { + Calls.Add(admission); + return Failure is not null + ? Task.FromException(Failure) + : Task.FromResult(new KillswitchToggleResult(Outcome, key, true, enabled)); + } + } + + private sealed class PlatformOperatorApiFactory( + TenantAuthenticationIssuer tenant, + TenantAuthenticationIssuer @operator, + IKillswitchToggle toggle, + string grantSubject = Subject, + bool configured = true) : ConstructionOnlyApiFactory + { + protected override void ConfigureTestHost(IWebHostBuilder builder) + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting(TenantAuthenticationOptions.IssuerConfigurationKey, tenant.Issuer); + if (configured) + { + builder.UseSetting("PlatformOperator:Issuer", @operator.Issuer); + builder.UseSetting("PlatformOperator:AcceptedAcr:0", "mfa"); + builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); + builder.UseSetting("PlatformOperator:Grants:0:Subject", grantSubject); + builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", PlatformPermissions.KillswitchWrite.Key); + } + + builder.ConfigureTestServices(services => services.AddScoped(_ => toggle)); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs index 034b7802..ac37d1db 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs @@ -27,6 +27,7 @@ public sealed partial class KeycloakFixture : IAsyncLifetime, IAsyncDisposable private readonly string _adminPassword = Guid.NewGuid().ToString("N"); private readonly string _databasePassword = Guid.NewGuid().ToString("N"); private readonly string? _tenantRealmJson; + private readonly string? _hubRealmJson; private INetwork? _network; private PostgreSqlContainer? _database; private IContainer? _keycloak; @@ -36,7 +37,11 @@ public sealed partial class KeycloakFixture : IAsyncLifetime, IAsyncDisposable private bool _callbackTrust = true; public KeycloakFixture() { } - private KeycloakFixture(string? tenantRealmJson) => _tenantRealmJson = tenantRealmJson; + private KeycloakFixture(string? tenantRealmJson, string? hubRealmJson = null) + { + _tenantRealmJson = tenantRealmJson; + _hubRealmJson = hubRealmJson; + } internal Uri BaseAddress { get; private set; } = null!; // Set only after successful container startup. internal string Issuer => IssuerFor("learnstack"); @@ -50,9 +55,10 @@ internal static string CheckedRealm(string realm) => realm is "learnstack" or "l internal string CallbackCertificate => Encoding.ASCII.GetString(_tls!.CallbackCertificatePem); internal string CallbackPrivateKey => Encoding.ASCII.GetString(_tls!.CallbackPrivateKeyPem); - internal static async Task StartAsync(string? tenantRealmJson = null, bool callbackTrust = true) + internal static async Task StartAsync( + string? tenantRealmJson = null, bool callbackTrust = true, string? hubRealmJson = null) { - var fixture = new KeycloakFixture(tenantRealmJson) { _callbackTrust = callbackTrust }; + var fixture = new KeycloakFixture(tenantRealmJson, hubRealmJson) { _callbackTrust = callbackTrust }; await fixture.InitializeAsync(); return fixture; } @@ -98,7 +104,9 @@ public async Task InitializeAsync() diagnostics.Mark(stage); var tenantImport = _tenantRealmJson ?? await File.ReadAllTextAsync(RealmPath("learnstack"), startup.Token); tenantImport = ConfigureInvitationMailRealm(tenantImport); - var hubImport = await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token); + var hubImport = _hubRealmJson is null + ? await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token) + : Encoding.UTF8.GetBytes(_hubRealmJson); _keycloak = BuildProvider(tenantImport, hubImport, _callbackTrust); _keycloak.Created += (_, _) => { stage = "provider_created"; diagnostics.Mark(stage); }; _keycloak.Starting += (_, _) => { stage = "provider_starting"; diagnostics.Mark(stage); }; @@ -197,7 +205,9 @@ internal async Task RecreateWithCallbackTrustAsync() using var startup = new CancellationTokenSource(TimeSpan.FromMinutes(2)); var tenantImport = _tenantRealmJson ?? await File.ReadAllTextAsync(RealmPath("learnstack"), startup.Token); tenantImport = ConfigureInvitationMailRealm(tenantImport); - var hubImport = await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token); + var hubImport = _hubRealmJson is null + ? await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token) + : Encoding.UTF8.GetBytes(_hubRealmJson); await _keycloak.DisposeAsync(); _keycloak = null; _keycloak = BuildProvider(tenantImport, hubImport, callbackTrust: true, publicPort); @@ -314,7 +324,7 @@ internal async Task WriteReconciliationInputAsync(Stream destination, string sce internal static string RealmPath(string realm) => Path.Combine(RepositoryRoot(), "infra", "keycloak", "realms", realm + ".json"); - private static string RepositoryRoot() + internal static string RepositoryRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory); while (directory is not null && !(File.Exists(Path.Combine(directory.FullName, "CLAUDE.md")) diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs new file mode 100644 index 00000000..6c4b9335 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs @@ -0,0 +1,186 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Hosting; +using LearnStack.Tests.Integration.Database; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.JsonWebTokens; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// What the pinned learnstack-hub realm actually issues to an operator, judged by the +/// same token profile the scheme and the rebind tool use (ADR-0101 § 2, § 3). +/// +/// +/// +/// A controlled issuer isolates protocol refusals in ; this +/// is the other half: the realm export, as shipped, emits an audience, a client, an acr +/// that shows the second factor, an auth_time and a lifetime inside the cap. A realm that +/// stopped doing any of these would pass every controlled-token case and fail here. +/// +/// +/// The shipped demo user must set up OTP at its first login, which a headless fixture cannot do, +/// so this case imports the same realm with that one user holding a known OTP credential. +/// Everything else is the file under infra/keycloak/realms. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class PlatformOperatorRealmTests : IAsyncLifetime +{ + private const string OtpSecret = "JBSWY3DPEHPK3PXP"; + private const string Redirect = "http://127.0.0.1:8765/callback"; + private const string OperatorClient = "learnstack-operator"; + + private KeycloakFixture _keycloak = null!; + + public async Task InitializeAsync() + { + var realm = JsonNode.Parse(await File.ReadAllTextAsync(KeycloakFixture.RealmPath("learnstack-hub")))!.AsObject(); + var user = realm["users"]!.AsArray()[0]!.AsObject(); + user["requiredActions"] = new JsonArray(); + user["credentials"]!.AsArray().Add(new JsonObject + { + ["type"] = "otp", + ["userLabel"] = "fixture", + ["secretData"] = JsonSerializer.Serialize(new { value = OtpSecret }), + ["credentialData"] = JsonSerializer.Serialize(new + { + subType = "totp", + digits = 6, + period = 30, + algorithm = "HmacSHA1", + secretEncoding = "BASE32", + }), + }); + _keycloak = await KeycloakFixture.StartAsync(hubRealmJson: realm.ToJsonString()); + } + + public async Task DisposeAsync() => await _keycloak.DisposeAsync(); + + [Fact] + public async Task The_Operator_Client_Issues_A_Token_That_Meets_The_Operator_Profile() + { + var token = await OperatorTokenAsync(); + + token.Issuer.Should().Be(_keycloak.IssuerFor("learnstack-hub")); + token.Audiences.Should().Contain("learnstack-platform"); + token.GetPayloadValue("azp").Should().Be(OperatorClient); + token.Subject.Should().Be(LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGrantOptions.DemoOperatorSubject, + "the export pins the demo operator's subject so a Development grant can name it"); + (new DateTimeOffset(token.ValidTo, TimeSpan.Zero) - DateTimeOffset.FromUnixTimeSeconds(token.GetPayloadValue("iat"))) + .Should().BeLessThanOrEqualTo(TimeSpan.FromMinutes(15), "the realm caps the operator client's access token"); + + var settings = Settings(token.GetPayloadValue("acr")); + PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, null, out var witness) + .Should().BeTrue("the token the realm issues is the token the scheme accepts"); + witness!.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_keycloak.IssuerFor("learnstack-hub"), token.Subject)); + } + + [Fact] + public async Task The_Acr_Shows_The_Second_Factor_And_The_Shipped_Development_Config_Accepts_It() + { + var token = await OperatorTokenAsync(); + var acr = token.GetPayloadValue("acr"); + + var development = JsonDocument.Parse(await File.ReadAllTextAsync( + Path.Combine(KeycloakFixture.RepositoryRoot(), "backend", "src", "LearnStack.Api", "appsettings.Development.json"))); + var accepted = development.RootElement.GetProperty("PlatformOperator").GetProperty("AcceptedAcr") + .EnumerateArray().Select(value => value.GetString()).ToList(); + + accepted.Should().Contain(acr, "Development configuration accepts exactly what the realm emits for MFA"); + token.TryGetPayloadValue("auth_time", out _).Should().BeTrue(); + } + + [Fact] + public async Task A_Token_From_The_Portal_Client_Does_Not_Meet_The_Operator_Profile() + { + // The Hub portal client shares the realm and the user, but not the audience, the + // client allow-list or the step-up: it is not an operator credential for LearnStack. + using var browser = _keycloak.Browser("learnstack-hub"); + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, "http://localhost:3100/callback", + clientId: "learnstack-hub-web", otpCode: () => Task.FromResult(Totp())); + authorization.Authorized.Should().BeTrue(); + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + + var token = new JsonWebToken(exchange.AccessToken); + + token.Audiences.Should().NotContain("learnstack-platform"); + PlatformOperatorTokenProfile.TryRead(token, Settings("mfa", "2", "1"), DateTimeOffset.UtcNow, null, out _) + .Should().BeFalse("a portal token carries neither the operator client nor the platform audience"); + } + + private async Task OperatorTokenAsync() + { + using var browser = _keycloak.Browser("learnstack-hub"); + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, Redirect, + clientId: OperatorClient, scope: "openid", otpCode: () => Task.FromResult(Totp())); + authorization.Authorized.Should().BeTrue("password, then the one-time password, completes the step-up"); + authorization.MfaChallenged.Should().BeTrue("the operator flow asks for the second factor on every login"); + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + return new JsonWebToken(exchange.AccessToken); + } + + private PlatformOperatorSettings Settings(params string[] acr) + { + var values = new Dictionary + { + ["PlatformOperator:Issuer"] = _keycloak.IssuerFor("learnstack-hub"), + ["PlatformOperator:AuthorizedParties:0"] = OperatorClient, + }; + for (var index = 0; index < acr.Length; index++) + { + values[$"PlatformOperator:AcceptedAcr:{index}"] = acr[index]; + } + + return PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(values).Build(), DeploymentMode.Development)!; + } + + /// RFC 6238, HMAC-SHA1, six digits, thirty seconds; the realm accepts one step either side. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", + Justification = "RFC 6238 TOTP is defined over HMAC-SHA1; this generates the fixture user's one-time code.")] + private static string Totp() + { + var key = Base32(OtpSecret); + var counter = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30; + var message = BitConverter.GetBytes(counter); + if (BitConverter.IsLittleEndian) + { + Array.Reverse(message); + } + + var hash = HMACSHA1.HashData(key, message); + var offset = hash[^1] & 0x0F; + var binary = ((hash[offset] & 0x7F) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; + return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); + } + + private static byte[] Base32(string value) + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + var bytes = new List(); + var buffer = 0; + var bits = 0; + foreach (var character in value.TrimEnd('=')) + { + buffer = (buffer << 5) | alphabet.IndexOf(character, StringComparison.Ordinal); + bits += 5; + if (bits >= 8) + { + bytes.Add((byte)(buffer >> (bits - 8))); + bits -= 8; + } + } + + return [.. bytes]; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs b/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs index 00739bd7..512ec609 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs @@ -25,6 +25,7 @@ internal static class TenantAuthenticationPipelineProof private static readonly Dictionary HelperLeaves = new(StringComparer.Ordinal) { ["MapLearnStackOpenApi"] = [], + ["MapLearnStackPlatformOperator"] = [], ["UseLearnStackPublicResponsePolicy"] = ["Use"], ["MapLearnStackClientErrors"] = ["UseStatusCodePages"], ["UseLearnStackCorrelationHeader"] = ["UseMiddleware"], @@ -222,7 +223,7 @@ IEnumerable Expand(SyntaxNode body, string receiver, HashSet -/// What stands between a caller and a BYPASSRLS connection. +/// What stands between an operator and a BYPASSRLS connection (ADR-0101). /// /// -/// No Docker: every case here is refused before a connection is opened, which is the -/// property under test. The Lazy throws if forced, so a case that completes at all -/// is a case where nothing reached the credential. +/// No Docker: every case here is decided before a connection is opened, which is the property +/// under test. The data source throws if forced, so a case that completes is a case where +/// nothing reached the credential. /// public sealed class PlatformAdminGateTests { + private static readonly string Digest = PlatformOperatorSubject.Digest(TestPlatformAdmissions.Issuer, "operator-1"); + [Fact] - public async Task The_Registered_Gate_Permits_Nobody() + public async Task An_Operator_Holding_The_Grant_Is_Admitted_For_The_Operation() { - // Nothing else instantiates this type, so without this the only gate behaviour - // the corpus exhibits is the permissive double the Docker suite uses. Its own doc - // says it exists so nobody makes the default permissive to unblock a demo; this - // is the line that would notice. - var gate = new DenyAllPlatformAdminGate(); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); - (await gate.IsPermittedAsync("anything", CancellationToken.None)).Should().BeFalse(); - (await gate.IsPermittedAsync("gdpr-redaction:some-user", CancellationToken.None)) - .Should().BeFalse("a plausible reason is not a permission"); + var result = await gate.AdmitAsync( + TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, "INC-1", CancellationToken.None); + + result.IsAdmitted.Should().BeTrue(); + result.Admission!.Operation.Should().BeSameAs(PlatformOperations.KillswitchToggle); + result.Admission.Ticket.Should().Be("INC-1"); + result.Admission.Operator.SubjectDigest.Should().Be(Digest); } [Fact] - public async Task Entry_Is_Refused_Before_The_Credential_Is_Touched() + public async Task An_Operator_Without_The_Grant_Is_Refused_Even_With_A_Valid_Witness() { - // ADR-0036 asks for the permission to be "checked before the scope opens". A - // check after the connection exists would already have spent a BYPASSRLS - // connection on a caller who was never allowed one — and, in a deployment with no - // platform credential at all, would report the wrong failure entirely. - var scope = Build(new DenyAllPlatformAdminGate(), out var dataSource); + var gate = Gate(Grants("someone-else", PlatformPermissions.KillswitchWrite.Key)); - var act = async () => await scope.EnterAsync("test:denied", CancellationToken.None); + var result = await gate.AdmitAsync( + TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null, CancellationToken.None); - await act.Should().ThrowAsync(); - dataSource.IsValueCreated.Should().BeFalse("the gate runs before the credential"); + result.IsAdmitted.Should().BeFalse(); + result.Refusal.Should().Be(PlatformRefusal.MissingPermission); } [Fact] - public async Task Ordinary_job_is_refused_even_by_a_permissive_platform_gate_before_credential_resolution() + public async Task A_Grant_For_Another_Permission_Does_Not_Admit() { - var fixture = new BackgroundJobExecutionAdmissionTests.Fixture(); - var gate = new PermissiveGate(); - var scope = Build(gate, out var source); - using var admission = fixture.Enter(); - var enter = async () => await scope.EnterAsync("test:ordinary-job"); - await enter.Should().ThrowAsync().WithMessage("*Ordinary background-job*"); - source.IsValueCreated.Should().BeFalse(); - gate.Calls.Should().Be(0, "ordinary admission refuses before the permissive platform gate"); + // The grant is the permission, matched exactly: a different Platform key, or a prefix + // of the right one, is not the key. + var gate = Gate(Grants("operator-1", "platform.killswitch")); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission); } [Theory] [InlineData("")] - [InlineData(" ")] - [InlineData(null)] - public async Task A_Blank_Reason_Is_Refused_Before_Anything_Else(string? reason) + [InlineData("has space")] + [InlineData("semi;colon")] + [InlineData("this-ticket-is-far-too-long-to-be-a-ticket-reference-it-exceeds-sixty-four")] + public async Task A_Malformed_Ticket_Is_Refused_Before_The_Grant_Is_Read(string ticket) + { + var grants = Grants("operator-1", PlatformPermissions.KillswitchWrite.Key); + var gate = Gate(grants); + + var result = await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket); + + result.Refusal.Should().Be(PlatformRefusal.InvalidTicket); + grants.Reads.Should().Be(0, "the ticket grammar is checked before any grant is evaluated"); + } + + [Fact] + public async Task An_Unregistered_Operation_Is_Refused() { - // The reason is the value Packet 9 writes durably, and a blank one makes the - // record of a cross-tenant access say nothing about why it happened. Refused - // ahead of the gate so the failure names the caller's own mistake rather than a - // permission they may well hold. - var scope = Build(new PermissiveGate(), out var dataSource); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); - var act = async () => await scope.EnterAsync(reason!, CancellationToken.None); + // A lookalike is not the registered instance, however identical its content. + var lookalike = typeof(PlatformOperation).GetConstructors( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true]); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), (PlatformOperation)lookalike, null)) + .Refusal.Should().Be(PlatformRefusal.UnknownOperation); + } + + [Fact] + public async Task A_Missing_Witness_Is_Refused() + { + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); + + (await gate.AdmitAsync(null!, PlatformOperations.KillswitchToggle, null)) + .Refusal.Should().Be(PlatformRefusal.InvalidWitness); + } + + [Fact] + public async Task Entry_With_An_Unregistered_Operation_Never_Touches_The_Credential() + { + // The scope also refuses a registered operation that does not use the platform role, + // but the registry holds none yet, so that second guard cannot be driven until a + // packet registers one (P03-9 Step 2 adds the first) and is exercised there. + var scope = Build(out var dataSource); + var lookalike = typeof(PlatformOperation).GetConstructors( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true]); + + var act = async () => await scope.EnterAsync( + TestPlatformAdmissions.Admission((PlatformOperation)lookalike), CancellationToken.None); await act.Should().ThrowAsync(); dataSource.IsValueCreated.Should().BeFalse(); } + [Fact] + public async Task Ordinary_job_is_refused_before_credential_resolution() + { + var fixture = new BackgroundJobExecutionAdmissionTests.Fixture(); + var scope = Build(out var source); + using var admission = fixture.Enter(); + + var enter = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission()); + + await enter.Should().ThrowAsync().WithMessage("*Ordinary background-job*"); + source.IsValueCreated.Should().BeFalse(); + } + [Fact] public async Task A_Permitted_Caller_Reaches_The_Credential_And_Fails_There_When_It_Is_Absent() { - // The other side of the ordering: with the gate open, the next thing that can go - // wrong is the credential, and it must surface as the credential rather than as - // anything else. - var scope = Build(new PermissiveGate(), out var dataSource); - - var act = async () => await scope.EnterAsync("test:permitted", CancellationToken.None); - - // InvalidOperationException and not PlatformAdminScopeDeniedException — the two - // are unrelated types, so this assertion already distinguishes "refused entry" - // from "entry allowed, credential missing". - // The exception's TYPE is the evidence, not IsValueCreated: when a Lazy factory - // throws, Lazy caches the failure and leaves IsValueCreated false — measured. - // So "reached the credential" is shown by the failure being the credential's, - // which is exactly what distinguishes it from the refusal above. - // The TYPE, not the message. The Lazy under test is built by this file, so an - // assertion on its text would be matching the double rather than production - // code; the production message is covered where it is produced, in + var scope = Build(out var dataSource); + + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); + + // The TYPE, not the message: the Lazy under test is built by this file, so an assertion + // on its text would match the double. Production's message is covered in // PlatformAdminScopeTests.An_Absent_Credential_Names_The_Key_Rather_Than_Degrading. await act.Should().ThrowAsync(); - dataSource.IsValueCreated.Should().BeFalse( - "a Lazy whose factory threw never records a created value"); + dataSource.IsValueCreated.Should().BeFalse("a Lazy whose factory threw never records a value"); } [Fact] public async Task An_Operation_The_Catalogue_Does_Not_Declare_Never_Opens_A_Connection() { - // Third in the ordering, and it belongs before the credential rather than after - // the connection: a deployment whose catalogue lost the slug must not spend a - // BYPASSRLS connection discovering that it cannot record the entry. Fail-closed - // is the whole posture — an entry nothing can record is an entry that does not - // happen (ADR-0044 § 10). - var scope = Build(new PermissiveGate(), out var dataSource, new AuditCatalog([])); + // A deployment whose catalogue lost a slug must not spend a BYPASSRLS connection + // discovering that it cannot record the entry (ADR-0044 § 10). + var scope = Build(out var dataSource, new AuditCatalog([])); - var act = async () => await scope.EnterAsync("test:unclassified", CancellationToken.None); + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); (await act.Should().ThrowAsync()) .Which.Message.Should().Contain(PlatformAdminScope.EnterOperation); + dataSource.IsValueCreated.Should().BeFalse("the refusal precedes the credential"); + } + + [Fact] + public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() + { + var catalogue = new AuditCatalog([new TenancyAuditCatalogSource()]); + + catalogue.TryGetOffPath(PlatformAdminScope.EnterOperation, out var entry).Should().BeTrue(); + entry.OperationClass.Should().Be(OperationClass.Must); + entry.OperationType.Should().Be(OperationType.SecurityEvent); + entry.ModuleName.Should().Be("platform", "the scope belongs to no module's request path"); + + foreach (var operation in PlatformOperations.All) + { + catalogue.TryGetOffPath(operation.AuditSlug, out var declared) + .Should().BeTrue($"'{operation.AuditSlug}' must be declared so its result row can be recorded"); + declared.OperationClass.Should().Be(OperationClass.Must); + } + } + + [Fact] + public void The_Registry_Is_Closed_And_Every_Operation_Names_A_Registered_Platform_Permission() + { + PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.AuditSlug); + PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.ReasonSlug); + foreach (var operation in PlatformOperations.All) + { + PlatformPermissions.TryGet(operation.Permission.Key, out var registered).Should().BeTrue(); + registered.Should().BeSameAs(operation.Permission); + operation.Permission.Scope.Should().Be(LearnStack.SharedKernel.Permissions.PermissionScope.Platform); + } + } - dataSource.IsValueCreated.Should().BeFalse( - "the refusal precedes the credential, so no connection is spent on it"); + [Fact] + public void The_Grant_Validator_Refuses_Unregistered_Keys_And_The_Demo_Operator_Outside_Development() + { + var options = new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }; + options.Grants.Add(new PlatformOperatorGrant { Subject = "operator-1", Permissions = { "platform.tenant.write" } }); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.Development).Validate(null, options).Failed.Should().BeTrue( + "a key no operation has registered is not a grant"); + + var demo = new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }; + demo.Grants.Add(new PlatformOperatorGrant + { + Subject = PlatformOperatorGrantOptions.DemoOperatorSubject, + Permissions = { PlatformPermissions.KillswitchWrite.Key }, + }); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.Development).Validate(null, demo).Succeeded.Should().BeTrue(); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.SaaS).Validate(null, demo).Failed.Should().BeTrue( + "the exported demo operator may hold a grant in Development only"); } [Fact] - public void The_Shipped_Tenancy_Source_Declares_The_Slug_The_Scope_Enters_On() + public async Task The_Configuration_Source_Matches_The_Digest_And_Fails_Closed_Without_An_Issuer() { - // The other half of the case above, and the reason it uses an empty catalogue - // rather than a fake that declares the slug: something has to assert that the - // shipped source really does. Both together fail if the declaration is removed. - new AuditCatalog([new TenancyAuditCatalogSource()]) - .TryGetOffPath(PlatformAdminScope.EnterOperation, out var declared) - .Should().BeTrue(); + var withIssuer = Source(new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + (await withIssuer.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeTrue(); + (await withIssuer.IsGrantedAsync(PlatformOperatorSubject.Digest("https://other/", "operator-1"), PlatformPermissions.KillswitchWrite.Key)) + .Should().BeFalse("the same subject at another issuer is another operator"); - declared.OperationClass.Should().Be(OperationClass.Must); - declared.OperationType.Should().Be(OperationType.SecurityEvent); - declared.ModuleName.Should().Be("platform", - "the scope belongs to no module\'s request path, whatever source declares it"); + var noIssuer = Source(new PlatformOperatorGrantOptions + { + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + (await noIssuer.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeFalse(); } - private static PlatformAdminScope Build( - IPlatformAdminGate gate, - out PrivilegedDataSource dataSource, - IAuditCatalog? catalog = null) + private static PlatformOperatorGate Gate(IPlatformOperatorGrantSource grants) => + new(grants, NullLogger.Instance); + + private static CountingGrants Grants(string subject, params string[] keys) => + new(TestPlatformAdmissions.Issuer, subject, keys); + + private static ConfigurationPlatformOperatorGrantSource Source(PlatformOperatorGrantOptions options) => + new(new FixedMonitor(options), NullLogger.Instance); + + private static PlatformAdminScope Build(out PrivilegedDataSource dataSource, IAuditCatalog? catalog = null) { dataSource = new PrivilegedDataSource(() => throw new InvalidOperationException( "ConnectionStrings:PlatformAdmin is not configured in this test.")); - // The catalogue is real and built from the shipped Tenancy source, because the - // lookup now sits between the gate and the credential: a fake declaring the slug - // would let this file pass while the source that has to declare it did not. - // Nothing here reaches the store — the credential throws first — so the scope - // factory is an empty provider's. + // The catalogue is real and built from the shipped Tenancy source, so a fake declaring + // the slugs cannot let this file pass while the source that must declare them did not. return new PlatformAdminScope( - gate, dataSource, catalog ?? new AuditCatalog([new TenancyAuditCatalogSource()]), new ServiceCollection().BuildServiceProvider().GetRequiredService(), @@ -169,13 +259,22 @@ private static PlatformAdminScope Build( NullLogger.Instance); } - private sealed class PermissiveGate : IPlatformAdminGate + private sealed class CountingGrants(string issuer, string subject, string[] keys) : IPlatformOperatorGrantSource { - public int Calls { get; private set; } - public ValueTask IsPermittedAsync(string reason, CancellationToken cancellationToken = default) + public int Reads { get; private set; } + + public ValueTask IsGrantedAsync(string subjectDigest, string permissionKey, CancellationToken cancellationToken = default) { - Calls++; - return ValueTask.FromResult(true); + Reads++; + return ValueTask.FromResult( + subjectDigest == PlatformOperatorSubject.Digest(issuer, subject) && keys.Contains(permissionKey)); } } + + private sealed class FixedMonitor(PlatformOperatorGrantOptions value) : IOptionsMonitor + { + public PlatformOperatorGrantOptions CurrentValue => value; + public PlatformOperatorGrantOptions Get(string? name) => value; + public IDisposable? OnChange(Action listener) => null; + } } diff --git a/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj b/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj index 0de2998b..64412d71 100644 --- a/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj +++ b/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj @@ -9,6 +9,7 @@ + diff --git a/docs/architecture/21-feature-flags.md b/docs/architecture/21-feature-flags.md index c1c0370b..0b334978 100644 --- a/docs/architecture/21-feature-flags.md +++ b/docs/architecture/21-feature-flags.md @@ -417,13 +417,13 @@ CREATE TABLE platform_killswitches ( **Packet 9 shipped the table and the read path, and no writer** ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). -The reason is reachability rather than scheduling: every killswitch write runs inside -`EnterPlatformAdminScope(reason)`, and the registered `IPlatformAdminGate` is -`DenyAllPlatformAdminGate` until the Platform-scope permission arrives with the registry -in [Phase 03](../roadmap/phase-03-identity-admin.md). A toggle command shipped now would -be unreachable code with a permission key nothing registers. **Phase 03 owns the toggle -command, its permission and its runbook**; every gated read honours a flipped switch the -day one exists, and what is absent until then is the flipping. +The reason was reachability rather than scheduling: every killswitch write runs inside +`EnterPlatformAdminScope`, and no Platform gate existed. **P03-9 Step 1 ships the writer** +as a service entered with an operator admission for `platform.killswitch.write`, with a +MUST result row on the same transaction and the overlay cache entry dropped after the +commit ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Other +instances see the flip within the overlay's 60-second TTL; the +[killswitch runbook](../runbooks/killswitch.md) says so, and that the read fails open. A flippable killswitch pairs with a runbook entry describing when to use it and how to restore, and the obligation attaches to the phase that makes it flippable, not to the @@ -503,8 +503,9 @@ Both surfaces are MUST-audit security-events (see the `AlterColumn` that makes `valid_until` nullable; `platform_killswitches`, the overlay and its cache family, read-only until Phase 03 ships the toggle; the architecture tests. -- **Phase 03** — the killswitch toggle command, its Platform-scope permission, the - permitting `IPlatformAdminGate` and the runbook that pairs with a flippable switch. +- **Phase 03** — the killswitch writer, its Platform-scope permission, the operator gate + ([ADR-0101](../decisions/0101-platform-operator-authority.md)) and the runbook that + pairs with a flippable switch. - **Phase 02c** (parallel Hub Foundation) — `HubEntitlementProvider` and the HTTPS projection push (`PUT /api/internal/tenants/{id}/entitlements`) that drives `RefreshAsync`. Limit **enforcement** lands here too — the `403` refusal and the diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index be0d70bb..d162a52f 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -1400,15 +1400,13 @@ guards are specified only in the Database standard: `EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its own row through the fourth write path. `tenancy.killswitch.toggle` — the operation [ADR-0044 § 1](../decisions/0044-audit-write-path.md) names as the first to be performed -*inside* that scope — ships no writer here: the registered gate is -`DenyAllPlatformAdminGate` and the Platform-scope permission arrives with the registry in -[Phase 03](../roadmap/phase-03-identity-admin.md), which owns the toggle command -([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). +*inside* that scope — shipped no writer in Packet 9; P03-9 Step 1 ships it as a service entered with an +operator admission ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), +[ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)). [The Tenancy matrix](../modules/tenancy/audit.md) classifies it MUST and marks it -**both** `(off-path)` and `(planned)`: off-path because the scope is entered by a service -method rather than by a MediatR request, so there is no request type to key a catalogue -entry on (§ 13); planned because no writer performs it in this packet. A cell carries -every marker that applies, and this is the row that carries two. +`(off-path)`: the scope is entered by a service method rather than by a MediatR request, +so there is no request type to key a catalogue entry on (§ 13). It carried `(planned)` as +well until its writer shipped; a cell carries every marker that applies. The organization column is decided from the same source as the tenant and at the same moment, which is what keeps the two paths agreeing. On the in-transaction path the diff --git a/docs/glossary.md b/docs/glossary.md index b583d3cf..f53f2ee3 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -12,6 +12,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Organization** | A sub-unit within a tenant — a branch, campus, studio, department, or cohort. Two-level hierarchy strict (`Tenant → Organization`, no nesting) per [ADR-0017](decisions/0017-tenant-organization-hierarchy.md). Every tenant has at least one default organization. | | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | +| **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | | **Org Admin** | A user with administrative rights inside a single organization within a tenant. | @@ -233,7 +234,7 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | **Entitlement Projection** | The read-only copy LearnStack holds, delivered by `PUT /api/internal/tenants/{id}/entitlements` or embedded in a signed licence key, stored durably in `platform_entitlement_cache` and served through `IEntitlementProvider`. The record carries `TenantId`, `PlanCode`, `Features`, `Limits`, `Compliance`, `ExpiresAt`, `GraceUntil` and a monotonic `Generation` — every field `entitlement-v1.schema.json` requires, the compliance caps that gate data residency and recording consent included. One name differs from the wire and one from the column: `PlanCode` is `tier` on the wire and `plan_code` in the column, and `ExpiresAt` is `expires_at` on the wire and persists to the `valid_until` column; `grace_until` and `generation` keep theirs in both. `ExpiresAt` and `GraceUntil` are both **nullable**: a null expiry means no scheduled expiry — trials and perpetual licences, the cohort the Hub creates first — and it persists as `valid_until NULL` rather than as a far-future sentinel somebody eventually has to explain, so Packet 9 alters the column Packet 6 shipped `NOT NULL`. `RefreshAsync` is **generation-guarded inside the write statement** — never read-then-write — and applies a push whose `generation` is **at least** the stored one, reporting `IgnoredAsStale` only for one that is older: a stale push cannot resurrect a revoked plan, and a redelivery at the same generation is idempotent rather than discarded, which is what keeps the provisioning row's default `1` from swallowing the Hub's first real projection ([ADR-0045 Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md)). Delivery is **push-primary, not push-only**: [ADR-0034](decisions/0034-hub-contract-surface-invariant.md)'s normative read order keeps a demand-driven `POST /api/v1/internal/license/verify` as its last step. Wire shape pinned by `entitlement-v1.schema.json` in both repositories. See [ADR-0045 § 1](decisions/0045-entitlement-and-feature-flag-socket.md). | | **Course Access** | *Not* an entitlement — a learner's right to open a course. See *Enrollment & Access*. | | **Feature Key / Limit Key** | A typed value object (`FeatureKey`, `LimitKey`) from the `FeatureKeys` / `LimitKeys` static catalogs. Free-form strings are forbidden. A **feature** key is spelled `{area}.{name}` with no `.enabled` suffix — `classroom.recording` — and its descriptor additionally declares two things that are never inferred from the string: whether the key is **fail-open or fail-closed** when no projection exists at all, and the `KillswitchKeys` entry that gates it, by name and nullable. An existing projection past `grace_until` instead yields every feature false and every limit zero, regardless of key class ([ADR-0045 Amendment 3](decisions/0045-entitlement-and-feature-flag-socket.md#amendment-3--when-a-keys-class-decides-2026-09-11)). A **limit** key carries the **`limits.` prefix the Hub already ships** — `limits.max_users`, `limits.classroom_minutes_per_month` — because the Hub has merged plan validators built on that vocabulary and LearnStack has no implementing line; the earlier `tenancy.max_learners` / `classroom.minutes_per_month` / `media.storage_gb` spellings are **withdrawn** ([ADR-0045 Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md), [ADR-0021 (2026-09-08)](decisions/0021-feature-based-entitlement.md)). A `LimitKey`'s value is a sentinel-carrying `long`: `-1` is unlimited, `0` is denied, `> 0` is the allowance. `GetLimitAsync` returns `long` and never `long?` — "not projected" is not a state a caller can act on — and a key absent from the projection resolves to the catalog default the key declares ([ADR-0045 § 3](decisions/0045-entitlement-and-feature-flag-socket.md)). See [26-hybrid-license-model.md § 0](architecture/26-hybrid-license-model.md). | -| **Killswitch** | A `KillswitchKeys.*` flag whose default is "enabled" and gates an expensive or risky code path. Flipped off during an incident to disable the path platform-wide. The overlay is applied last and wins over both the plan projection and the tenant flag, and it reaches a key only through the `KillswitchKey` that key's descriptor **names** — the correspondence is declared, never derived from the spelling, so a renamed key cannot go silently ungated. It lives in **`platform_killswitches`** — one platform-scoped row per key, no `tenant_id` and no foreign key — and **not** in `tenant_feature_flags`, whose foreign key to `tenants` the deliberately absent sentinel cannot satisfy and which no role or `BYPASSRLS` attribute moves. Read through the L1 cache under the `platform:tenancy:killswitch` family and invalidated on toggle; a read failure resolves to the key's default (`true`) and logs at `Error`, because a cache outage must not disable every gated path platform-wide. **Packet 9 ships the table, the policies, the overlay and the cache family — and no writer**: every toggle runs inside `EnterPlatformAdminScope(reason)`, whose registered gate is `DenyAllPlatformAdminGate`, so nothing can enter that scope until the Platform-scope permission arrives, and [Phase 03](roadmap/phase-03-identity-admin.md) owns the toggle command, its permission and its runbook. Every gated read honours a flipped switch the day one exists; what is absent is the flipping. Per [ADR-0045 § 5 and Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md). | +| **Killswitch** | A `KillswitchKeys.*` flag whose default is "enabled" and gates an expensive or risky code path. Flipped off during an incident to disable the path platform-wide. The overlay is applied last and wins over both the plan projection and the tenant flag, and it reaches a key only through the `KillswitchKey` that key's descriptor **names** — the correspondence is declared, never derived from the spelling, so a renamed key cannot go silently ungated. It lives in **`platform_killswitches`** — one platform-scoped row per key, no `tenant_id` and no foreign key — and **not** in `tenant_feature_flags`, whose foreign key to `tenants` the deliberately absent sentinel cannot satisfy and which no role or `BYPASSRLS` attribute moves. Read through the L1 cache under the `platform:tenancy:killswitch` family and invalidated on toggle; a read failure resolves to the key's default (`true`) and logs at `Error`, because a cache outage must not disable every gated path platform-wide. Packet 9 shipped the table, the policies, the overlay and the cache family, and no writer. The writer ships with P03-9 Step 1: a service entered with an operator admission for the Platform permission `platform.killswitch.write` ([ADR-0101 § 13](decisions/0101-platform-operator-authority.md)), which records a MUST row on the same transaction and drops the overlay cache entry after the commit; see the [killswitch runbook](runbooks/killswitch.md). Per [ADR-0045 § 5 and Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md). | | **Soft vs Hard Limit** | A `LimitKey` declares `LimitEnforcement = Soft \| Hard`. Hard refuses the operation with `403 ProblemDetails`; Soft surfaces a banner and emits a Hub-side soft-limit alert. The descriptor is declared with each key in Phase 02a Packet 9; the **enforcement** path — the refusal and the `usage.alert.soft_limit_reached` signal — lands in [Phase 02c](roadmap/phase-02c-hub-foundation.md) with `IUsageReporter` and `POST /api/v1/usage/report`, and each individual gate ships with the feature it gates rather than speculatively ([ADR-0045 § 6](decisions/0045-entitlement-and-feature-flag-socket.md)). | ## Search diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 8b4cc3be..34d8974f 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -159,7 +159,7 @@ unmarked row is one a shipped command already raises. | `TenantSetting` | `tenancy.setting.soft_delete` `(planned)` | **MUST** | Removing a setting is a change to it, so the same baseline row covers it — and `ux_tenant_settings_tenant_id_organization_id_key` is partial on `deleted_at IS NULL`, so the key becomes free for a successor | | `Tenant` | `tenancy.locale.write` | SHOULD | Configuration; contained TenantLocale changes are captured with their owning Tenant root | | `TenantFeatureFlag` | `tenancy.feature_flag.write` `(planned)` | **MUST** | "Feature flag toggled" is on the same baseline row, and [Feature Flags § Audit](../../architecture/21-feature-flags.md) classes both flag surfaces as security events | -| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` `(planned)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | +| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | | `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, for the reason `tenancy.killswitch.toggle` carries both: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | | `platform_host_to_tenant` | `tenancy.hostmapping.write` | **MUST** | The resolution index — the row that decides whose data an anonymous request sees | | `platform_host_to_tenant` | `tenancy.hostmapping.delete` `(planned)` | **MUST** | The same row removed. The table carries no `deleted_at`, so the delete is a row gone and a host that resolves to nobody | diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index caa988ef..401d578f 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -110,6 +110,12 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi [Database Standards § GRANT matrix](../../standards/05-database.md) records that the widening it needs is an ADR's to make, not a migration's. +The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) is +separate and never assignable to a Role. Tenancy owns one key in it today, +`platform.killswitch.write`, which authorizes the operator surface to toggle +`platform_killswitches`; operators hold it by configuration +([Standard 19](../../standards/19-permissions.md)). + ## Bounded human administration contract Internal human requests carry separate Protected policies and audit bindings. diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 983865b2..2e928ccb 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,9 +509,10 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 264 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 372 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines + - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -24433,3 +24434,111 @@ and 19, Architecture 13, 28 and 30, the glossary, the Tenancy audit matrix, Phas Standard 05 grants and definers, Standard 19 key rows, Standard 21 rules, the permission and audit matrices and the runbooks land with the steps that use them. No gate other than G13 and G14 changes status, and no behavior is implemented by this record. + +### P03-9 Step 1 — operator authority and killswitch (2026-11-19) + +Step 1 delivers [ADR-0101](../decisions/0101-platform-operator-authority.md) § 1 to § 14 +for the first Platform operation, the killswitch toggle. The decisions were Accepted in +`a396f50e`; this record is the implementation and its proof. + +Delivered: + +- **Contracts** in `LearnStack.SharedKernel`: the Platform permission catalogue + (`platform.killswitch.write`), the closed operation registry, the operator witness and + the admission, each constructible only through a nested `Minter`, the operator subject + digest, the gate and grant-source ports and the ticket grammar. +- **Gate and grants** in `LearnStack.Infrastructure`: `PlatformOperatorGate`, the + configuration grant adapter on `IOptionsMonitor` (valid reloads apply on the next act, + an invalid reload refuses everyone), start-time validation of every grant, the + demo-operator rule, and the `learnstack.platform_operator` counters. +- **Scope redesign**: `EnterAsync` takes an admission; the handle is a facade with no + connection or transaction member and closes its connection at commit; the entry row + carries `metadata.operator`, the closed reason slug and the correlation id with a NULL + actor; a new witness-bound `IAuditStore.WritePlatformOperatorResultAsync` writes the + MUST result row on the work transaction. `IPlatformAdminGate`, + `DenyAllPlatformAdminGate` and `PlatformAdminScopeDeniedException` are removed. +- **Surface**: the `PlatformOperator` bearer scheme with a closed token profile shared + as `PlatformOperatorTokenProfile`, the named policy, minimal endpoints under + `/api/platform/v1`, the `platform-v1` OpenAPI document, the prefix added to the host + classification and versioned-route exemptions, and absence when no issuer is + configured. +- **Killswitch writer** `KillswitchToggle`: reads the before state under `FOR UPDATE`, + upserts, writes the result row, commits, then drops the overlay entry, including after + an indeterminate commit. `tenancy.killswitch.toggle` is declared off-path and loses + its `(planned)` marker. +- **Realm**: the `learnstack-operator` client with the `learnstack-platform` audience, a + 900-second access-token lifespan, no realm roles in the token, the `browser-loa` flow + with a level-2 one-time password, `acr.loa.map` `mfa` to 2, and a pinned demo-operator + subject. Development configuration accepts `mfa` and grants the demo operator the one + key. +- **Documents**: the operator-access and killswitch runbooks and the runbooks index; the + Keycloak README; Standard 19's Platform catalogue; the catalogue entry for + `PlatformAdminScope_Entry_Requires_Platform_Permission` and two new rules; the Tenancy + permission note; the glossary; the stale "no writer" narratives in Architecture 21 and + 31, Standard 05 and the code comments. + +Findings made while implementing, each fixed: + +- The host's default and fallback authorization policies carry only the + declared-operation requirement and no authenticated-user requirement, so + `[Authorize(AuthenticationSchemes = ...)]` alone authenticated the token and then + admitted an anonymous caller. The endpoints use an explicit named policy that requires + an authenticated principal from this scheme only. The case that found it asserts the + `Bearer` challenge, which only the challenge path sets. +- The pipeline-order proof treated the endpoint mapper's `MapGroup` as an unverifiable + helper; `MapGroup` joins `MapGet` as a framework endpoint leaf and the mapper is + declared. +- The Debug build of the architecture project fails + `Authorization_Evidence_Uses_Trusted_Bounded_Provenance`, an IL-shape rule over a type + this step does not touch; the Release build that CI uses passes it. Recorded, not + changed. +- Six closed censuses counted the new surface and were updated, each by exact type or + name and never by widening a pattern: the authenticated HTTP surface and the + job-manifest registration population exclude `PlatformOperatorEndpoints` (its own + population is closed by + `The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_Its_Prefix`); the + raw-claim authority census admits `PlatformOperatorTokenProfile.TryRead` alone; + `IAuditStore` gains its eleventh write; the unversioned-prefix list gains + `api/platform`; and Standard 21's published counts move from 377 to 379 test methods + and 164 to 166 rules in that assembly. +- Development configuration now carries an operator issuer and the demo grant, so every + test host would have inherited them. The base test factory blanks the issuer and + points the one grant at a subject nobody holds; the operator tests set their own. + Grants without an issuer validate as inert, because with no issuer there is no scheme + and the grant source answers no for everyone. +- A restored source file kept its old modification time, so an incremental build reused + the mutated binaries and three suites failed on stale code. Restored files are touched + before the rebuild. + +Proof run locally: + +| Suite | Result | +|---|---| +| Unit | 4,181 passed | +| Integration, operator and boundary subset (619 cases: route, host classification, authenticated surface, composition, OpenAPI, deployment modes, job manifest, tenant authentication, platform scope, operator HTTP, job admission, idempotency, rate limit, federation) | 619 passed | +| of which `PlatformOperatorHttpTests` (production Program, controlled RS256 issuer) | 26 passed | +| of which `PlatformAdminScopeTests` (real PostgreSQL as the platform role) | 24 passed | +| `PlatformOperatorRealmTests` (pinned Keycloak 26.7.5, real OTP login) | 3 passed | +| Contract (served tenant document unchanged) | 13 passed | +| Architecture (Release): scope and evidence rules, API conventions, audit conventions, corpus consistency | passed | +| Architecture (Release): `OutboxDispatchConventionTests`, `AuthenticationAuthorityTests`, `AuthenticatedHttpSurfaceTests` | were still running at the commit; the result is recorded in the review-round entry | + +The real-realm cases show that the shipped export issues an operator token with audience +`learnstack-platform`, `azp` `learnstack-operator`, `acr` `mfa`, an `auth_time`, a +lifetime inside 15 minutes and the pinned subject, that the same profile the scheme uses +accepts it, and that a token from the portal client on the same realm and user does not +meet it. + +Mutation checks, each applied, built, run and restored: the gate skipping the grant, the +ticket reaching a tenant-visible row, the cache dropped before the commit, a policy +without an authenticated-user requirement, an ignored `auth_time` age, an unchecked +`azp` and a result row allowed an actor were all killed. One survived: the scope's +refusal of a registered operation that does not use the platform role, because the +registry holds no such operation yet. It is an equivalent mutant today; Step 2 registers +the first and drives the guard. The unit case that implied it covered the +unregistered-operation half and was renamed to say so. + +Not done here and owned elsewhere: manual accessibility needs no screen in this step; +the runbooks were written and their requests are the ones the tests make, but no person +ran them end to end; gateway exposure, production realm MFA enforcement and the grant +table adapter are in Phase 11's list. diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md new file mode 100644 index 00000000..9a042b87 --- /dev/null +++ b/docs/runbooks/README.md @@ -0,0 +1,12 @@ +# Runbooks + +Operational procedures, one per failure or privileged act. Each names the signal, the +diagnostic access, the safe recovery and what is not recoverable +([Documentation Standards](../standards/13-documentation.md)). Phase 03 begins this +directory with the platform operator runbooks; +[Phase 11](../roadmap/phase-11-production-hardening.md) completes the set. + +| Runbook | Use it when | +|---|---| +| [Platform operator access](operator-access.md) | An operator needs a token, a grant, or an answer to a 401, 403 or 503 | +| [Killswitch](killswitch.md) | A capability must be switched off for every tenant during an incident | diff --git a/docs/runbooks/killswitch.md b/docs/runbooks/killswitch.md new file mode 100644 index 00000000..66a0b98a --- /dev/null +++ b/docs/runbooks/killswitch.md @@ -0,0 +1,63 @@ +# Killswitch + +Switching a capability off for every tenant during an incident, and switching it back. +Decided in [ADR-0101 § 13](../decisions/0101-platform-operator-authority.md); the +registry and the overlay are described in +[Feature Flags](../architecture/21-feature-flags.md). + +## When to use it + +Only during an incident, to stop an expensive or risky path for all tenants at once. It +is not a way to take a feature away from one tenant; tenant flags and the plan do that. + +| Key | Capability | +|---|---| +| `killswitch.classroom.recording` | Recording a live class | +| `killswitch.notifications.email` | Outbound email | +| `killswitch.analytics.ingest` | Analytics ingest | + +No production code reads any of these yet. Flipping one is recorded and visible to the +overlay, but changes no behavior until the capability that guards a path reads it. The +owner of that capability states it in its own runbook. + +## What it needs + +An operator holding the Platform permission `platform.killswitch.write`, a current token +(see [operator access](operator-access.md)), and the key from the table. + +## Switching a key off + +`PUT /api/platform/v1/killswitches/{key}` with body +`{"enabled": false, "ticket": "INC-123"}`. The answer is +`{ "key", "before", "after", "correlationId" }`. `before` is `true` when no row existed, +because absent and enabled mean the same. + +Two audit rows are written under the platform sentinel, which no tenant can read: the +entry into the platform scope, and the result row `tenancy.killswitch.toggle` with the +before and after state and the operator's digest. The ticket is on those rows and in the +`reason` column of the switch's own row. Find them by the correlation id. + +## When it takes effect + +Immediately on the instance that handled the request, which drops its cached copy after +the commit. Every other instance refreshes within 60 seconds. Plan for that minute. + +**The read fails open.** If the overlay cannot read the table or the cache, it answers +the key's default, which is enabled. A switch flipped off during a database or cache +incident can therefore read as on again once its cached copy expires. Watch the log for +the overlay's read-failure error, and repeat the flip if it appears. + +## Switching it back + +Send the same request with `"enabled": true`. There is no other restore, and no delete. +Confirm by the response (`after` is `true`) and by the result row. + +## If the answer is 503 + +The audit row could not be written, so the table was not changed. Repeat the request. + +## Not recoverable here + +A flip is not undone by the audit log: the log records it, and only another flip +reverses it. Two operators flipping the same key at once is last writer wins; the row +has no version, and both flips are in the audit log. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md new file mode 100644 index 00000000..77d9adce --- /dev/null +++ b/docs/runbooks/operator-access.md @@ -0,0 +1,94 @@ +# Platform operator access + +How a LearnStack or deployment operator authenticates to the platform surface, how a +grant is given and withdrawn, and how to read a refusal. Decided in +[ADR-0101](../decisions/0101-platform-operator-authority.md). + +## Who this is for + +Operators only: LearnStack staff, or the customer's staff in a Self-Hosted deployment. +An operator is not a tenant user and holds no tenant role. Nothing here is reachable +with a tenant token. + +## What must be configured + +The surface does not exist until an issuer is configured; with none, every +`/api/platform` path answers 404. + +| Setting | Meaning | +|---|---| +| `PlatformOperator:Issuer` | The deployment-controlled OIDC issuer, for example the `learnstack-hub` realm. HTTPS only; loopback HTTP in Development | +| `PlatformOperator:AcceptedAcr` | The `acr` values that show the second factor. The shipped realm emits `mfa` | +| `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | +| `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, at most one hour; default 15 minutes | +| `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | + +Environment variables use double underscores, for example `PlatformOperator__Issuer`. + +A Self-Hosted issuer other than the shipped realm must issue access tokens with: +audience `learnstack-platform`; `azp` in the allowed list; an `acr` in the accepted list +that is reached only after a second factor; an `auth_time` claim; and a lifetime of at +most 15 minutes. If it cannot, no operator can act, by design. + +## Getting a token + +The shipped realm provides the public client `learnstack-operator` (authorization code +with PKCE, redirect `http://127.0.0.1:8765/*`). The first login of the demo operator +asks it to set up an authenticator application. + +1. Make a verifier and its challenge: + `verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')` and + `challenge=$(printf %s "$verifier" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')`. +2. Open + `$ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator&response_type=code&scope=openid&redirect_uri=http://127.0.0.1:8765/callback&code_challenge=$challenge&code_challenge_method=S256&state=x` + and sign in with the password and the one-time code. +3. The browser lands on the callback address and shows a connection error. Copy `code` + from its address bar. +4. Redeem it: + `curl -s $ISSUER/protocol/openid-connect/token -d grant_type=authorization_code -d client_id=learnstack-operator -d redirect_uri=http://127.0.0.1:8765/callback -d code=$CODE -d code_verifier=$verifier`. + Use `access_token` as the bearer token. It lasts at most 15 minutes. + +## Making a call + +Send `Authorization: Bearer $TOKEN`. Every write may carry an optional `ticket` of 1 to +64 characters of `A-Z a-z 0-9 . _ : / # -`. The response carries a `correlationId`; +record it against your own ticket, because the audit rows a tenant can read never hold +the ticket. + +The operator contract is the document `/openapi/platform-v1.json`. It is served only +when an issuer is configured and is not part of the tenant contract or SDK. + +## Giving and withdrawing a grant + +Edit `PlatformOperator:Grants` in the deployment configuration: the operator's `sub` +from the issuer's console and the permission keys. Each entry is validated when the +process starts, and a key that is not registered stops the start. A configuration +provider that reloads (a file or a mounted secret) applies a change on the operator's +next act; one that cannot reload needs a restart. Withdrawal is the same edit, and it +takes effect on the next act, not at the token's expiry. + +The demo operator's grant is accepted in Development only; the process refuses to start +in any other mode while it is present. Never import the shipped realm's demo user into a +production realm. + +## Reading a refusal + +| Answer | Meaning | What to do | +|---|---|---| +| 401, `Bearer` challenge | The token is missing, expired, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated more than the allowed age ago, or lives longer than 15 minutes | Sign in again; check the issuer settings | +| 403 | The token is good and this operator holds no grant for the act | Ask for the grant | +| 400 | The ticket or the body is malformed | Fix the request | +| 404 | Unknown killswitch key, or the surface is not configured | Check the key and the issuer setting | +| 503 | The audit row could not be written, so nothing changed | Retry; the act is safe to repeat | + +Signals: counters `learnstack.platform_operator.admissions`, `.refusals` and `.results`; +a Warning log for every refusal naming the operation and the operator's digest (event +7102 for a refused act, 7103 for a refused credential); and, for every admitted platform +act, the Warning log of the platform scope (event 7001). A refused operator leaves no +database row. + +## Not recoverable here + +A refusal leaves no record in the audit log, only the counter and the log line. An +operator cannot grant themselves anything: grants are configuration, edited by whoever +deploys it. diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index dfe32697..fe2a98ae 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -953,16 +953,13 @@ no context, `learnstack_app` reads **all** of `platform_killswitches`, which is `USING (true)` exists to guarantee. **Packet 9 shipped the table and the read path, and no writer.** The reason is -reachability rather than scheduling: every toggle runs inside -`EnterPlatformAdminScope(reason)`, the registered `IPlatformAdminGate` is -`DenyAllPlatformAdminGate`, and nothing can enter that scope until the Platform-scope -permission arrives with the registry in -[Phase 03](../roadmap/phase-03-identity-admin.md) — which owns the toggle command, its -permission and its runbook -([ADR-0045 Amendment 1](../decisions/0045-entitlement-and-feature-flag-socket.md)). The -`learnstack_platform` write grant in the matrix below is written ahead of its caller, -and no runtime path puts a row in the table until that phase lands. Every gated read -honours a flipped switch the day one exists; what is absent is the flipping. +reachability rather than scheduling: every toggle runs inside the platform scope, and no +Platform gate existed. P03-9 Step 1 ships the writer, a service entered with an operator +admission for `platform.killswitch.write` +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), +[ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)); an +architecture rule confines the table's write verbs to it. The `learnstack_platform` write +grant in the matrix below is that writer's. The overlay is read through the L1 cache and invalidated on toggle, so the table itself is touched on a cache miss rather than on every request diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 4f2e1e1a..2612f74c 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -96,6 +96,15 @@ nonempty foundation registry. | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | +The registered Platform catalogue is `PlatformPermissions` in `LearnStack.SharedKernel`, +apart from the tenant registry and never assignable, so the served tenant document does not +change when it grows ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 5). A +key is registered with the operation that has a denied proof for it: + +| Key | Operation | Packet | +|---|---|---| +| `platform.killswitch.write` | `tenancy.killswitch.toggle` | P03-9 Step 1 | + Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. An explicit eligible Tenant grant can independently authorize the declared diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 295d3b39..f3fa4aab 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**377 test methods run in +**379 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, Packet 7, @@ -218,7 +218,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**282 rules in this catalogue are Implemented, and 164 of them are in that assembly.** +**284 rules in this catalogue are Implemented, and 166 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -5875,46 +5875,49 @@ structural test proves — and what it does not. #### `PlatformAdminScope_Entry_Requires_Platform_Permission` -- **Asserts:** `EnterPlatformAdminScope(reason)` cannot open without an authenticated principal holding a Platform-scope permission, and no handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry. -- **Source:** ADR-0036 § The platform-admin override is not a resolution source. -- **Type:** xUnit — reflection, a source scan, and a call to the registered gate. - **Kind:** structural (the marker and the scan) + behavioural (the gate refuses). -- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7) — conjunct A only. -- **Phase:** 02a (Packet 7). -- **Note:** **the permission clause is live in its mechanism and vacuous in its subject; - the marker clause is vacuous outright.** Two Notes previously stood here assigning - "live" to opposite clauses — one written when the rule was Registered and one when it - landed — and this replaces both. - - *Mechanism, live:* the gate is a real port, the registered implementation refuses - everyone, `PlatformAdminScope` consults it, and no second implementation exists in any - production assembly — which is how a permissive default actually arrives, registered - elsewhere for a demo. The ordering, gate before the credential is touched, is - behavioural and asserted in `PlatformAdminGateTests`; a structural rule cannot see it. - - *Subject, vacuous:* there is no Platform permission to hold. The canonical - `AuthorizationBehavior` uses explicit live policies, while the retained - assignable manifest contains only Tenant/Organization pairs. API authentication - is delivered under ADR-0064; the Platform-scope permission remains Identity work in - [Phase 03](../roadmap/phase-03-identity-admin.md). So - nothing exercises a *permitted* entry, and the gate refusing everyone blocks nothing - this packet ships. Packet 9 gives the scope its first real work and inherits the gate: - the platform-scope `security-event` row the scope writes on entry through - `IAuditStore.WritePlatformScopeAsync` - ([ADR-0044 § 10](../decisions/0044-audit-write-path.md)). The killswitch toggle is not - that caller. Packet 9 ships `platform_killswitches`, its policies, the overlay and the - cache family and **no writer at all**: a toggle command would sit behind - `DenyAllPlatformAdminGate` carrying a permission key nothing registers, so - [Phase 03](../roadmap/phase-03-identity-admin.md) owns the command, its permission and - its runbook - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - Neither is the GDPR redaction handler, which lands in Phase 03 with the `users` table - it needs. - - *Marker clause, still vacuous — but for a narrower reason since Packet 7 step 9:* no - handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry. - `ProvisionTenantCommand` now carries the first, and nothing carries the second, so the - conjunction is empty because one half of it is — not because both are. +- **Asserts:** entering the platform scope takes a `PlatformAdmission` and nothing else, and + the censuses that make an admission mean something are closed across every production + assembly: `PlatformAdmission.Minter` has exactly one subclass, the operator gate; + `PlatformOperatorWitness.Minter` has exactly one, the operator authentication boundary's; + `IPlatformOperatorGate` and `IPlatformOperatorGrantSource` each have exactly one + implementation. A second of any of them is how a permissive default ships. +- **Source:** ADR-0036 § The platform-admin override is not a resolution source; + [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and § 8. +- **Type:** xUnit — reflection over every production assembly, and behavioural cases without + Docker (`PlatformAdminGateTests`) and over HTTP with controlled signed tokens + (`PlatformOperatorHttpTests`). **Kind:** structural + behavioural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7; rewritten + against the real gate by P03-9 Step 1). +- **Phase:** 02a (Packet 7); P03-9. +- **Note:** the rule was live in its mechanism and vacuous in its subject while the registered + gate refused everyone. It now has a subject: a Platform permission exists (`PlatformPermissions`), + an operator can hold it through a grant, and a permitted entry is exercised. The ordering — + admission before the credential is touched — is behavioural and asserted in + `PlatformAdminGateTests`; a structural rule cannot see it. The marker clause, that no + handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry, is now + structural as well: `Only_The_Operator_Services_Hold_The_Platform_Scope` lists every file + that may hold the scope, and no request handler is among them. + +#### `Only_The_Operator_Services_Hold_The_Platform_Scope` + +- **Asserts:** the files that name `IPlatformAdminScope` are exactly the interface, the scope, + the persistence composition and the operator services that perform an admitted act + (today the killswitch toggle). Adding a service is a deliberate edit here, with its denied proof. +- **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a + tenant request path. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). +- **Phase:** P03-9. + +#### `Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer` + +- **Asserts:** the verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` against + `platform_killswitches` appear only in `KillswitchToggle`. The overlay's reads are unaffected. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 13. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). +- **Phase:** P03-9. ## P02d-4 public-read obligations diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index e07535cf..110d030b 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -186,7 +186,22 @@ manual ledger deletion, history reset, reduced retention or tenant-copy purge. | Realm | Population | Clients | |-------|------------|---------| | `learnstack` | Tenant users; four declared development accounts | `learnstack-web`: confidential code/S256 BFF; `learnstack-api`: resource and legacy service account; `learnstack-event-reader`: confined history reader; `learnstack-federation-admin`: confined federation adapter ([below](#federation-administration-client)); `account` and `account-console`: retired, disabled | -| `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE; unchanged by P02b-6 | +| `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE, the portal's; `learnstack-operator`: public PKCE for LearnStack's platform surface, audience `learnstack-platform`, 15-minute access tokens, MFA step-up | + +The `learnstack-hub` realm's browser flow is `browser-loa`: password at level 1, a one-time +password at level 2, so a login through `learnstack-operator` (which asks for `acr` `mfa`) always +ends in an `acr` that LearnStack accepts only for an operator who passed the second factor +([ADR-0101](../../docs/decisions/0101-platform-operator-authority.md) § 3). The demo operator +has a pinned subject and sets up an authenticator at its first login; production MFA enforcement +for the realm stays [Phase 11](../../docs/roadmap/phase-11-production-hardening.md). A realm import +into production never includes the demo user. + +`learnstack-hub-web` keeps `fullScopeAllowed: true` as a development posture, because the Hub +operator portal maps the `hub-*` realm roles from its token. Narrowing it needs `scopeMappings` for +those roles and is coordinated with the Hub's operator-portal packet (P02c-4), since the realm export +is shared with the Hub repository. The `learnstack-operator` client is `false` and carries no realm +roles. The procedure for getting a token is the +[operator access runbook](../../docs/runbooks/operator-access.md). [SeedData.IdentityUsers](../../backend/src/LearnStack.Tools.Seeder/SeedData.cs) owns actor UUIDs and the account/tenant association. The read-only Seeder diff --git a/infra/keycloak/realms/learnstack-hub.json b/infra/keycloak/realms/learnstack-hub.json index 6a2d4d21..b792b670 100644 --- a/infra/keycloak/realms/learnstack-hub.json +++ b/infra/keycloak/realms/learnstack-hub.json @@ -23,6 +23,116 @@ "internationalizationEnabled": true, "supportedLocales": ["en"], "defaultLocale": "en", + "browserFlow": "browser-loa", + "attributes": { + "acr.loa.map": "{\"mfa\":\"2\"}" + }, + "authenticationFlows": [ + { + "alias": "browser-loa", + "description": "Operator browser flow: password at level 1, OTP at level 2 (ADR-0101 step-up).", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "auth-cookie", + "authenticatorFlow": false, + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false + }, + { + "flowAlias": "browser-loa forms", + "authenticatorFlow": true, + "requirement": "ALTERNATIVE", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa forms", + "description": "The two authentication levels.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "flowAlias": "browser-loa level-1", + "authenticatorFlow": true, + "requirement": "CONDITIONAL", + "priority": 10, + "userSetupAllowed": false + }, + { + "flowAlias": "browser-loa level-2", + "authenticatorFlow": true, + "requirement": "CONDITIONAL", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa level-1", + "description": "Level 1: username and password.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "conditional-level-of-authentication", + "authenticatorConfig": "loa-1", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false + }, + { + "authenticator": "auth-username-password-form", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa level-2", + "description": "Level 2: one-time password, asked on every authentication.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "conditional-level-of-authentication", + "authenticatorConfig": "loa-2", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false + }, + { + "authenticator": "auth-otp-form", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false + } + ] + } + ], + "authenticatorConfig": [ + { + "alias": "loa-1", + "config": { "loa-condition-level": "1", "loa-max-age": "36000" } + }, + { + "alias": "loa-2", + "config": { "loa-condition-level": "2", "loa-max-age": "0" } + } + ], "requiredActions": [ { "alias": "CONFIGURE_TOTP", @@ -77,10 +187,49 @@ "post.logout.redirect.uris": "http://localhost:3100/*" }, "fullScopeAllowed": true + }, + { + "clientId": "learnstack-operator", + "name": "LearnStack Platform Operator (public PKCE)", + "description": "Operator access to LearnStack's /api/platform surface (ADR-0101). Public client, PKCE-enforced, MFA step-up, access tokens of at most 15 minutes, audience learnstack-platform, no realm roles in the token.", + "enabled": true, + "publicClient": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "redirectUris": [ + "http://127.0.0.1:8765/*", + "http://localhost:8765/*" + ], + "webOrigins": [], + "protocol": "openid-connect", + "attributes": { + "pkce.code.challenge.method": "S256", + "access.token.lifespan": "900", + "acr.loa.map": "{\"mfa\":\"2\"}", + "default.acr.values": "mfa" + }, + "protocolMappers": [ + { + "name": "learnstack-platform-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "consentRequired": false, + "config": { + "included.custom.audience": "learnstack-platform", + "id.token.claim": "false", + "access.token.claim": "true", + "introspection.token.claim": "true" + } + } + ], + "fullScopeAllowed": false } ], "users": [ { + "id": "5a3c8f0e-2b1d-4c6a-9e47-0d1f6a2b7c93", "username": "demo-operator@learnstack.test", "email": "demo-operator@learnstack.test", "emailVerified": true, From 5ebc5676c063f8df02da08c60cbc3f7f5b297e45 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 14:40:25 +0300 Subject: [PATCH 05/28] fix(platform): harden operator auth, scope facade and killswitch writer Review round 1 of P03-9 Step 1 found no Blocker. This applies the verified findings: a bounded, same-origin metadata transport for the operator scheme, a closed set of refusal causes, a profile that restates the issuer and range-checks its time claims, and a classifier that honours the operator metadata only on the operator surface. The admission is stamped, short lived and single use; the scope facade takes one DML statement, refuses a commit with no result row and a commit after a failed statement; the audit store binds the result row to its admission by parsing metadata.operator. The killswitch writer creates the row before it locks it so two first toggles serialise. The operator realm switches password reset off. Runbooks, Standards 05, 10, 18, 19 and 21, and the stale "no writer" statements are corrected, and the delivery log records the round, its mutation checks and its proof. ADR: 0101 Module: Tenancy, Audit, Api Co-Authored-By: Claude Sonnet 5.5 --- .claude/skills/add-feature-key/SKILL.md | 60 ++-- CLAUDE.md | 14 +- .../Authentication/BoundedMetadataReader.cs | 57 +++ .../OperationHttpClassification.cs | 14 +- .../PlatformOperatorAuthentication.cs | 225 ++++++++++-- .../PlatformOperatorMetadata.cs | 118 +++++++ .../PlatformOperatorSettings.cs | 26 +- .../TenantAuthenticationBackchannel.cs | 43 +-- .../Platform/PlatformOperatorEndpoints.cs | 37 +- .../PostgresAuditStore.cs | 52 ++- .../MultiTenancy/PlatformAdminScope.cs | 120 ++++++- .../PlatformOperator/PlatformOperatorGate.cs | 5 +- .../PlatformOperatorMetrics.cs | 42 ++- .../Platform/PlatformAdmission.cs | 29 +- .../KillswitchToggle.cs | 68 +++- .../Persistence/TenancyDbContext.cs | 5 +- .../tests/Fixtures/TestPlatformAdmissions.cs | 13 +- .../PlatformAdminScopeConventionTests.cs | 145 ++++++-- .../Database/KillswitchToggleOrderingTests.cs | 188 ++++++++++ .../Database/PlatformAdminScopeTests.cs | 333 +++++++++++++++--- .../PlatformOperatorHttpTests.cs | 202 ++++++++++- .../PlatformOperatorRealmFileTests.cs | 49 +++ .../PlatformOperatorRealmTests.cs | 4 +- .../PlatformOperatorAuthenticationTests.cs | 261 ++++++++++++++ .../MultiTenancy/PlatformAdminGateTests.cs | 136 ++++++- docs/architecture/21-feature-flags.md | 23 +- docs/modules/tenancy/audit.md | 4 +- docs/roadmap/phase-03-delivery-log.md | 110 +++++- docs/runbooks/killswitch.md | 54 ++- docs/runbooks/operator-access.md | 149 ++++++-- docs/standards/05-database.md | 6 +- docs/standards/10-observability.md | 5 + docs/standards/18-audit-coverage.md | 24 +- docs/standards/19-permissions.md | 2 +- .../21-architecture-tests-catalogue.md | 46 ++- infra/compose/README.md | 7 +- infra/keycloak/README.md | 31 +- infra/keycloak/realms/learnstack-hub.json | 2 +- 38 files changed, 2361 insertions(+), 348 deletions(-) create mode 100644 backend/src/LearnStack.Api/Authentication/BoundedMetadataReader.cs create mode 100644 backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs diff --git a/.claude/skills/add-feature-key/SKILL.md b/.claude/skills/add-feature-key/SKILL.md index 5b37d6f5..35a62187 100644 --- a/.claude/skills/add-feature-key/SKILL.md +++ b/.claude/skills/add-feature-key/SKILL.md @@ -25,9 +25,8 @@ the socket; [ADR-0021](../../../docs/decisions/0021-feature-based-entitlement.md `platform_entitlement_cache` itself. - **Tenant-flag** keys read `tenant_feature_flags` (per-tenant rollout / opt-in). - **Killswitches** read `platform_killswitches`, a platform-scoped table with no - tenant column and no foreign key, through the L1 cache. Packet 9 ships that table - **unwritten** — read path only, no toggle — and Phase 03 owns the command that flips a - switch (Step 6). + tenant column and no foreign key, through the L1 cache. Their single writer is + `KillswitchToggle`, reached by the operator route (P03-9 Step 1). `IFeatureFlags` is the **only** module-facing read and it **composes** over the port rather than querying a table; the catalogue's `Source` descriptor says which half a key @@ -331,9 +330,11 @@ role and no `BYPASSRLS` moves it. Killswitches ship as **`platform_killswitches` the Tenancy migration chain with role-qualified policies like `platform_host_to_tenant`'s: `ENABLE` **and** `FORCE`, `FOR SELECT TO learnstack_app USING (true)`, every write reserved to -`learnstack_platform` through the audited `EnterPlatformAdminScope(reason)` path — which -is what makes `tenancy.killswitch.toggle` a MUST-class audit row with a real actor -([ADR-0045 § 5](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md)). +`learnstack_platform` through the audited, admission-gated `IPlatformAdminScope` path — +which is what makes `tenancy.killswitch.toggle` a MUST-class audit row that names the +operator in `metadata.operator` +([ADR-0045 § 5](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md), +[ADR-0101](../../../docs/decisions/0101-platform-operator-authority.md)). The overlay is read through the **L1 cache** and invalidated on toggle, under a second allowed platform `CacheKey` family — `platform:tenancy:killswitch`. `EnsureValid` admits @@ -343,31 +344,28 @@ the key's default (`true`, enabled) and logs at `Error`: a cache outage must not every gated path platform-wide. A flip is eventually consistent across instances, bounded by the TTL and the invalidation event. -**Packet 9 ships the table unwritten, and nothing in it flips a switch** +**The table has one writer: `KillswitchToggle`** +([ADR-0101 § 13](../../../docs/decisions/0101-platform-operator-authority.md)). Packet 9 +shipped the table, the policies, the overlay, the cache family and the three +`KillswitchKeys` with no writer, because every write needs an authenticated operator +holding the Platform permission and none existed ([ADR-0045 Amendment 1 § 4](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md#amendment-1--what-the-other-repository-already-shipped-2026-09-08)). -The table, the policies, the overlay, the cache family and the three `KillswitchKeys` -ship; no writer does. The reason is reachability rather than scheduling: every killswitch -write runs inside `EnterPlatformAdminScope(reason)`, the registered `IPlatformAdminGate` -is `DenyAllPlatformAdminGate`, and nothing can enter that scope until the Platform-scope -permission arrives with the registry in -[Phase 03](../../../docs/roadmap/phase-03-identity-admin.md). A toggle command shipped -now would be unreachable code with a permission key nothing registers. **Phase 03 owns -the toggle command, its permission and its runbook**; until it lands, -`tenancy.killswitch.toggle` carries `(planned)` in the Tenancy matrix beside the -`(off-path)` marker it keeps permanently +P03-9 Step 1 added the operator scheme, the gate and the writer: the operator calls +`PUT /api/platform/v1/killswitches/{key}`, the gate checks `platform.killswitch.write`, +and the writer flips the row and records the MUST result row on one transaction. No +other file may write the table (an architecture rule pins it), and a new key needs no +new command: declaring it in `KillswitchKeys.All` makes it flippable through the same +route. `tenancy.killswitch.toggle` keeps `(off-path)` in the Tenancy matrix permanently ([Audit Coverage § The join](../../../docs/standards/18-audit-coverage.md), [ADR-0044 Amendment 3](../../../docs/decisions/0044-audit-write-path.md#amendment-3--what-the-join-binds-to-and-the-types-the-ports-carry-2026-09-08)). -Every gated read honours a flipped switch the day one exists; what is absent is the -flipping. +Every gated read honours a flipped switch. -So a killswitch key added before Phase 03 is read-only, and its runbook lands with the -command that makes it flippable. The runbook entry — in `docs/runbooks/`, a directory -[Phase 11](../../../docs/roadmap/phase-11-production-hardening.md) owns — describes: +So a killswitch key added from now on is flippable the day it is declared, and its entry +in `docs/runbooks/killswitch.md` lands in the same change. The entry describes: - When to use it (the incident shape). -- How to flip it — the operator action through `EnterPlatformAdminScope(reason)`, never - a hand-written `UPDATE` as `learnstack_app`, which holds no write privilege on the - table. +- How to flip it — the operator request, never a hand-written `UPDATE` as + `learnstack_app`, which holds no write privilege on the table. - How to restore (revert + observability check). A flippable killswitch without a runbook is incomplete. @@ -482,11 +480,11 @@ public async Task RefreshAsync_AppliesAnEqualGenerationPush() - **Omitting the failure posture.** ADR-0034 puts it in the registry; a key that leaves it to the call site has no answer for the unresolved case, which is the one case the member exists for. -- **A killswitch without a runbook, once one can be flipped.** The runbook belongs with - the command Phase 03 lands, not with the key Packet 9 registers. CI does not enforce - its presence; review must. -- **Writing a killswitch toggle in Packet 9.** The table ships unwritten and - `DenyAllPlatformAdminGate` is registered, so the command would be unreachable code - gated by a permission nothing registers. +- **A killswitch without a runbook entry.** The key is flippable the moment it is + declared, so its entry in `docs/runbooks/killswitch.md` belongs in the same change. CI + does not enforce its presence; review must. +- **A second writer of `platform_killswitches`.** `KillswitchToggle` is the only one; an + architecture rule fails any other file that inserts, updates, deletes or truncates the + table. - **Removing a key without a deprecation cycle.** A rename / remove follows the same one-release-deprecation-warning rule as permissions. diff --git a/CLAUDE.md b/CLAUDE.md index 9e69f553..71518c67 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -318,13 +318,13 @@ rules: `BYPASSRLS` moves. Killswitches live in the platform-scoped `platform_killswitches` ([ADR-0045](docs/decisions/0045-entitlement-and-feature-flag-socket.md)). - Packet 9 ships that table, its policies, the overlay and its cache family — - and **no writer**: every toggle runs inside `EnterPlatformAdminScope(reason)`, - whose registered gate is `DenyAllPlatformAdminGate`, so nothing can enter that - scope until the Platform-scope permission arrives, and - [Phase 03](docs/roadmap/phase-03-identity-admin.md) owns the toggle command, - its permission and its runbook - ([ADR-0045 Amendment 1](docs/decisions/0045-entitlement-and-feature-flag-socket.md)). + Packet 9 shipped that table, its policies, the overlay and its cache family; + the single writer is `KillswitchToggle`, which enters the platform scope only + with a `PlatformAdmission` the operator gate minted for an authenticated + operator holding `platform.killswitch.write` + ([ADR-0101](docs/decisions/0101-platform-operator-authority.md), + [runbook](docs/runbooks/killswitch.md)), and the architecture rules pin that no + other file writes the table. - **Read `platform_entitlement_cache` from a module, `IFeatureFlags` included.** The only sanctioned reader *and* writer is an `IEntitlementProvider` implementation; `IFeatureFlags` composes over the port, which is what makes diff --git a/backend/src/LearnStack.Api/Authentication/BoundedMetadataReader.cs b/backend/src/LearnStack.Api/Authentication/BoundedMetadataReader.cs new file mode 100644 index 00000000..ab84edfa --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/BoundedMetadataReader.cs @@ -0,0 +1,57 @@ +using System.Text; +using OpenTelemetry; + +namespace LearnStack.Api.Authentication; + +/// +/// Reads one identity-provider metadata document under a deadline and a byte cap, so a hostile +/// or broken issuer endpoint can neither hold a request nor fill memory. +/// +/// +/// Both bearer schemes' stock configuration managers consume documents through this one +/// reader: the tenant scheme and the operator scheme (ADR-0101 § 2) each pass their own +/// client, timeout, cap and refusal text, and nothing else differs. +/// +internal static class BoundedMetadataReader +{ + internal static async Task ReadAsync( + HttpClient client, + Uri uri, + TimeSpan timeout, + int maximumBytes, + string refusal, + CancellationToken cancel) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancel); + deadline.CancelAfter(timeout); + // Suppress metadata HTTP spans. The composition root separately projects + // native HTTP/DNS metrics, which do not honor this request-local scope. + using var suppression = SuppressInstrumentationScope.Begin(); + using var request = new HttpRequestMessage(HttpMethod.Get, uri); + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); + if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength > maximumBytes) + { + throw new IOException(refusal); + } + + await using var stream = await response.Content.ReadAsStreamAsync(deadline.Token); + using var body = new MemoryStream(); + var buffer = new byte[8192]; + while (true) + { + var remaining = maximumBytes - (int)body.Length; + var read = await stream.ReadAsync(buffer.AsMemory(0, Math.Min(buffer.Length, remaining + 1)), deadline.Token); + if (read == 0) + { + return Encoding.UTF8.GetString(body.GetBuffer(), 0, (int)body.Length); + } + + if (read > remaining) + { + throw new IOException(refusal); + } + + body.Write(buffer, 0, read); + } + } +} diff --git a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs index 36fc5873..260aeeea 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs @@ -71,7 +71,8 @@ internal HttpOperationClassification Classify(Endpoint? endpoint, out OperationP return ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.Health) || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.OpenApi) || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.Documentation) - || ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.PlatformOperator) + || (ReferenceEquals(infrastructure[0], InfrastructureOperationMetadata.PlatformOperator) + && IsOperatorEndpoint(endpoint)) ? HttpOperationClassification.Infrastructure : HttpOperationClassification.Refused; } if (declarations.Count != 1 || endpoint.Metadata.GetMetadata() is not { } action @@ -106,6 +107,17 @@ internal HttpOperationClassification Classify(Endpoint? endpoint, out OperationP return HttpOperationClassification.Application; } + // The operator metadata is a declaration, not a proof: it classifies an endpoint as + // infrastructure, which the tenant admission middlewares then leave alone. So it is honoured + // only where the operator surface is: under the versioned operator prefix, behind exactly the + // operator policy and never anonymous. Anything else carrying it is refused. + private static bool IsOperatorEndpoint(Endpoint endpoint) => + endpoint is RouteEndpoint { RoutePattern.RawText: { } raw } + && raw.TrimStart('/').StartsWith("api/platform/v1/", StringComparison.OrdinalIgnoreCase) + && endpoint.Metadata.GetOrderedMetadata() is [{ } authorize] + && authorize.Policy == PlatformOperatorAuthentication.PolicyName + && endpoint.Metadata.GetOrderedMetadata().Count == 0; + private static bool HasCanonicalKeyMetadata(Endpoint endpoint, ControllerActionDescriptor action, ProtectedAdministrationDescriptor? operation) { diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs index 4c268582..8c036484 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs @@ -9,6 +9,8 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Logging; +using Microsoft.IdentityModel.Protocols; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; namespace LearnStack.Api.Authentication; @@ -32,6 +34,12 @@ namespace LearnStack.Api.Authentication; /// azp, a token lifetime of at most 15 minutes, an accepted acr and a recent /// auth_time. Roles and every other claim carry no authority. /// +/// +/// Bounded metadata. The discovery document and key set come through a client of the +/// scheme's own that follows no redirect, waits five seconds, reads at most 256 KB and fetches +/// nothing outside the issuer's origin. The last known good configuration is off: an issuer +/// that cannot be reached refuses every operator, which is the safe side of an outage. +/// /// internal static class PlatformOperatorAuthentication { @@ -56,11 +64,13 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( IdentityModelEventSource.LogCompleteSecurityArtifact = false; services.AddSingleton(settings); services.TryAddSingleton(); + services.AddSingleton(); services.AddAuthentication().AddJwtBearer(Scheme, _ => { }); services.AddAuthorization(options => options.AddPolicy( PolicyName, policy => policy.AddAuthenticationSchemes(Scheme).RequireAuthenticatedUser())); services.AddOptions(Scheme) - .Configure>((options, clock, logger) => + .Configure, ILogger>( + (options, backchannel, clock, logger, retrieverLogger) => { options.Authority = settings.Issuer; options.MetadataAddress = settings.MetadataAddress; @@ -68,11 +78,24 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( options.MapInboundClaims = false; options.SaveToken = false; options.IncludeErrorDetails = false; + options.Backchannel = backchannel.Client; + options.BackchannelTimeout = PlatformOperatorBackchannel.Timeout; options.AutomaticRefreshInterval = TimeSpan.FromMinutes(5); options.RefreshInterval = TimeSpan.FromSeconds(30); + options.ConfigurationManager = new ConfigurationManager( + settings.MetadataAddress, + new OpenIdConnectConfigurationRetriever(), + new PlatformOperatorDocumentRetriever(settings, backchannel, retrieverLogger), + new PlatformOperatorConfigurationValidator(settings)) + { + AutomaticRefreshInterval = options.AutomaticRefreshInterval, + RefreshInterval = options.RefreshInterval, + UseLastKnownGoodConfiguration = false, + }; options.TokenValidationParameters = new TokenValidationParameters { RequireSignedTokens = true, + TryAllIssuerSigningKeys = false, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidIssuer = settings.Issuer, @@ -100,21 +123,13 @@ internal sealed class PlatformOperatorFeature(PlatformOperatorWitness witness) internal PlatformOperatorWitness Witness { get; } = witness; } -/// The one minter the operator authentication boundary owns (ADR-0101 § 7). -internal sealed class PlatformOperatorWitnessMinter : PlatformOperatorWitness.Minter -{ - internal static PlatformOperatorWitness Create( - string issuer, string subjectDigest, string acr, DateTimeOffset authenticatedAt, string? correlationId) => - Mint(issuer, subjectDigest, acr, authenticatedAt, PlatformOperatorSettings.Executor, correlationId); -} - /// Scopes the scheme to its prefix and applies the closed token profile. internal sealed class PlatformOperatorEvents( PlatformOperatorSettings settings, IClock clock, ILogger logger) : JwtBearerEvents { public override Task MessageReceived(MessageReceivedContext context) { - if (!context.Request.Path.StartsWithSegments(PlatformOperatorSettings.RoutePrefix, StringComparison.Ordinal)) + if (!context.Request.Path.StartsWithSegments(PlatformOperatorSettings.RoutePrefix, StringComparison.OrdinalIgnoreCase)) { context.NoResult(); return Task.CompletedTask; @@ -123,7 +138,7 @@ public override Task MessageReceived(MessageReceivedContext context) var values = context.Request.Headers.Authorization; if (values.Count != 1 || values[0] is not { } header - || !header.StartsWith("Bearer ", StringComparison.Ordinal) + || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) || header.Length <= "Bearer ".Length) { context.NoResult(); @@ -136,10 +151,18 @@ public override Task MessageReceived(MessageReceivedContext context) public override Task TokenValidated(TokenValidatedContext context) { - if (context.SecurityToken is not JsonWebToken token - || !PlatformOperatorTokenProfile.TryRead(token, settings, clock.UtcNow, Activity.Current?.Id, out var witness)) + // The correlation id is the request's trace when one exists and the server's request + // id otherwise, so a result row is never recorded without a handle an operator can use. + var correlationId = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier; + if (context.SecurityToken is not JsonWebToken token) + { + context.Fail(new PlatformOperatorProfileException("token_invalid")); + return Task.CompletedTask; + } + + if (!PlatformOperatorTokenProfile.TryRead(token, settings, clock.UtcNow, correlationId, out var witness, out var cause)) { - context.Fail("Operator credential refused."); + context.Fail(new PlatformOperatorProfileException(cause.Label())); return Task.CompletedTask; } @@ -147,13 +170,22 @@ public override Task TokenValidated(TokenValidatedContext context) return Task.CompletedTask; } + public override Task AuthenticationFailed(AuthenticationFailedContext context) + { + // The stock handler rethrows what it did not classify, an unreachable issuer included, + // which would answer 500 and hide the cause. Failing here keeps one answer and lets + // the challenge below name the cause on the counter and the log. + context.Fail(context.Exception); + return Task.CompletedTask; + } + public override Task Challenge(JwtBearerChallengeContext context) { // One answer for a missing, malformed, expired or wrongly profiled credential: no // detail a probing caller could use, a counter and a log an operator can alert on. - var cause = context.AuthenticateFailure is null ? "token_missing" : "token_invalid"; + var cause = PlatformOperatorFailure.Classify(context.AuthenticateFailure); PlatformOperatorMetrics.Unauthenticated(cause); - LogUnauthenticated(logger, cause, null); + LogUnauthenticated(logger, cause, context.AuthenticateFailure?.GetType().Name ?? "none", null); context.HandleResponse(); context.Response.Headers.WWWAuthenticate = "Bearer"; return Respond(context.HttpContext, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); @@ -173,21 +205,100 @@ internal static Task Respond(HttpContext http, int status, string key) cancellationToken: http.RequestAborted); } - private static readonly Action LogUnauthenticated = - LoggerMessage.Define( + private static readonly Action LogUnauthenticated = + LoggerMessage.Define( LogLevel.Warning, new EventId(7103, nameof(LogUnauthenticated)), - "Platform operator credential refused: {Cause}."); + "Platform operator credential refused: {Cause} ({FailureType})."); +} + +/// Why a cryptographically valid operator token failed the closed profile. +internal enum PlatformOperatorTokenCause +{ + Subject = 0, + Issuer, + AuthorizedParty, + AuthenticationContext, + IssuedAt, + AuthenticationTime, + Lifetime, + AuthenticationAge, +} + +/// The bounded label set a counter carries; nothing a caller wrote reaches it. +internal static class PlatformOperatorTokenCauseLabels +{ + internal static string Label(this PlatformOperatorTokenCause cause) => cause switch + { + PlatformOperatorTokenCause.Subject => "profile_subject", + PlatformOperatorTokenCause.Issuer => "profile_issuer", + PlatformOperatorTokenCause.AuthorizedParty => "profile_azp", + PlatformOperatorTokenCause.AuthenticationContext => "profile_acr", + PlatformOperatorTokenCause.IssuedAt => "profile_iat", + PlatformOperatorTokenCause.AuthenticationTime => "profile_auth_time", + PlatformOperatorTokenCause.Lifetime => "profile_lifetime", + PlatformOperatorTokenCause.AuthenticationAge => "profile_auth_age", + _ => "profile_invalid", + }; +} + +/// Carries a closed profile label from TokenValidated to the challenge. +internal sealed class PlatformOperatorProfileException(string label) : Exception("Operator credential refused.") +{ + internal string Label { get; } = label; +} + +/// Maps an authentication failure to a closed label; the response never varies. +internal static class PlatformOperatorFailure +{ + internal static string Classify(Exception? failure) => failure switch + { + null => "token_missing", + PlatformOperatorProfileException profile => profile.Label, + AggregateException { InnerExceptions.Count: > 0 } aggregate => Classify(aggregate.InnerExceptions[0]), + SecurityTokenExpiredException => "token_expired", + SecurityTokenNotYetValidException or SecurityTokenNoExpirationException or SecurityTokenInvalidLifetimeException + => "token_lifetime", + SecurityTokenInvalidSignatureException or SecurityTokenSignatureKeyNotFoundException => "token_signature", + SecurityTokenInvalidIssuerException => "token_issuer", + SecurityTokenInvalidAudienceException => "token_audience", + SecurityTokenInvalidAlgorithmException => "token_algorithm", + SecurityTokenInvalidTypeException => "token_type", + _ when IsMetadataFailure(failure) => "metadata_unavailable", + _ => "token_invalid", + }; + + // The stock manager wraps every retrieval failure in an InvalidOperationException (IDX20803) + // whose cause is the transport or the retriever's own refusal. + private static bool IsMetadataFailure(Exception failure) + { + for (var current = failure; current is not null; current = current.InnerException) + { + if (current is IOException or HttpRequestException or TaskCanceledException) + { + return true; + } + } + + return failure is InvalidOperationException && failure.Message.Contains("IDX20803", StringComparison.Ordinal); + } } /// /// The closed profile a cryptographically valid operator token must also meet (ADR-0101 § 2, § 3). /// /// +/// /// A pure function of the validated token, the settings and the clock, so the scheme, the real-realm -/// proof and the offline rebind tool judge one definition. It admits an allow-listed azp, an -/// accepted acr, a lifetime of at most 15 minutes, and an auth_time that is neither in -/// the future nor older than the configured age. Nothing else in the token carries authority. +/// proof and the offline rebind tool judge one definition. It admits the pinned iss, an +/// allow-listed azp, an accepted acr, a lifetime of at most 15 minutes, and an +/// auth_time that is neither in the future nor older than the configured age. Nothing else +/// in the token carries authority. +/// +/// +/// It owns the witness minter. The minter is nested and private, so no other type in the +/// assembly can mint a witness, and a source census pins who may call . +/// /// internal static class PlatformOperatorTokenProfile { @@ -196,30 +307,66 @@ internal static bool TryRead( PlatformOperatorSettings settings, DateTimeOffset now, string? correlationId, - out PlatformOperatorWitness? witness) + out PlatformOperatorWitness? witness, + out PlatformOperatorTokenCause cause) { witness = null; - if (string.IsNullOrWhiteSpace(token.Subject) - || !token.TryGetPayloadValue("azp", out var azp) || !settings.AuthorizedParties.Contains(azp) - || !token.TryGetPayloadValue("acr", out var acr) || !settings.AcceptedAcr.Contains(acr) - || !token.TryGetPayloadValue("iat", out var iat) - || !token.TryGetPayloadValue("auth_time", out var authTime) - || token.ValidTo == DateTime.MinValue) + cause = default; + + // Stock validation already pinned the issuer; this restates it so the profile is + // correct for any caller, including one that validated with other parameters. + if (!string.Equals(token.Issuer, settings.Issuer, StringComparison.Ordinal)) + { + cause = PlatformOperatorTokenCause.Issuer; + return false; + } + + if (string.IsNullOrWhiteSpace(token.Subject)) + { + cause = PlatformOperatorTokenCause.Subject; + return false; + } + + if (!token.TryGetPayloadValue("azp", out var azp) || !settings.AuthorizedParties.Contains(azp)) + { + cause = PlatformOperatorTokenCause.AuthorizedParty; + return false; + } + + if (!token.TryGetPayloadValue("acr", out var acr) || !settings.AcceptedAcr.Contains(acr)) + { + cause = PlatformOperatorTokenCause.AuthenticationContext; + return false; + } + + if (!token.TryGetPayloadValue("iat", out var iat) || !IsUnixSeconds(iat) || token.ValidTo == DateTime.MinValue) + { + cause = PlatformOperatorTokenCause.IssuedAt; + return false; + } + + if (!token.TryGetPayloadValue("auth_time", out var authTime) || !IsUnixSeconds(authTime)) { + cause = PlatformOperatorTokenCause.AuthenticationTime; return false; } var issuedAt = DateTimeOffset.FromUnixTimeSeconds(iat); var authenticatedAt = DateTimeOffset.FromUnixTimeSeconds(authTime); var lifetime = new DateTimeOffset(token.ValidTo, TimeSpan.Zero) - issuedAt; - if (lifetime <= TimeSpan.Zero || lifetime > PlatformOperatorSettings.MaxTokenLifetime - || authenticatedAt > now + PlatformOperatorSettings.ClockSkew - || now - authenticatedAt > settings.MaxAuthenticationAge) + if (lifetime <= TimeSpan.Zero || lifetime > PlatformOperatorSettings.MaxTokenLifetime) { + cause = PlatformOperatorTokenCause.Lifetime; return false; } - witness = PlatformOperatorWitnessMinter.Create( + if (authenticatedAt > now + PlatformOperatorSettings.ClockSkew || now - authenticatedAt > settings.MaxAuthenticationAge) + { + cause = PlatformOperatorTokenCause.AuthenticationAge; + return false; + } + + witness = WitnessMinter.Create( settings.Issuer, PlatformOperatorSubject.Digest(settings.Issuer, token.Subject), acr, @@ -227,4 +374,16 @@ internal static bool TryRead( correlationId); return true; } + + // DateTimeOffset.FromUnixTimeSeconds throws outside year 1..9999; a claim an issuer signed + // is still not trusted to be in range. + private static bool IsUnixSeconds(long value) => value is >= -62135596800L and <= 253402300799L; + + /// The one minter the operator authentication boundary owns (ADR-0101 § 7). + private sealed class WitnessMinter : PlatformOperatorWitness.Minter + { + internal static PlatformOperatorWitness Create( + string issuer, string subjectDigest, string acr, DateTimeOffset authenticatedAt, string? correlationId) => + Mint(issuer, subjectDigest, acr, authenticatedAt, PlatformOperatorSettings.Executor, correlationId); + } } diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs new file mode 100644 index 00000000..cf5d3e7f --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs @@ -0,0 +1,118 @@ +using LearnStack.Infrastructure.PlatformOperator; +using Microsoft.IdentityModel.Protocols; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; + +namespace LearnStack.Api.Authentication; + +/// +/// The operator scheme's own bounded client: finite I/O and no redirects, cookies or +/// instrumented credential metadata (ADR-0101 § 2). +/// +/// +/// Owned apart from the tenant client because the two trust different issuers: sharing a +/// client would share nothing a reader should have to reason about. +/// +internal sealed class PlatformOperatorBackchannel : IDisposable +{ + internal static readonly TimeSpan Timeout = TimeSpan.FromSeconds(5); + internal const int MaximumDocumentBytes = 256 * 1024; + + public PlatformOperatorBackchannel() : this(new SocketsHttpHandler()) { } + + // Test-owned certificate authorities use the normal TLS chain/hostname checks; the + // transport bounds remain mandatory for every supplied handler. + internal PlatformOperatorBackchannel(SocketsHttpHandler handler) + { + ArgumentNullException.ThrowIfNull(handler); + if (handler.SslOptions.RemoteCertificateValidationCallback is not null) + { + throw new InvalidOperationException("Platform operator certificate validation cannot be replaced."); + } + + handler.AllowAutoRedirect = false; + handler.ConnectTimeout = Timeout; + handler.UseCookies = false; + Client = new HttpClient(handler) + { + Timeout = Timeout, + MaxResponseContentBufferSize = MaximumDocumentBytes, + }; + } + + internal HttpClient Client { get; } + + public void Dispose() => Client.Dispose(); +} + +/// +/// Fetches the discovery document and the key set, and nothing at another origin. +/// +/// +/// A discovery document that names a jwks_uri elsewhere would let whoever controls that +/// host choose the keys the operator scheme trusts, so every address must share the issuer's +/// origin and be canonical. +/// +internal sealed class PlatformOperatorDocumentRetriever( + PlatformOperatorSettings settings, + PlatformOperatorBackchannel backchannel, + ILogger logger) : IDocumentRetriever +{ + private const string Refusal = "Platform operator metadata refused."; + + public async Task GetDocumentAsync(string address, CancellationToken cancel) + { + try + { + return await ReadAsync(address, cancel); + } + catch (Exception failure) when (failure is not OperationCanceledException || !cancel.IsCancellationRequested) + { + // The request that triggered the fetch only learns that it found no key. The failure is + // counted and logged here, where it happens, because an issuer that cannot be reached + // refuses every operator and that is a state an operator of the platform must see. + PlatformOperatorMetrics.MetadataFailed(); + LogMetadataFailed(logger, failure.GetType().Name, null); + throw; + } + } + + private async Task ReadAsync(string address, CancellationToken cancel) + { + var issuer = new Uri(settings.Issuer); + if (!Uri.TryCreate(address, UriKind.Absolute, out var uri) + || !string.IsNullOrEmpty(uri.UserInfo) + || !string.IsNullOrEmpty(uri.Query) + || !string.IsNullOrEmpty(uri.Fragment) + || !uri.IsWellFormedOriginalString() + || !string.Equals(uri.AbsoluteUri, address, StringComparison.Ordinal) + || !string.Equals(uri.GetLeftPart(UriPartial.Authority), issuer.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal)) + { + throw new IOException(Refusal); + } + + return await BoundedMetadataReader.ReadAsync( + backchannel.Client, + uri, + PlatformOperatorBackchannel.Timeout, + PlatformOperatorBackchannel.MaximumDocumentBytes, + Refusal, + cancel); + } + + private static readonly Action LogMetadataFailed = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(7106, nameof(LogMetadataFailed)), + "Platform operator issuer metadata could not be read ({FailureType}); operators are refused until it can."); +} + +/// Discovery cannot widen the issuer authority the stock manager trusts. +internal sealed class PlatformOperatorConfigurationValidator(PlatformOperatorSettings settings) + : IConfigurationValidator +{ + public ConfigurationValidationResult Validate(OpenIdConnectConfiguration configuration) => new() + { + Succeeded = string.Equals(configuration.Issuer, settings.Issuer, StringComparison.Ordinal), + ErrorMessage = "Platform operator metadata refused.", + }; +} diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs index b9981058..4e3017fa 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorSettings.cs @@ -66,7 +66,27 @@ private PlatformOperatorSettings( { throw new InvalidOperationException( "PlatformOperator needs at least one AcceptedAcr and one AuthorizedParties value when " - + "an Issuer is configured; assurance and client are never inferred."); + + "an Issuer is configured, as indexed keys such as PlatformOperator__AcceptedAcr__0. " + + "Assurance and client are never inferred."); + } + + // OpenID Connect reserves 0 for authentication no stronger than a single factor, and + // many issuers emit 1 for a password: an accepted acr that is one of those is a + // misconfiguration that would turn the multi-factor requirement into a formality. + if (acr.Any(value => value is "0" or "1")) + { + throw new InvalidOperationException( + "PlatformOperator:AcceptedAcr must name a multi-factor assurance value the issuer emits; " + + "'0' and '1' are single-factor levels and are refused."); + } + + var tenantIssuer = configuration[TenantAuthenticationOptions.IssuerConfigurationKey]; + if (!string.IsNullOrWhiteSpace(tenantIssuer) + && string.Equals(tenantIssuer.TrimEnd('/'), issuer.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException( + "PlatformOperator:Issuer must not be the tenant issuer: operators authenticate at a " + + "deployment-controlled issuer that tenant administrators cannot influence."); } var ageText = section["MaxAuthenticationAge"]; @@ -74,7 +94,9 @@ private PlatformOperatorSettings( if (ageText is not null && (!TimeSpan.TryParse(ageText, System.Globalization.CultureInfo.InvariantCulture, out age) || age <= TimeSpan.Zero || age > TimeSpan.FromHours(1))) { - throw new InvalidOperationException("PlatformOperator:MaxAuthenticationAge must be between 0 and 1 hour."); + throw new InvalidOperationException( + "PlatformOperator:MaxAuthenticationAge must be a time span between 0 and 1 hour, " + + "for example 00:15:00."); } return new PlatformOperatorSettings(issuer, acr, parties, age); diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationBackchannel.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationBackchannel.cs index 7e2ae96e..22a8937a 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationBackchannel.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationBackchannel.cs @@ -1,7 +1,5 @@ -using System.Text; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; -using OpenTelemetry; namespace LearnStack.Api.Authentication; @@ -53,40 +51,13 @@ public async Task GetDocumentAsync(string address, CancellationToken can throw new IOException("Tenant authentication metadata refused."); } - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancel); - deadline.CancelAfter(TenantAuthenticationBackchannel.Timeout); - // Suppress metadata HTTP spans. The composition root separately projects - // native HTTP/DNS metrics, which do not honor this request-local scope. - using var suppression = SuppressInstrumentationScope.Begin(); - using var request = new HttpRequestMessage(HttpMethod.Get, uri); - using var response = await backchannel.Client.SendAsync( - request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); - if (!response.IsSuccessStatusCode - || response.Content.Headers.ContentLength > TenantAuthenticationBackchannel.MaximumDocumentBytes) - { - throw new IOException("Tenant authentication metadata refused."); - } - - await using var stream = await response.Content.ReadAsStreamAsync(deadline.Token); - using var body = new MemoryStream(); - var buffer = new byte[8192]; - while (true) - { - var remaining = TenantAuthenticationBackchannel.MaximumDocumentBytes - (int)body.Length; - var read = await stream.ReadAsync( - buffer.AsMemory(0, Math.Min(buffer.Length, remaining + 1)), deadline.Token); - if (read == 0) - { - return Encoding.UTF8.GetString(body.GetBuffer(), 0, (int)body.Length); - } - - if (read > remaining) - { - throw new IOException("Tenant authentication metadata refused."); - } - - body.Write(buffer, 0, read); - } + return await BoundedMetadataReader.ReadAsync( + backchannel.Client, + uri, + TenantAuthenticationBackchannel.Timeout, + TenantAuthenticationBackchannel.MaximumDocumentBytes, + "Tenant authentication metadata refused.", + cancel); } } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index e8f5f657..c88df1ff 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -1,5 +1,7 @@ using LearnStack.Api.Authentication; +using System.ComponentModel.DataAnnotations; using LearnStack.Api.Common; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Entitlements; using LearnStack.SharedKernel.Localization; @@ -11,7 +13,11 @@ namespace LearnStack.Api.Platform; /// The body of a killswitch toggle. /// The state to set; required. /// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. -internal sealed record KillswitchToggleRequest(bool? Enabled, string? Ticket); +internal sealed record KillswitchToggleRequest( + [property: Required] bool? Enabled, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(@"^[A-Za-z0-9._:/#-]{1,64}$")] + string? Ticket); /// What a toggle changed, with the correlation id the operator records. internal sealed record KillswitchToggleResponse(string Key, bool Before, bool After, string? CorrelationId); @@ -66,6 +72,7 @@ private static async Task ToggleKillswitchAsync( HttpContext http, IPlatformOperatorGate gate, IKillswitchToggle toggle, + ILoggerFactory loggerFactory, CancellationToken cancellationToken) { var witness = http.Features.Get()?.Witness; @@ -74,12 +81,9 @@ private static async Task ToggleKillswitchAsync( return Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); } - if (body?.Enabled is not { } enabled) - { - return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); - } - - var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body.Ticket, cancellationToken); + // Admission first: an operator without the grant learns nothing about the body, so a + // malformed request is answered 400 only to someone who may act at all. + var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body?.Ticket, cancellationToken); if (!admission.IsAdmitted) { return admission.Refusal switch @@ -90,6 +94,11 @@ private static async Task ToggleKillswitchAsync( }; } + if (body?.Enabled is not { } enabled) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + try { var result = await toggle.ToggleAsync(admission.Admission!, new KillswitchKey(key), enabled, cancellationToken); @@ -97,12 +106,24 @@ private static async Task ToggleKillswitchAsync( ? Results.Ok(new KillswitchToggleResponse(key, result.Before, result.After, admission.Admission!.Operator.CorrelationId)) : Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"); } - catch (AuditWriteFailedException) + catch (AuditWriteFailedException failure) { + // A MUST row that cannot be written refuses the act, and the refusal is a signal: + // an error line and a counter an operator can alert on, and a Retry-After like + // every other 503 the API answers. + PlatformOperatorMetrics.AuditFailed(PlatformOperations.KillswitchToggle); + LogAuditRefused(loggerFactory.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), failure); + RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); } } + private static readonly Action LogAuditRefused = + LoggerMessage.Define( + LogLevel.Error, + new EventId(7105, nameof(LogAuditRefused)), + "A platform operator act was refused because its audit row could not be written."); + private static IResult Problem(HttpContext http, int status, string key) => Results.Json( ProblemDetailsFactory.For(new Error(new LocalizedMessage(key)), http), diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index da1dcc0c..07cfcebf 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -443,8 +443,8 @@ public async Task WritePlatformOperatorResultAsync( || entry.ActorUserId is not null || entry.Outcome != AuditOutcome.Success || entry.OperationClass != OperationClass.Must - || entry.Metadata is null - || !entry.Metadata.Contains(admission.Operator.SubjectDigest, StringComparison.Ordinal)) + || !string.Equals(entry.CorrelationId, admission.Operator.CorrelationId, StringComparison.Ordinal) + || !MetadataNamesAdmittedOperator(entry, admission)) { throw new ArgumentException( "The platform operator result row does not match its admission.", nameof(entry)); @@ -469,6 +469,54 @@ public async Task WritePlatformOperatorResultAsync( } } + /// + /// Whether metadata.operator names exactly the admitted issuer and subject digest, + /// and carries a ticket only on a sentinel-tenant row, and only the admitted one. + /// + /// + /// A substring search would accept a row whose digest appeared anywhere, in a field an + /// operator can influence; the parse reads the one place the attribution lives. + /// + private static bool MetadataNamesAdmittedOperator(AuditEntryDraft entry, PlatformAdmission admission) + { + if (entry.Metadata is null) + { + return false; + } + + try + { + using var document = JsonDocument.Parse(entry.Metadata); + if (document.RootElement.ValueKind != JsonValueKind.Object + || !document.RootElement.TryGetProperty("operator", out var op) + || op.ValueKind != JsonValueKind.Object + || !StringIs(op, "subjectDigest", admission.Operator.SubjectDigest) + || !StringIs(op, "issuer", admission.Operator.Issuer)) + { + return false; + } + + if (!op.TryGetProperty("ticket", out _)) + { + return true; + } + + // The ticket appears only in sentinel-tenant rows, which no tenant can read. + return entry.TenantId == TenantId.PlatformSentinel + && admission.Ticket is not null + && StringIs(op, "ticket", admission.Ticket); + } + catch (JsonException) + { + return false; + } + } + + private static bool StringIs(JsonElement parent, string name, string expected) => + parent.TryGetProperty(name, out var value) + && value.ValueKind == JsonValueKind.String + && string.Equals(value.GetString(), expected, StringComparison.Ordinal); + /// public async Task WriteEventTerminalAsync( AuditEntryDraft entry, diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index fd45456b..b256024c 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -126,6 +126,21 @@ public async Task EnterAsync( BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); + // 0. The admission is short lived and single use. A stale one, or one already spent, + // never reaches a connection: the grant was evaluated for a moment and an act, and + // a kept or replayed proof would turn that into a standing capability. + if ((_clock.UtcNow - admission.IssuedAt).Duration() > PlatformAdmission.MaximumAge) + { + throw new InvalidOperationException( + "The platform admission is stale. An act asks the gate again rather than reusing a proof."); + } + + if (!admission.TryConsume()) + { + throw new InvalidOperationException( + "The platform admission was already used to enter a scope. One admission opens one scope."); + } + // 1. The catalogue's own declarations, before the connection. They fix the tier and // the operation type, so the rows and `docs/modules/tenancy/audit.md` cannot say // different things, and an absent declaration is refused here rather than papered @@ -174,6 +189,7 @@ public async Task EnterAsync( connection, current, (result, token) => WriteResultAsync(admission, declaredResult, result, connection, current, token), + () => PlatformOperatorMetrics.Result(admission.Operation), _logger); } catch @@ -274,7 +290,6 @@ private async Task WriteResultAsync( await services.ServiceProvider .GetRequiredService() .WritePlatformOperatorResultAsync(draft, admission, connection, transaction, cancellationToken); - PlatformOperatorMetrics.Result(admission.Operation); } /// @@ -370,22 +385,54 @@ private static string ShortPath(string? path) "Platform-admin scope entered: {Reason} (from {Member} at {File}:{Line}). " + "Cross-tenant access under learnstack_platform, audit row {AuditEntryId}."); + /// + /// The bounded facade over one work transaction. + /// + /// + /// + /// One statement, a DML verb. A statement must start with SELECT, + /// INSERT, UPDATE, DELETE or WITH and contain no further + /// statement, so a caller cannot send COMMIT, SET or BEGIN through the + /// facade and end or reshape the transaction the result row is bound to. This is a guard + /// against a mistake by trusted code, not a sandbox: the architecture rules decide who may + /// hold a handle at all. + /// + /// + /// A result row, and no failed statement, before the commit. A state change that + /// commits without its MUST row is the failure this scope exists to prevent, and a + /// statement that threw leaves PostgreSQL's transaction aborted, so a later commit would + /// silently roll back. A read-only scope has nothing to commit and ends by disposal. + /// + /// private sealed class Handle( NpgsqlConnection connection, NpgsqlTransaction transaction, Func writeResult, + Action onCommitted, ILogger logger) : IPlatformAdminScopeHandle { + private static readonly string[] StatementVerbs = ["SELECT", "INSERT", "UPDATE", "DELETE", "WITH"]; + private bool _resolved; private bool _disposed; + private bool _faulted; + private bool _resultWritten; public async Task ExecuteAsync( string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) { EnsureUsable(); await using var command = Build(sql, parameters); - return await command.ExecuteNonQueryAsync(cancellationToken); + try + { + return await command.ExecuteNonQueryAsync(cancellationToken); + } + catch + { + _faulted = true; + throw; + } } public async Task> QueryAsync( @@ -397,28 +444,53 @@ public async Task> QueryAsync( EnsureUsable(); ArgumentNullException.ThrowIfNull(map); await using var command = Build(sql, parameters); - await using var reader = await command.ExecuteReaderAsync(cancellationToken); - var rows = new List(); - while (await reader.ReadAsync(cancellationToken)) + try { - rows.Add(map(reader)); - } + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + var rows = new List(); + while (await reader.ReadAsync(cancellationToken)) + { + rows.Add(map(reader)); + } - return rows; + return rows; + } + catch + { + _faulted = true; + throw; + } } - public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + public async Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) { EnsureUsable(); - return writeResult(result, cancellationToken); + try + { + await writeResult(result, cancellationToken); + } + catch + { + _faulted = true; + throw; + } + + _resultWritten = true; } public async Task CommitAsync(CancellationToken cancellationToken = default) { EnsureUsable(); + if (!_resultWritten) + { + throw new InvalidOperationException( + "A platform scope commits only after its MUST result row is written. An act with " + + "nothing to record ends by disposal, which rolls back."); + } _resolved = true; await transaction.CommitAsync(cancellationToken); + onCommitted(); // The connection closes at completion, not at disposal: nothing may run on a // connection that sees every tenant once its transaction is over. @@ -472,7 +544,7 @@ private async ValueTask CloseAsync() private NpgsqlCommand Build(string sql, IReadOnlyList? parameters) { - ArgumentException.ThrowIfNullOrWhiteSpace(sql); + RequireOneStatement(sql); var command = new NpgsqlCommand(sql, connection, transaction); if (parameters is not null) { @@ -485,6 +557,25 @@ private NpgsqlCommand Build(string sql, IReadOnlyList? par return command; } + private static void RequireOneStatement(string sql) + { + ArgumentException.ThrowIfNullOrWhiteSpace(sql); + var text = sql.AsSpan().Trim(); + if (text.EndsWith(";")) + { + text = text[..^1].TrimEnd(); + } + + var verbEnd = text.IndexOfAny(" \t\r\n("); + var verb = (verbEnd < 0 ? text : text[..verbEnd]).ToString(); + if (text.Contains(';') || !StatementVerbs.Contains(verb, StringComparer.OrdinalIgnoreCase)) + { + throw new ArgumentException( + "A platform scope statement is a single SELECT, INSERT, UPDATE, DELETE or WITH statement.", + nameof(sql)); + } + } + private void EnsureUsable() { ObjectDisposedException.ThrowIf(_disposed, this); @@ -496,6 +587,13 @@ private void EnsureUsable() + "A caller needing further cross-tenant work takes a fresh scope: the " + "connection bypasses Row Level Security and is closed at completion."); } + + if (_faulted) + { + throw new InvalidOperationException( + "A statement of this platform-admin scope failed, so its transaction can only be abandoned. " + + "Dispose the scope; the work rolls back."); + } } } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs index 4e42415f..8ab7b6f9 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs @@ -1,4 +1,5 @@ using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Time; using Microsoft.Extensions.Logging; namespace LearnStack.Infrastructure.PlatformOperator; @@ -21,9 +22,11 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// public sealed partial class PlatformOperatorGate( IPlatformOperatorGrantSource grants, + IClock clock, ILogger logger) : PlatformAdmission.Minter, IPlatformOperatorGate { private readonly IPlatformOperatorGrantSource _grants = grants ?? throw new ArgumentNullException(nameof(grants)); + private readonly IClock _clock = clock ?? throw new ArgumentNullException(nameof(clock)); private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); /// @@ -54,7 +57,7 @@ public async ValueTask AdmitAsync( } PlatformOperatorMetrics.Admitted(operation); - return PlatformAdmissionResult.Admit(Mint(operatorWitness, operation, ticket)); + return PlatformAdmissionResult.Admit(Mint(operatorWitness, operation, ticket, _clock.UtcNow)); } private PlatformAdmissionResult Refuse( diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index 2d33d342..e5e64204 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -4,21 +4,51 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// Counters a monitoring owner can alert on without searching logs (ADR-0101 § 14). +/// +/// Names follow the platform convention (learnstack_*_total, Standard 10), and every +/// label is a closed set: an operation slug, a refusal cause or a token-failure cause, never a +/// value a caller wrote. +/// public static class PlatformOperatorMetrics { /// The meter name; covered by the host's learnstack.* subscription. public const string MeterName = "learnstack.platform_operator"; + /// Admissions by outcome and operation. + public const string AdmissionCounterName = "learnstack_platform_operator_admissions_total"; + + /// Refusals by cause, at the gate and before it. + public const string RefusalCounterName = "learnstack_platform_operator_refusals_total"; + + /// MUST result rows committed, by operation. + public const string ResultCounterName = "learnstack_platform_operator_results_total"; + + /// Acts refused with 503 because a MUST row could not be written, by operation. + public const string AuditFailureCounterName = "learnstack_platform_operator_audit_failures_total"; + + /// Issuer metadata or key fetches that failed or were refused (no label). + public const string MetadataFailureCounterName = "learnstack_platform_operator_metadata_failures_total"; + private static readonly Meter Meter = new(MeterName); private static readonly Counter Admissions = - Meter.CreateCounter("learnstack.platform_operator.admissions", description: "Operator admissions by outcome and operation."); + Meter.CreateCounter(AdmissionCounterName, description: "Operator admissions by outcome and operation."); private static readonly Counter Refusals = - Meter.CreateCounter("learnstack.platform_operator.refusals", description: "Operator refusals by cause."); + Meter.CreateCounter(RefusalCounterName, description: "Operator refusals by cause."); private static readonly Counter Results = - Meter.CreateCounter("learnstack.platform_operator.results", description: "MUST result rows written by operation."); + Meter.CreateCounter(ResultCounterName, description: "MUST result rows committed by operation."); + + private static readonly Counter AuditFailures = + Meter.CreateCounter(AuditFailureCounterName, description: "Operator acts refused because the MUST row was not durable."); + + private static readonly Counter MetadataFailures = + Meter.CreateCounter( + MetadataFailureCounterName, description: "Operator issuer metadata or key fetches that failed or were refused."); + + /// Counts a failed or refused issuer metadata fetch; every operator is refused while it persists. + public static void MetadataFailed() => MetadataFailures.Add(1); /// Counts an admission. public static void Admitted(PlatformOperation operation) => @@ -37,7 +67,11 @@ public static void Refused(PlatformRefusal refusal, PlatformOperation? operation public static void Unauthenticated(string cause) => Refusals.Add(1, new KeyValuePair("cause", cause)); - /// Counts a written result row. + /// Counts a result row that committed with its state change. public static void Result(PlatformOperation operation) => Results.Add(1, new KeyValuePair("operation", operation.AuditSlug)); + + /// Counts an act that was refused because its MUST row could not be written. + public static void AuditFailed(PlatformOperation operation) => + AuditFailures.Add(1, new KeyValuePair("operation", operation.AuditSlug)); } diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs index 796edd59..60b09c78 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformAdmission.cs @@ -7,7 +7,9 @@ namespace LearnStack.SharedKernel.Platform; /// /// It binds the operator, the operation, the optional ticket and the correlation id, so the /// scope, the audit rows and the result method take them from here and no caller can supply -/// or forge them. It is short lived: the gate mints it at the act and nothing stores it. +/// or forge them. It is short lived and single use: the gate stamps the time it minted it, +/// the scope refuses one older than , and the scope consumes it on +/// entry so a retained admission cannot open a second privileged scope. /// /// /// The census is closed to the operator gate by an architecture rule. @@ -15,13 +17,20 @@ namespace LearnStack.SharedKernel.Platform; /// public sealed class PlatformAdmission { - private PlatformAdmission(PlatformOperatorWitness operatorWitness, PlatformOperation operation, string? ticket) + /// The longest an admission may wait between the gate and the scope entry. + public static TimeSpan MaximumAge { get; } = TimeSpan.FromSeconds(30); + + private int _consumed; + + private PlatformAdmission( + PlatformOperatorWitness operatorWitness, PlatformOperation operation, string? ticket, DateTimeOffset issuedAt) { ArgumentNullException.ThrowIfNull(operatorWitness); ArgumentNullException.ThrowIfNull(operation); Operator = operatorWitness; Operation = operation; Ticket = ticket; + IssuedAt = issuedAt; } /// The authenticated operator. @@ -33,6 +42,15 @@ private PlatformAdmission(PlatformOperatorWitness operatorWitness, PlatformOpera /// The optional, grammar-checked ticket; it appears only in sentinel-tenant rows. public string? Ticket { get; } + /// When the gate minted this admission. + public DateTimeOffset IssuedAt { get; } + + /// + /// Spends the admission; true for exactly one caller. The platform scope calls it on entry, + /// so an admission that was kept, copied or replayed cannot open a second scope. + /// + public bool TryConsume() => Interlocked.Exchange(ref _consumed, 1) == 0; + /// public override string ToString() => nameof(PlatformAdmission); @@ -43,7 +61,10 @@ public abstract class Minter { /// Mints an admission after the gate has evaluated the grant. protected static PlatformAdmission Mint( - PlatformOperatorWitness operatorWitness, PlatformOperation operation, string? ticket) => - new(operatorWitness, operation, ticket); + PlatformOperatorWitness operatorWitness, + PlatformOperation operation, + string? ticket, + DateTimeOffset issuedAt) => + new(operatorWitness, operation, ticket, issuedAt); } } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs index 286e6b86..33952c80 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs @@ -4,6 +4,7 @@ using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Logging; namespace LearnStack.Modules.Tenancy.Infrastructure; @@ -14,29 +15,40 @@ namespace LearnStack.Modules.Tenancy.Infrastructure; /// /// /// Order. Resolve the key from only, enter the scope -/// (which records its entry first), read the before state, upsert, write the MUST result row -/// on the work transaction, commit, and only then remove the overlay cache entry. Removing -/// before the commit would let a concurrent load repopulate the stale value; removing after -/// a commit whose outcome is unknown still happens, because the flip may have landed. +/// (which records its entry first), make sure the row exists, lock it and read the before +/// state, update it, write the MUST result row on the work transaction, commit, and only then +/// remove the overlay cache entry. Removing before the commit would let a concurrent load +/// repopulate the stale value; removing after a commit whose outcome is unknown still happens, +/// because the flip may have landed. +/// +/// +/// The first toggle of a key cannot race. SELECT … FOR UPDATE locks nothing when no +/// row exists, so two first toggles would both read the registry default as their before state. +/// The row is therefore created at its default with ON CONFLICT DO NOTHING first; the +/// lock and the read then see one row, and the loser reads the winner's committed state. /// /// /// What it does not do. It cannot reach other instances: the cache is process-local /// and the overlay refreshes within . The runbook -/// states that lag. Concurrent toggles are last writer wins; the row has no version. +/// states that lag. Concurrent toggles serialise on the row lock, so each one's before state is +/// the previous one's after state. /// /// -public sealed class KillswitchToggle( +public sealed partial class KillswitchToggle( IPlatformAdminScope scope, ICacheService cache, - IClock clock) : IKillswitchToggle + IClock clock, + ILogger logger) : IKillswitchToggle { + private const string EnsureRow = + "INSERT INTO platform_killswitches (key, is_enabled, reason, toggled_at, toggled_by) " + + "VALUES (@key, @default, NULL, @at, NULL) ON CONFLICT (key) DO NOTHING"; + private const string SelectBefore = "SELECT is_enabled FROM platform_killswitches WHERE key = @key FOR UPDATE"; - private const string Upsert = - "INSERT INTO platform_killswitches (key, is_enabled, reason, toggled_at, toggled_by) " - + "VALUES (@key, @enabled, @reason, @at, NULL) " - + "ON CONFLICT (key) DO UPDATE SET is_enabled = EXCLUDED.is_enabled, " - + "reason = EXCLUDED.reason, toggled_at = EXCLUDED.toggled_at, toggled_by = NULL"; + private const string Update = + "UPDATE platform_killswitches SET is_enabled = @enabled, reason = @reason, " + + "toggled_at = @at, toggled_by = NULL WHERE key = @key"; /// public async Task ToggleAsync( @@ -58,20 +70,30 @@ public async Task ToggleAsync( { await using var handle = await scope.EnterAsync(admission, cancellationToken); + var at = clock.UtcNow; + await handle.ExecuteAsync( + EnsureRow, + [ + new PlatformSqlParameter("key", key.Value), + new PlatformSqlParameter("default", registryDefault), + new PlatformSqlParameter("at", at), + ], + cancellationToken); + var rows = await handle.QueryAsync( SelectBefore, [new PlatformSqlParameter("key", key.Value)], reader => reader.GetBoolean(0), cancellationToken); - var before = rows.Count == 0 ? registryDefault : rows[0]; + var before = rows[0]; await handle.ExecuteAsync( - Upsert, + Update, [ new PlatformSqlParameter("key", key.Value), new PlatformSqlParameter("enabled", enabled), new PlatformSqlParameter("reason", admission.Ticket), - new PlatformSqlParameter("at", clock.UtcNow), + new PlatformSqlParameter("at", at), ], cancellationToken); @@ -84,8 +106,10 @@ await handle.WriteResultAsync( State(enabled)), cancellationToken); + // Past the point where the caller's abort matters: a cancelled commit leaves its + // outcome unknown, which is the state this order is built to avoid. commitAttempted = true; - await handle.CommitAsync(cancellationToken); + await handle.CommitAsync(CancellationToken.None); return new KillswitchToggleResult(KillswitchToggleOutcome.Applied, key, before, enabled); } finally @@ -108,9 +132,17 @@ private async Task RemoveCacheAsync() { await cache.RemoveAsync(CacheKey.ForKillswitchOverlay(), CancellationToken.None); } - catch (InvalidOperationException) + catch (Exception failure) when (failure is not OperationCanceledException) { - // The cache is an optimisation here; the overlay TTL bounds the lag. + // The cache is an optimisation here; the overlay TTL bounds the lag. The failure + // is still worth a line: a store that cannot remove is a store that serves stale. + LogCacheRemovalFailed(logger, failure); } } + + [LoggerMessage( + EventId = 7104, + Level = LogLevel.Warning, + Message = "The killswitch overlay cache entry could not be removed after a toggle; it expires within the overlay TTL.")] + private static partial void LogCacheRemovalFailed(ILogger logger, Exception failure); } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs index 33f80235..c9c8e5d4 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs @@ -75,9 +75,8 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) public DbSet PlatformHostMappings => Set(); /// - /// The killswitch overlay. Read-only in this packet — no writer exists, because every - /// toggle runs inside a scope whose registered gate refuses everyone (ADR-0045 - /// Amendment 1 § 4). + /// The killswitch overlay. This context only reads it: the one writer is + /// KillswitchToggle, which runs inside an admitted platform scope (ADR-0101 § 13). /// public DbSet PlatformKillswitches => Set(); diff --git a/backend/tests/Fixtures/TestPlatformAdmissions.cs b/backend/tests/Fixtures/TestPlatformAdmissions.cs index 89363cb3..7a9b62a9 100644 --- a/backend/tests/Fixtures/TestPlatformAdmissions.cs +++ b/backend/tests/Fixtures/TestPlatformAdmissions.cs @@ -19,8 +19,13 @@ internal static PlatformAdmission Admission( PlatformOperation? operation = null, string? ticket = null, string subject = "operator-1", - string? correlationId = "00-test-trace-01") => - AdmissionMinter.Create(Witness(subject, correlationId), operation ?? PlatformOperations.KillswitchToggle, ticket); + string? correlationId = "00-test-trace-01", + DateTimeOffset? issuedAt = null) => + AdmissionMinter.Create( + Witness(subject, correlationId), + operation ?? PlatformOperations.KillswitchToggle, + ticket, + issuedAt ?? DateTimeOffset.UtcNow); private sealed class WitnessMinter : PlatformOperatorWitness.Minter { @@ -32,7 +37,7 @@ internal static PlatformOperatorWitness Create( private sealed class AdmissionMinter : PlatformAdmission.Minter { internal static PlatformAdmission Create( - PlatformOperatorWitness witness, PlatformOperation operation, string? ticket) => - Mint(witness, operation, ticket); + PlatformOperatorWitness witness, PlatformOperation operation, string? ticket, DateTimeOffset issuedAt) => + Mint(witness, operation, ticket, issuedAt); } } diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 8f3d3b65..46b0108f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Text.RegularExpressions; using FluentAssertions; using LearnStack.Api.Messaging; using LearnStack.Infrastructure.Messaging; @@ -13,7 +14,7 @@ namespace LearnStack.Tests.Architecture; /// /// The rules that keep the one BYPASSRLS credential reachable from one place. /// -public sealed class PlatformAdminScopeConventionTests +public sealed partial class PlatformAdminScopeConventionTests { /// /// Every LearnStack.* assembly under backend/src, loaded without a @@ -167,23 +168,44 @@ public void PlatformAdminScope_Entry_Requires_Platform_Permission() // assembly, not just the one declaring the types: a permissive minter or gate would // be registered somewhere else, for a demo, and that is exactly where a narrowed scan // would not look. Test assemblies are not scanned, so a test double does not widen it. + // Abstract subclasses count: a census that skipped them would let a permissive abstract minter + // stand in the assembly for a test or a later edit to complete. Full names, not simple ones, + // so a lookalike in another namespace is a different (and failing) entry. var types = ProductionAssemblies().SelectMany(assembly => assembly.GetTypes()) - .Where(type => type is { IsAbstract: false, IsInterface: false }).ToList(); + .Where(type => !type.IsInterface).ToList(); - Names(types, typeof(PlatformAdmission.Minter)).Should().BeEquivalentTo( - [nameof(PlatformOperatorGate)], + FullNames(types, typeof(PlatformAdmission.Minter)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], "only the gate mints an admission, after it has evaluated a grant"); - Names(types, typeof(PlatformOperatorWitness.Minter)).Should().BeEquivalentTo( - ["PlatformOperatorWitnessMinter"], - "only the operator authentication boundary mints a witness; the rebind tool joins in " - + "Step 3 by an edit to this list, not by accident"); - Names(types, typeof(IPlatformOperatorGate)).Should().BeEquivalentTo( - [nameof(PlatformOperatorGate)], "a second gate is how a permissive default ships"); - Names(types, typeof(IPlatformOperatorGrantSource)).Should().BeEquivalentTo( - [nameof(ConfigurationPlatformOperatorGrantSource)], + FullNames(types, typeof(PlatformOperatorWitness.Minter)).Should().BeEquivalentTo( + ["LearnStack.Api.Authentication.PlatformOperatorTokenProfile+WitnessMinter"], + "only the operator token profile mints a witness, through a private nested minter; the rebind " + + "tool joins in Step 3 by an edit to this list, not by accident"); + FullNames(types, typeof(IPlatformOperatorGate)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], + "a second gate is how a permissive default ships"); + FullNames(types, typeof(IPlatformOperatorGrantSource)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.ConfigurationPlatformOperatorGrantSource"], "a second grant source is how a permissive grant ships; the table adapter joins on its trigger"); } + [Fact] + public void The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only() + { + // The witness is evidence that a token passed the profile. TryRead is the only door to the + // minter, so who may call it is the question: the scheme's TokenValidated event, which lives + // beside it, and nothing else in production code. The real-realm test and the offline rebind + // tool (Step 3) are the sanctioned further callers, the latter added here by name. + const string Boundary = "LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs"; + + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile", except: null) + .Should().Equal([Boundary], "no other source file may name the profile that mints a witness"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile.TryRead(", except: null) + .Should().Equal([Boundary]); + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorWitness.Minter", except: null) + .Should().Equal([Boundary], "the witness minter base is named by its one nested subclass"); + } + [Fact] public void Only_The_Operator_Services_Hold_The_Platform_Scope() { @@ -191,42 +213,95 @@ public void Only_The_Operator_Services_Hold_The_Platform_Scope() // from nowhere else. A request handler holding it would enter a cross-tenant scope // from a tenant request path, which the marker rules forbid for a platform entry. SourceScan.FilesContaining(SourceScan.SourceRoot, "IPlatformAdminScope", except: null) - .Select(Path.GetFileName) .Should().BeEquivalentTo( [ - "IPlatformAdminScope.cs", - "PlatformAdminScope.cs", - "PersistenceCompositionExtensions.cs", - "KillswitchToggle.cs", + "LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs", + ScopeFile, + CompositionFile, + KillswitchWriterFile, ], "each new operator service is added here deliberately, with its denied proof"); } + private const string KillswitchWriterFile = + "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; + [Fact] public void Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer() { - // ADR-0101 § 13: the overlay reads the table, so a rule on every mention would be - // wrong; the confinement is on the write verbs. The writer upserts, so INSERT is the - // literal that must be present and UPDATE/DELETE the ones that must stay absent. - var writers = KillswitchWriteVerbs - .SelectMany(verb => SourceScan.FilesContaining(SourceScan.SourceRoot, verb, except: null)) - .Select(Path.GetFileName) - .Distinct() - .ToList(); + // ADR-0101 § 13: the overlay reads the table, so a rule on every mention would be wrong; the + // confinement is on the write verbs, in any case, with an optional schema and quotes. The + // writer inserts the default row, locks it and updates it, so those two verbs must be present + // and DELETE and TRUNCATE must stay absent everywhere (the tests that clean up use the scope, + // outside backend/src). + var offenders = new List(); + var sawWriter = false; + foreach (var file in Directory.EnumerateFiles(SourceScan.SourceRoot, "*.cs", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(SourceScan.SourceRoot, file).Replace(Path.DirectorySeparatorChar, '/'); + if (relative.Split('/') is var segments && (segments.Contains("obj") || segments.Contains("bin"))) + { + continue; + } + + var code = SourceText.WithoutComments(File.ReadAllText(file)); + if (KillswitchWrite().IsMatch(code)) + { + offenders.Add(relative); + sawWriter |= relative == KillswitchWriterFile; + } + } + + sawWriter.Should().BeTrue("the premise: the sweep read the writer's own statements"); + offenders.Should().Equal([KillswitchWriterFile], "the writer alone writes the table"); + + var writer = SourceText.WithoutComments(File.ReadAllText( + Path.Combine(SourceScan.SourceRoot, KillswitchWriterFile.Replace('/', Path.DirectorySeparatorChar)))); + KillswitchWrite().Matches(writer).Select(match => match.Groups["verb"].Value.ToUpperInvariant().Split(' ')[0]) + .Distinct().Should().BeEquivalentTo(["INSERT", "UPDATE"], "the writer never deletes or truncates"); + } + + [Fact] + public void The_Killswitch_Write_Pattern_Can_Fail_And_Catches_The_Ordinary_Spellings() + { + // The rule above passes whether its pattern works or matches nothing, so the shapes it must + // catch and the ones it must not are checked against the pattern directly. + foreach (var caught in new[] + { + "INSERT INTO platform_killswitches (key) VALUES (@k)", + "insert into platform_killswitches", + "UPDATE platform_killswitches SET is_enabled = true", + "update only public.platform_killswitches set x = 1", + "UPDATE \"public\".\"platform_killswitches\" SET x = 1", + "DELETE FROM platform_killswitches", + "delete from only \"platform_killswitches\"", + "TRUNCATE platform_killswitches", + "truncate table public.platform_killswitches", + }) + { + KillswitchWrite().IsMatch(caught).Should().BeTrue(caught); + } - writers.Should().BeEquivalentTo(["KillswitchToggle.cs"], "the writer alone writes the table"); + foreach (var ignored in new[] + { + "SELECT is_enabled FROM platform_killswitches WHERE key = @k FOR UPDATE", + "INSERT INTO platform_killswitches_archive (key) VALUES (@k)", + "UPDATE platform_killswitches2 SET x = 1", + "GRANT SELECT, INSERT, UPDATE ON platform_killswitches TO learnstack_platform", + }) + { + KillswitchWrite().IsMatch(ignored).Should().BeFalse(ignored); + } } - private static readonly string[] KillswitchWriteVerbs = - [ - "INSERT INTO platform_killswitches", - "UPDATE platform_killswitches", - "DELETE FROM platform_killswitches", - "TRUNCATE platform_killswitches", - ]; + [GeneratedRegex( + @"\b(?INSERT\s+INTO|UPDATE|DELETE\s+FROM|TRUNCATE(?:\s+TABLE)?)(?:\s+ONLY)?\s+(?:""?[A-Za-z_][A-Za-z0-9_]*""?\s*\.\s*)?""?platform_killswitches""?(?![A-Za-z0-9_])", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex KillswitchWrite(); - private static List Names(IEnumerable types, Type baseType) => - types.Where(baseType.IsAssignableFrom).Select(type => type.Name).Distinct().ToList(); + private static List FullNames(IEnumerable types, Type baseType) => + types.Where(type => type != baseType && baseType.IsAssignableFrom(type)) + .Select(type => type.FullName!).Distinct().ToList(); [Fact] public void The_Platform_Scope_Writes_No_Tenant_Context_And_Sets_No_Session_Variable() diff --git a/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs new file mode 100644 index 00000000..1399e8ad --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs @@ -0,0 +1,188 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Modules.Tenancy.Infrastructure; +using LearnStack.SharedKernel.Caching; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The order of the killswitch writer's steps and the failure branches around its commit, decided +/// against a scripted scope so a commit that faults can be produced exactly (ADR-0101 § 13). +/// +/// +/// No Docker. The real-database behaviour (row lock, both audit rows, rollback) is asserted in +/// ; what a stub can show and a database cannot is the writer's +/// reaction to a commit whose outcome is unknown. +/// +public sealed class KillswitchToggleOrderingTests +{ + private static readonly KillswitchKey Key = KillswitchKeys.AnalyticsIngestEnabled; + + [Fact] + public async Task A_Commit_Whose_Outcome_Is_Unknown_Still_Drops_The_Cache_And_Reaches_The_Caller() + { + // The flip may have landed. A stale overlay entry must not outlive a commit that might have + // happened, and the caller must see the failure rather than an Applied it cannot trust. + var handle = new ScriptedHandle { CommitFailure = new TimeoutException("the commit reply never came") }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync(); + cache.Removed.Should().Be(1); + handle.Disposed.Should().BeTrue("the scope is released whatever the commit did"); + } + + [Fact] + public async Task A_Failure_Before_The_Commit_Leaves_The_Cache_Alone() + { + var handle = new ScriptedHandle { ResultFailure = new LearnStack.SharedKernel.Audit.AuditWriteFailedException("no row") }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync(); + cache.Removed.Should().Be(0, "nothing was committed, so nothing is stale"); + handle.CommitCalls.Should().Be(0); + } + + [Fact] + public async Task The_Commit_Is_Not_Cancellable_By_The_Caller() + { + // Past the point where the caller's abort could matter, a cancelled commit would leave its + // outcome unknown, which is the state this order exists to avoid. + var handle = new ScriptedHandle(); + using var abort = new CancellationTokenSource(); + await abort.CancelAsync(); + + await Toggle(handle, new CountingCache()).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false, abort.Token); + + handle.CommitToken.CanBeCanceled.Should().BeFalse(); + } + + [Fact] + public async Task A_Cache_That_Cannot_Remove_Is_Logged_And_Does_Not_Fail_The_Applied_Toggle() + { + var handle = new ScriptedHandle(); + var logger = new CapturingLogger(); + var cache = new CountingCache { Failure = new TimeoutException("cache down") }; + var toggle = new KillswitchToggle(new ScriptedScope(handle), cache, new SystemClock(), logger); + + var result = await toggle.ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + result.Outcome.Should().Be(KillswitchToggleOutcome.Applied, "the flip committed; the cache is an optimisation"); + logger.EventIds.Should().Contain(7104, "a store that cannot remove is a store that serves stale"); + } + + [Fact] + public async Task The_Writer_Creates_Locks_Reads_Updates_Records_And_Only_Then_Commits_In_That_Order() + { + var handle = new ScriptedHandle(); + + await Toggle(handle, new CountingCache()).ToggleAsync(TestPlatformAdmissions.Admission(ticket: "INC-3"), Key, false); + + handle.Steps.Should().Equal("exec:INSERT", "query:SELECT", "exec:UPDATE", "result", "commit"); + handle.Statements[1].Should().EndWith("FOR UPDATE", "the read takes the row lock the update then holds"); + } + + private static KillswitchToggle Toggle(ScriptedHandle handle, CountingCache cache) => + new(new ScriptedScope(handle), cache, new SystemClock(), NullLogger.Instance); + + private sealed class ScriptedScope(ScriptedHandle handle) : IPlatformAdminScope + { + public Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + string? callerMember = null, string? callerFile = null, int callerLine = 0) => + Task.FromResult(handle); + } + + private sealed class ScriptedHandle : IPlatformAdminScopeHandle + { + public Exception? CommitFailure { get; init; } + public Exception? ResultFailure { get; init; } + public List Steps { get; } = []; + public List Statements { get; } = []; + public int CommitCalls { get; private set; } + public CancellationToken CommitToken { get; private set; } + public bool Disposed { get; private set; } + + public Task ExecuteAsync( + string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) + { + Steps.Add("exec:" + sql.Split(' ')[0]); + Statements.Add(sql); + return Task.FromResult(1); + } + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) + { + Steps.Add("query:" + sql.Split(' ')[0]); + Statements.Add(sql); + return Task.FromResult>((IReadOnlyList)(object)new List { true }); + } + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + { + Steps.Add("result"); + return ResultFailure is null ? Task.CompletedTask : Task.FromException(ResultFailure); + } + + public Task CommitAsync(CancellationToken cancellationToken = default) + { + Steps.Add("commit"); + CommitCalls++; + CommitToken = cancellationToken; + return CommitFailure is null ? Task.CompletedTask : Task.FromException(CommitFailure); + } + + public ValueTask DisposeAsync() + { + Disposed = true; + return ValueTask.CompletedTask; + } + } + + private sealed class CountingCache : ICacheService + { + public int Removed { get; private set; } + public Exception? Failure { get; init; } + + public Task RemoveAsync(string key, CancellationToken cancellationToken = default) + { + Removed++; + return Failure is null ? Task.CompletedTask : Task.FromException(Failure); + } + + public Task GetAsync(string key, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task GetOrSetAsync( + string key, Func> factory, CacheOptions? options = null, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task SetAsync(string key, T value, CacheOptions? options = null, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + } + + private sealed class CapturingLogger : ILogger + { + public List EventIds { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + EventIds.Add(eventId.Id); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index ba52c99a..08eff639 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -16,6 +16,7 @@ using LearnStack.Tests.Fixtures; using LearnStack.Modules.Tenancy.Infrastructure; using LearnStack.SharedKernel.Entitlements; +using System.Diagnostics.Metrics; namespace LearnStack.Tests.Integration.Database; @@ -245,7 +246,7 @@ public async Task A_Resolved_Handle_Cannot_Be_Used_Again_And_Exposes_No_Connecti await using var handle = await Build(dataSource).EnterAsync(Admission(), CancellationToken.None); (await ScalarAsync(handle, "SELECT pg_backend_pid()")).Should().BeGreaterThan(0); - await handle.CommitAsync(CancellationToken.None); + await CompleteAsync(handle); var execute = async () => await handle.ExecuteAsync("SELECT 1", null, CancellationToken.None); var query = async () => await ScalarAsync(handle, "SELECT 1"); @@ -278,7 +279,7 @@ await handle.ExecuteAsync( [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], CancellationToken.None); - await handle.CommitAsync(CancellationToken.None); + await CompleteAsync(handle); } await using var check = await scope.EnterAsync(Admission(), CancellationToken.None); @@ -292,7 +293,7 @@ await handle.ExecuteAsync( // The schema fixture is shared and other classes assert exact row counts. await using var cleanup = await scope.EnterAsync(Admission(), CancellationToken.None); await cleanup.ExecuteAsync("DELETE FROM platform_host_to_tenant WHERE host = @host", [new PlatformSqlParameter("host", host)], CancellationToken.None); - await cleanup.CommitAsync(CancellationToken.None); + await CompleteAsync(cleanup); } } @@ -326,20 +327,16 @@ public async Task A_Faulted_Commit_Returns_The_Connection_And_Is_Left_Indetermin await using (handle) { - var suicide = new Terminator(handle); + // The MUST row is written first so the commit is attempted, and the backend is + // ended from outside the facade, so the statement fault guard does not stop the + // commit short of the wire: this case is about a commit that itself faults. + var pid = await ScalarAsync(handle, "SELECT pg_backend_pid()"); + await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, null), + CancellationToken.None); + await using (var killer = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString)) { - - try - { - await suicide.ExecuteNonQueryAsync(CancellationToken.None); - } - catch (PostgresException) - { - // The server hangs up mid-statement; that is the point. - } - catch (NpgsqlException) - { - } + await ScalarAsync(killer, null, "SELECT pg_terminate_backend(@pid)", ("pid", pid)); } var commit = async () => await handle.CommitAsync(CancellationToken.None); @@ -585,7 +582,7 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin case "read-then-throw": throw new InvalidOperationException("the work failed after reading"); case "committed": - await handle.CommitAsync(); + await CompleteAsync(handle); break; } }; @@ -603,7 +600,9 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin _schema.Postgres.PlatformConnectionString); var survivors = await ScalarAsync( - afterwards, null, "SELECT count(*) FROM audit_log WHERE correlation_id = @correlation", ("correlation", correlation)); + afterwards, null, + "SELECT count(*) FROM audit_log WHERE correlation_id = @correlation AND operation = @entry", + ("correlation", correlation), ("entry", PlatformAdminScope.EnterOperation)); survivors.Should().Be(1, "entry into a cross-tenant scope is recorded whatever the work then does"); } @@ -658,10 +657,14 @@ public async Task A_Result_Row_Commits_With_The_Work_And_Carries_The_Operator_Bu var correlation = $"corr-{Guid.NewGuid():N}"; var admission = TestPlatformAdmissions.Admission(ticket: "INC-7", correlationId: correlation); + // A throwaway tenant id: the shared fixture tenants must keep the audit rows other classes + // count, and audit_log keeps no foreign key to tenants. + var target = Guid.CreateVersion7(); + await using (var handle = await Build(dataSource).EnterAsync(admission)) { await handle.WriteResultAsync(new PlatformResult( - TenantId.From(SchemaFixture.TenantA), "PlatformKillswitch", "key-1", "{\"isEnabled\":true}", "{\"isEnabled\":false}")); + TenantId.From(target), "PlatformKillswitch", "key-1", "{\"isEnabled\":true}", "{\"isEnabled\":false}")); await handle.CommitAsync(); } @@ -675,7 +678,7 @@ await handle.WriteResultAsync(new PlatformResult( entry.Actor.Should().BeNull("an operator is not a users row"); var result = rows.Single(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug); - result.Tenant.Should().Be(SchemaFixture.TenantA, "a tenant-targeted act is recorded under the real tenant"); + result.Tenant.Should().Be(target, "a tenant-targeted act is recorded under the real tenant"); result.Reason.Should().Be(PlatformOperations.KillswitchToggle.ReasonSlug); result.Actor.Should().BeNull(); using var metadata = System.Text.Json.JsonDocument.Parse(result.Metadata); @@ -718,8 +721,8 @@ public async Task A_Result_Row_That_Cannot_Be_Written_Fails_The_Act_And_Leaves_N var before = await ScalarAsync(read, null, "SELECT coalesce((SELECT is_enabled::text FROM platform_killswitches WHERE key = @k), 'absent')", ("k", key.Value)); - var act = async () => await new KillswitchToggle(scope, removals, new SystemClock()) - .ToggleAsync(TestPlatformAdmissions.Admission(), key, before != "false", CancellationToken.None); + var act = async () => await new KillswitchToggle(scope, removals, new SystemClock(), NullLogger.Instance) + .ToggleAsync(TestPlatformAdmissions.Admission(), key, before == "false", CancellationToken.None); await act.Should().ThrowAsync(); removals.Removed.Should().Be(0, "nothing committed, so nothing is stale"); @@ -740,7 +743,7 @@ public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_ return await ScalarAsync(independent, null, "SELECT is_enabled::text FROM platform_killswitches WHERE key = @k", ("k", key.Value)); }); - var toggle = new KillswitchToggle(scope, cache, new SystemClock()); + var toggle = new KillswitchToggle(scope, cache, new SystemClock(), NullLogger.Instance); var correlation = $"corr-{Guid.NewGuid():N}"; try @@ -763,14 +766,33 @@ public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_ (await ScalarAsync(read, null, "SELECT count(*) FROM platform_killswitches WHERE key = @k AND toggled_by IS NULL", ("k", key.Value))) .Should().Be(1, "an operator is not a users row, so toggled_by stays NULL"); - (await Rows(read, correlation)).Count(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug) - .Should().Be(2, "one MUST result row per flip"); + var results = (await Rows(read, correlation)) + .Where(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug).ToList(); + results.Should().HaveCount(2, "one MUST result row per flip"); + results.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null); + results.Should().OnlyContain(row => row.Reason == PlatformOperations.KillswitchToggle.ReasonSlug); + results[0].Before.Should().Contain("true"); + results[0].After.Should().Contain("false"); + results[1].Before.Should().Contain("false"); + results[1].After.Should().Contain("true"); + using var firstMetadata = System.Text.Json.JsonDocument.Parse(results[0].Metadata); + var operatorNode = firstMetadata.RootElement.GetProperty("operator"); + operatorNode.GetProperty("issuer").GetString().Should().Be(TestPlatformAdmissions.Issuer); + operatorNode.GetProperty("executor").GetString().Should().Be("operator.test"); + operatorNode.GetProperty("ticket").GetString().Should().Be("INC-9", + "a sentinel-tenant row is unreadable to every tenant, so it carries the ticket"); + using var secondMetadata = System.Text.Json.JsonDocument.Parse(results[1].Metadata); + secondMetadata.RootElement.GetProperty("operator").TryGetProperty("ticket", out _).Should().BeFalse(); + (await ScalarAsync(read, null, "SELECT toggled_at FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(30)); + (await ScalarAsync(read, null, "SELECT coalesce(reason, 'null') FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().Be("null", "the second flip carried no ticket, so the reason column is empty again"); } finally { await using var cleanup = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission()); await cleanup.ExecuteAsync("DELETE FROM platform_killswitches WHERE key = @k", [new PlatformSqlParameter("k", key.Value)]); - await cleanup.CommitAsync(); + await CompleteAsync(cleanup); } } @@ -781,7 +803,7 @@ public async Task An_Undeclared_Killswitch_Key_Enters_No_Scope_And_Writes_Nothin var correlation = $"corr-{Guid.NewGuid():N}"; var cache = new RecordingCache(); - var result = await new KillswitchToggle(Build(dataSource), cache, new SystemClock()).ToggleAsync( + var result = await new KillswitchToggle(Build(dataSource), cache, new SystemClock(), NullLogger.Instance).ToggleAsync( TestPlatformAdmissions.Admission(correlationId: correlation), new KillswitchKey("killswitch.not.declared"), false); result.Outcome.Should().Be(KillswitchToggleOutcome.UnknownKey); @@ -791,26 +813,33 @@ public async Task An_Undeclared_Killswitch_Key_Enters_No_Scope_And_Writes_Nothin } [Fact] - public async Task A_Result_Row_Cannot_Name_A_Different_Operation_Than_Its_Admission() + public async Task A_Result_Row_Cannot_Differ_From_Its_Admission_In_Any_Bound_Attribute() { - // The audit seam is witness-bound: a draft for another operation, a non-null actor or a - // missing operator digest is refused, whatever the caller composed. + // The audit seam is witness-bound: the operation, the closed reason, the correlation id, the + // outcome and class, the module, the tenant, the actor and the operator attribution in + // metadata.operator are all checked against the admission, whatever the caller composed. The + // accepted control comes first so a refusal below is the attribute's, not a broken fixture. await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); await using var store = AuditStoreScopeFactory().CreateAsyncScope(); var audit = store.ServiceProvider.GetRequiredService(); - var admission = TestPlatformAdmissions.Admission(); + var admission = TestPlatformAdmissions.Admission(ticket: "INC-1"); + var digest = admission.Operator.SubjectDigest; await using var connection = await dataSource.OpenConnectionAsync(); await using var transaction = await connection.BeginTransactionAsync(); - AuditEntryDraft Draft(string operation, UserId? actor, string metadata) => new() + string Metadata(string issuer, string? ticket = null) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + digest + "\",\"kind\":\"human\"" + + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + var good = new AuditEntryDraft { Id = AuditEntryId.From(Guid.CreateVersion7()), TenantId = TenantId.PlatformSentinel, OrganizationId = null, - ActorUserId = actor, + ActorUserId = null, ActorEmail = null, ModuleName = "tenancy", - Operation = operation, + Operation = admission.Operation.AuditSlug, OperationType = OperationType.SecurityEvent, OperationClass = OperationClass.Must, EntityType = null, @@ -821,31 +850,234 @@ public async Task A_Result_Row_Cannot_Name_A_Different_Operation_Than_Its_Admiss BeforeState = null, AfterState = null, Changes = null, - CorrelationId = "c", + CorrelationId = admission.Operator.CorrelationId, IpAddress = null, UserAgent = null, Timestamp = DateTimeOffset.UtcNow, - Metadata = metadata, + Metadata = Metadata(admission.Operator.Issuer), }; - var good = "{\"operator\":{\"subjectDigest\":\"" + admission.Operator.SubjectDigest + "\"}}"; - foreach (var draft in new[] + await audit.WritePlatformOperatorResultAsync(good, admission, connection, transaction); + await audit.WritePlatformOperatorResultAsync( + good with { Id = AuditEntryId.From(Guid.CreateVersion7()), Metadata = Metadata(admission.Operator.Issuer, "INC-1") }, + admission, connection, transaction); + + var refused = new Dictionary { - Draft("tenancy.other.operation", null, good), - Draft(admission.Operation.AuditSlug, UserId.From(Guid.CreateVersion7()), good), - Draft(admission.Operation.AuditSlug, null, "{}"), - }) + ["another operation"] = good with { Operation = "tenancy.other.operation" }, + ["a non-null actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["no metadata"] = good with { Metadata = null }, + ["the digest in the wrong place"] = good with + { + Metadata = "{\"note\":\"" + digest + "\",\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\"}}", + }, + ["another issuer"] = good with { Metadata = Metadata("https://elsewhere.example.test/realms/x") }, + ["an outcome of failure"] = good with { Outcome = AuditOutcome.Failed }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["another reason"] = good with { Reason = "other_reason" }, + ["the identity module"] = good with { ModuleName = "identity" }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["a ticket on a tenant row"] = good with + { + TenantId = TenantId.From(Guid.CreateVersion7()), + Metadata = Metadata(admission.Operator.Issuer, "INC-1"), + }, + ["a ticket the admission never held"] = good with { Metadata = Metadata(admission.Operator.Issuer, "INC-2") }, + }; + + foreach (var (attribute, draft) in refused) { var act = async () => await audit.WritePlatformOperatorResultAsync(draft, admission, connection, transaction); - await act.Should().ThrowAsync(); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + } + + [Fact] + public async Task Commit_Without_A_Result_Row_Is_Refused_And_The_Work_Rolls_Back() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"norow-{Guid.NewGuid():N}.example.com"; + + await using (var handle = await Build(dataSource).EnterAsync(Admission())) + { + await InsertHostAsync(handle, host); + + var commit = async () => await handle.CommitAsync(); + + await commit.Should().ThrowAsync().WithMessage("*MUST result row*"); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0, "a state change with no MUST row never commits"); + } + + [Fact] + public async Task A_Failed_Statement_Leaves_The_Scope_Only_To_Be_Abandoned_And_The_Work_Rolls_Back() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"faulted-{Guid.NewGuid():N}.example.com"; + + await using (var handle = await Build(dataSource).EnterAsync(Admission())) + { + await InsertHostAsync(handle, host); + var failing = async () => await handle.ExecuteAsync("SELECT 1/0", null, CancellationToken.None); + await failing.Should().ThrowAsync(); + + // PostgreSQL would answer "current transaction is aborted"; the facade says what to do. + var next = async () => await ScalarAsync(handle, "SELECT 1"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, null, null, null, null), CancellationToken.None); + var commit = async () => await handle.CommitAsync(); + await next.Should().ThrowAsync().WithMessage("*Dispose the scope*"); + await result.Should().ThrowAsync(); + await commit.Should().ThrowAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0); + } + + [Theory] + [InlineData("COMMIT")] + [InlineData("ROLLBACK")] + [InlineData("BEGIN")] + [InlineData("SET app.tenant_id = 'x'")] + [InlineData("SELECT 1; COMMIT")] + [InlineData("SELECT 1; SELECT 2")] + [InlineData("DROP TABLE platform_killswitches")] + [InlineData("TRUNCATE platform_killswitches")] + [InlineData("COPY platform_killswitches TO STDOUT")] + [InlineData("DO $$ BEGIN END $$")] + [InlineData("-- comment\nSELECT 1")] + [InlineData(" ")] + public async Task The_Facade_Refuses_Anything_But_One_Dml_Statement_And_Stays_Usable(string sql) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var refused = async () => await handle.ExecuteAsync(sql, null, CancellationToken.None); + + await refused.Should().ThrowAsync(); + (await ScalarAsync(handle, "SELECT 1")).Should().Be(1, "a statement refused before it ran does not fault the scope"); + } + + [Theory] + [InlineData("select 1")] + [InlineData("SELECT 1;")] + [InlineData(" SELECT\n1")] + [InlineData("WITH x AS (SELECT 1 AS n) SELECT n FROM x")] + public async Task The_Facade_Accepts_One_Statement_Whatever_Its_Case_Or_Spacing(string sql) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var rows = await handle.QueryAsync(sql, null, reader => reader.GetInt32(0), CancellationToken.None); + + rows.Should().Equal(1); + } + + [Fact] + public async Task The_Connection_Is_Returned_At_Commit_Not_At_Disposal() + { + // A pool of one: the second entry can only succeed if the first scope's commit already + // returned its connection. A handle that held it until disposal would block here. + var builder = new NpgsqlConnectionStringBuilder(_schema.Postgres.PlatformConnectionString) + { + MaxPoolSize = 1, + Timeout = 3, + }; + await using var dataSource = PlatformSource(builder.ConnectionString); + var scope = Build(dataSource); + + var first = await scope.EnterAsync(Admission(), CancellationToken.None); + await CompleteAsync(first); + + await using var second = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(second, "SELECT 1")).Should().Be(1); + await first.DisposeAsync(); + } + + [Fact] + public async Task The_Result_Counter_Counts_A_Committed_Result_And_Not_A_Rolled_Back_One() + { + long total = 0; + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.ResultCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, value, _, _) => Interlocked.Add(ref total, value)); + listener.Start(); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource); + + await using (var abandoned = await scope.EnterAsync(Admission())) + { + await abandoned.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, null, null, null, null)); + } + + Interlocked.Read(ref total).Should().Be(0, "a result that rolled back is not a result"); + + await using (var completed = await scope.EnterAsync(Admission())) + { + await CompleteAsync(completed); + } + + Interlocked.Read(ref total).Should().Be(1); + } + + [Fact] + public async Task Two_First_Toggles_Of_One_Key_Serialise_On_The_Row_Lock() + { + // SELECT ... FOR UPDATE locks nothing when no row exists, so two first toggles used to read the + // registry default as their before state. The row is created first, so exactly one of two + // concurrent first toggles sees the default and the other sees the first one's result. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var key = KillswitchKeys.EmailDispatchEnabled; + var registryDefault = KillswitchKeys.All[key]; + var toggle = new KillswitchToggle( + Build(dataSource), new RecordingCache(), new SystemClock(), NullLogger.Instance); + + for (var attempt = 0; attempt < 5; attempt++) + { + try + { + var results = await Task.WhenAll( + toggle.ToggleAsync(TestPlatformAdmissions.Admission(), key, !registryDefault), + toggle.ToggleAsync(TestPlatformAdmissions.Admission(), key, !registryDefault)); + + results.Count(result => result.Before == registryDefault).Should().Be(1, + "one toggle saw the default and the other saw the first one's committed state"); + results.Count(result => result.Before == !registryDefault).Should().Be(1); + } + finally + { + await using var cleanup = await Build(dataSource).EnterAsync(Admission()); + await cleanup.ExecuteAsync("DELETE FROM platform_killswitches WHERE key = @k", [new PlatformSqlParameter("k", key.Value)]); + await CompleteAsync(cleanup); + } } } + private static Task InsertHostAsync(IPlatformAdminScopeHandle handle, string host) => + handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); + private static async Task> Rows(System.Data.Common.DbConnection connection, string correlation) { await using var command = connection.CreateCommand(); command.CommandText = - "SELECT tenant_id, operation, reason, actor_user_id, metadata::text, after_state::text " + "SELECT tenant_id, operation, reason, actor_user_id, metadata::text, after_state::text, before_state::text " + "FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id"; command.Parameters.Add(new NpgsqlParameter("c", correlation)); await using var reader = await command.ExecuteReaderAsync(); @@ -855,13 +1087,14 @@ private static async Task> Rows(System.Data.Common.DbConnection c rows.Add(new AuditRow( reader.GetGuid(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? string.Empty : reader.GetString(4), - reader.IsDBNull(5) ? string.Empty : reader.GetString(5))); + reader.IsDBNull(5) ? string.Empty : reader.GetString(5), + reader.IsDBNull(6) ? string.Empty : reader.GetString(6))); } return rows; } - private sealed record AuditRow(Guid Tenant, string Operation, string? Reason, Guid? Actor, string Metadata, string After); + private sealed record AuditRow(Guid Tenant, string Operation, string? Reason, Guid? Actor, string Metadata, string After, string Before); private sealed class RecordingCache(Func>? observe = null) : LearnStack.SharedKernel.Caching.ICacheService { @@ -1062,6 +1295,14 @@ private static async Task ScalarAsync( return (T)(await command.ExecuteScalarAsync())!; } + /// Writes a MUST result row under the sentinel and commits, as a completed act does. + private static async Task CompleteAsync(IPlatformAdminScopeHandle handle) + { + await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "test", null, null), CancellationToken.None); + await handle.CommitAsync(CancellationToken.None); + } + private static PlatformAdmission Admission(string? correlation = null) => correlation is null ? TestPlatformAdmissions.Admission() diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index 885fb67e..70c8c49b 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -1,12 +1,16 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; using System.Net; using System.Net.Http.Json; using System.Text.Json; using FluentAssertions; using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Entitlements; using LearnStack.SharedKernel.Platform; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -76,6 +80,27 @@ public async Task A_Valid_Operator_With_The_Grant_Toggles_And_The_Admission_Carr admission.Operator.Acr.Should().Be("mfa"); admission.Ticket.Should().Be("INC-42"); admission.Operation.Should().BeSameAs(PlatformOperations.KillswitchToggle); + admission.Operator.CorrelationId.Should().NotBeNullOrWhiteSpace( + "a result row is never recorded without a handle the operator can quote"); + body.GetProperty("correlationId").GetString().Should().Be(admission.Operator.CorrelationId); + admission.IssuedAt.Should().BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromSeconds(30)); + } + + [Fact] + public async Task The_Bearer_Prefix_And_The_Route_Prefix_Are_Matched_Without_Regard_To_Case() + { + // Routing is case-insensitive, so the scheme's own prefix checks must be too: a request the + // router sends to the operator endpoint is a request the operator scheme authenticates. + using var request = new HttpRequestMessage(HttpMethod.Put, Path.ToUpperInvariant().Replace("KILLSWITCH.CLASSROOM.RECORDING", "killswitch.classroom.recording")) + { + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + request.Headers.TryAddWithoutValidation("Authorization", "bearer " + Valid()); + + var response = await _client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + _toggle.Calls.Should().ContainSingle(); } [Fact] @@ -92,22 +117,31 @@ public async Task No_Credential_Is_Refused_Without_Detail() } [Theory] - [InlineData("audience")] - [InlineData("azp")] - [InlineData("acr")] - [InlineData("acr-missing")] - [InlineData("auth-time-old")] - [InlineData("auth-time-missing")] - [InlineData("auth-time-future")] - [InlineData("lifetime")] - [InlineData("expired")] - [InlineData("subject-missing")] - public async Task A_Wrongly_Profiled_Token_Is_Refused_And_Nothing_Is_Called(string defect) + [InlineData("audience", "token_audience")] + [InlineData("issuer", "token_issuer")] + [InlineData("typ", "token_type")] + [InlineData("alg", "token_signature")] // the stock handler reports a disallowed algorithm as a signature failure + [InlineData("signature", "token_signature")] + [InlineData("azp", "profile_azp")] + [InlineData("acr", "profile_acr")] + [InlineData("acr-missing", "profile_acr")] + [InlineData("auth-time-old", "profile_auth_age")] + [InlineData("auth-time-missing", "profile_auth_time")] + [InlineData("auth-time-future", "profile_auth_age")] + [InlineData("lifetime", "profile_lifetime")] + [InlineData("expired", "token_expired")] + [InlineData("subject-missing", "profile_subject")] + public async Task A_Wrongly_Profiled_Token_Is_Refused_Counted_Under_Its_Cause_And_Nothing_Is_Called( + string defect, string expectedCause) { var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var token = defect switch { "audience" => Sign(("aud", "learnstack-api")), + "issuer" => Sign(("iss", _tenant.Issuer)), + "typ" => _operator.Token(Payload([]), header: Header("RS256", "at+jwt")), + "alg" => SignWithSha384(), + "signature" => Sign()[..^4] + "AAAA", "azp" => Sign(("azp", "learnstack-web")), "acr" => Sign(("acr", "0")), "acr-missing" => SignWithout("acr"), @@ -118,11 +152,88 @@ public async Task A_Wrongly_Profiled_Token_Is_Refused_And_Nothing_Is_Called(stri "expired" => Sign(("iat", now - 7200), ("exp", now - 3600)), _ => SignWithout("sub"), }; + using var counted = Counted(); var response = await Put(token, """{"enabled":false}"""); await AssertUnauthorized(response); _toggle.Calls.Should().BeEmpty("a refused credential reaches no operator service"); + counted.Causes.Should().Contain(expectedCause, "the cause is a closed label an operator can alert on"); + } + + [Fact] + public async Task A_Missing_Credential_Is_Counted_As_Missing() + { + using var counted = Counted(); + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + + await AssertUnauthorized(await _client.SendAsync(request)); + + counted.Causes.Should().Contain("token_missing"); + } + + [Theory] + [InlineData("redirect")] + [InlineData("oversized-keys")] + [InlineData("foreign-jwks-uri")] + public async Task Unsafe_Issuer_Metadata_Refuses_Every_Operator_And_Is_Counted(string fault) + { + // The scheme's own transport follows no redirect, reads at most 256 KB and fetches nothing + // outside the issuer's origin, so a hostile or broken metadata endpoint cannot choose the + // keys the operator scheme trusts. An unreachable issuer refuses everyone (no last known + // good), which is the safe side of an outage. + var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + var foreign = await TenantAuthenticationIssuer.StartAsync(); + try + { + TenantAuthenticationSigningKey? signer = null; + switch (fault) + { + case "redirect": + misbehaving.DiscoveryStatusCode = StatusCodes.Status302Found; + misbehaving.DiscoveryRedirect = misbehaving.CanaryAddress; + break; + case "oversized-keys": + misbehaving.JwksResponse = new string(' ', 300 * 1024); + break; + default: + // A second, live origin that would happily serve a key set and so make a token + // signed by its key valid, if the discovery document's address were followed. + misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( + misbehaving.Issuer + "/keys", foreign.Issuer + "/keys", StringComparison.Ordinal); + signer = foreign.CurrentKey; + break; + } + + var toggle = new RecordingToggle(); + await using var factory = new PlatformOperatorApiFactory(_tenant, misbehaving, toggle, grantSubject: Subject); + using var client = factory.CreateClient(); + using var counted = Counted(); + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + misbehaving.Token(misbehaving.Payload( + ("aud", "learnstack-platform"), ("azp", "learnstack-operator"), ("acr", "mfa"), + ("auth_time", DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 30), ("sub", Subject)), key: signer) } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + + var response = await client.SendAsync(request); + + await AssertUnauthorized(response); + toggle.Calls.Should().BeEmpty(); + counted.MetadataFailures.Should().BeGreaterThan(0, + "the transport refusal is counted where it happens; the request itself finds no key"); + misbehaving.CanaryRequests.Should().Be(0, "no redirect target is ever dereferenced"); + foreign.JwksRequests.Should().Be(0, "a key set at another origin is never fetched"); + } + finally + { + await foreign.DisposeAsync(); + await misbehaving.DisposeAsync(); + } } [Fact] @@ -192,6 +303,7 @@ public async Task A_Failed_Audit_Write_Is_A_Retryable_503_Not_A_Success() response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); await AssertProblem(response, "audit_unavailable"); + response.Headers.RetryAfter.Should().NotBeNull("every 503 the API answers carries Retry-After"); } [Fact] @@ -240,11 +352,15 @@ public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_S public void The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_Its_Prefix() { // The tenant surface census excludes this surface by exact type (it has its own scheme), so - // its population is closed here instead: every routed endpoint under /api/platform, its verb, - // and the policy that guards it. A second endpoint, another verb or a missing policy fails. + // its population is closed here instead: every routed endpoint under /api/platform (whatever + // the case of its pattern) or carrying the operator metadata anywhere, its verb, and the + // policy that guards it. A second endpoint, another verb or a missing policy fails. var endpoints = _factory.Services.GetServices() .SelectMany(source => source.Endpoints).OfType() - .Where(endpoint => endpoint.RoutePattern.RawText!.StartsWith("/api/platform", StringComparison.Ordinal)) + .Where(endpoint => endpoint.RoutePattern.RawText!.TrimStart('/') + .StartsWith("api/platform", StringComparison.OrdinalIgnoreCase) + || endpoint.Metadata.GetMetadata() + ?.Kind == InfrastructureOperationKind.PlatformOperator) .ToList(); var only = endpoints.Should().ContainSingle().Subject; @@ -256,8 +372,66 @@ public void The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_It only.Metadata.GetMetadata().Should().BeNull(); } + private string Header(string alg, string typ) => JsonSerializer.Serialize(new { alg, typ, kid = _operator.CurrentKey.Kid }); + + // Correctly signed, with an algorithm the scheme does not allow: only the algorithm is wrong. + private string SignWithSha384() + { + var input = TenantAuthenticationIssuer.Base64Url(System.Text.Encoding.UTF8.GetBytes(Header("RS384", "JWT"))) + + "." + TenantAuthenticationIssuer.Base64Url(System.Text.Encoding.UTF8.GetBytes(Payload([]))); + var signature = _operator.CurrentKey.Rsa.SignData( + System.Text.Encoding.ASCII.GetBytes(input), + System.Security.Cryptography.HashAlgorithmName.SHA384, + System.Security.Cryptography.RSASignaturePadding.Pkcs1); + return input + "." + TenantAuthenticationIssuer.Base64Url(signature); + } + private string Valid() => Sign(); + private static CauseListener Counted() => new(); + + /// Captures the cause label of every refusal counted while it is alive. + private sealed class CauseListener : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly ConcurrentBag _causes = []; + private long _metadataFailures; + + public CauseListener() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name is PlatformOperatorMetrics.RefusalCounterName or PlatformOperatorMetrics.MetadataFailureCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + if (instrument.Name == PlatformOperatorMetrics.MetadataFailureCounterName) + { + Interlocked.Add(ref _metadataFailures, value); + } + + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + _causes.Add(cause); + } + } + }); + _listener.Start(); + } + + public IReadOnlyCollection Causes => _causes; + + public long MetadataFailures => Interlocked.Read(ref _metadataFailures); + + public void Dispose() => _listener.Dispose(); + } + private string Sign(params (string Name, object? Value)[] replacements) => _operator.Token(Payload(replacements)); private string SignWithout(string name) diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs new file mode 100644 index 00000000..b3463107 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs @@ -0,0 +1,49 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// Properties of the shipped operator realm export that need no running Keycloak (ADR-0101 § 3). +/// +/// +/// The behavioural proof against pinned Keycloak is . These +/// cases pin the settings whose effect is a refusal that cannot be provoked from a headless login. +/// +public sealed class PlatformOperatorRealmFileTests +{ + private static JsonObject Realm() => + JsonNode.Parse(File.ReadAllText(KeycloakFixture.RealmPath("learnstack-hub")))!.AsObject(); + + [Fact] + public void Password_Reset_Is_Off_So_No_Second_Path_To_A_Password_Skips_The_Second_Factor() => + Realm()["resetPasswordAllowed"]!.GetValue().Should().BeFalse(); + + [Fact] + public void The_Operator_Client_Is_Public_Pkce_With_No_Direct_Grant_And_No_Realm_Roles_In_Its_Token() + { + var client = Realm()["clients"]!.AsArray().Select(node => node!.AsObject()) + .Single(candidate => candidate["clientId"]!.GetValue() == "learnstack-operator"); + + client["publicClient"]!.GetValue().Should().BeTrue(); + client["standardFlowEnabled"]!.GetValue().Should().BeTrue(); + client["implicitFlowEnabled"]!.GetValue().Should().BeFalse(); + client["directAccessGrantsEnabled"]!.GetValue().Should().BeFalse(); + client["serviceAccountsEnabled"]!.GetValue().Should().BeFalse(); + client["fullScopeAllowed"]!.GetValue().Should().BeFalse(); + client["attributes"]!["pkce.code.challenge.method"]!.GetValue().Should().Be("S256"); + client["attributes"]!["access.token.lifespan"]!.GetValue().Should().Be("900"); + } + + [Fact] + public void The_Realm_Browser_Flow_Is_The_Step_Up_Flow_And_Its_Second_Level_Asks_For_The_Factor_Every_Time() + { + var realm = Realm(); + + realm["browserFlow"]!.GetValue().Should().Be("browser-loa"); + var level2 = realm["authenticatorConfig"]!.AsArray().Select(node => node!.AsObject()) + .Single(config => config["alias"]!.GetValue() == "loa-2"); + level2["config"]!["loa-max-age"]!.GetValue().Should().Be("0", "level 2 never rides an earlier session"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs index 6c4b9335..1bc3d390 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs @@ -76,7 +76,7 @@ public async Task The_Operator_Client_Issues_A_Token_That_Meets_The_Operator_Pro .Should().BeLessThanOrEqualTo(TimeSpan.FromMinutes(15), "the realm caps the operator client's access token"); var settings = Settings(token.GetPayloadValue("acr")); - PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, null, out var witness) + PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, null, out var witness, out _) .Should().BeTrue("the token the realm issues is the token the scheme accepts"); witness!.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_keycloak.IssuerFor("learnstack-hub"), token.Subject)); } @@ -112,7 +112,7 @@ public async Task A_Token_From_The_Portal_Client_Does_Not_Meet_The_Operator_Prof var token = new JsonWebToken(exchange.AccessToken); token.Audiences.Should().NotContain("learnstack-platform"); - PlatformOperatorTokenProfile.TryRead(token, Settings("mfa", "2", "1"), DateTimeOffset.UtcNow, null, out _) + PlatformOperatorTokenProfile.TryRead(token, Settings("mfa"), DateTimeOffset.UtcNow, null, out _, out _) .Should().BeFalse("a portal token carries neither the operator client nor the platform audience"); } diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs new file mode 100644 index 00000000..904d165e --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs @@ -0,0 +1,261 @@ +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Routing.Patterns; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Authentication; + +/// +/// The closed operator token profile, the failure labels, the settings guards and the classifier +/// guard (ADR-0101 § 2, § 3). The profile runs after the stock handler verified the signature, so +/// these unsigned fixtures exercise only the claim reading. +/// +public sealed class PlatformOperatorAuthenticationTests +{ + private const string Issuer = "https://operator.example.test/realms/learnstack-hub"; + private static readonly DateTimeOffset Now = new(2026, 11, 19, 9, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Pinned_Issuer() + { + var read = PlatformOperatorTokenProfile.TryRead( + Token(), Settings(), Now, "00-trace-01", out var witness, out var cause); + + read.Should().BeTrue(); + witness!.Issuer.Should().Be(Issuer); + witness.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(Issuer, "operator-sub-1")); + witness.Acr.Should().Be("mfa"); + witness.Executor.Should().Be(PlatformOperatorSettings.Executor); + witness.CorrelationId.Should().Be("00-trace-01"); + witness.AuthenticatedAt.Should().Be(Now.AddSeconds(-30)); + cause.Should().Be(default(PlatformOperatorTokenCause)); + } + + [Theory] + [InlineData("iss-other", "Issuer")] + [InlineData("iss-case", "Issuer")] + [InlineData("iss-missing", "Issuer")] + [InlineData("sub-missing", "Subject")] + [InlineData("sub-blank", "Subject")] + [InlineData("azp-missing", "AuthorizedParty")] + [InlineData("azp-other", "AuthorizedParty")] + [InlineData("acr-missing", "AuthenticationContext")] + [InlineData("acr-other", "AuthenticationContext")] + [InlineData("iat-missing", "IssuedAt")] + [InlineData("iat-out-of-range", "IssuedAt")] + [InlineData("auth-time-missing", "AuthenticationTime")] + [InlineData("auth-time-out-of-range", "AuthenticationTime")] + [InlineData("lifetime-too-long", "Lifetime")] + [InlineData("lifetime-not-positive", "Lifetime")] + [InlineData("auth-time-future", "AuthenticationAge")] + [InlineData("auth-time-old", "AuthenticationAge")] + public void Each_Profile_Defect_Is_Refused_With_Its_Own_Closed_Cause(string defect, string expectedCause) + { + var expected = Enum.Parse(expectedCause); + var iat = Now.ToUnixTimeSeconds() - 5; + var claims = Claims(); + switch (defect) + { + case "iss-other": claims["iss"] = "https://elsewhere.example.test/realms/x"; break; + case "iss-case": claims["iss"] = Issuer.ToUpperInvariant(); break; + case "iss-missing": claims.Remove("iss"); break; + case "sub-missing": claims.Remove("sub"); break; + case "sub-blank": claims["sub"] = " "; break; + case "azp-missing": claims.Remove("azp"); break; + case "azp-other": claims["azp"] = "learnstack-web"; break; + case "acr-missing": claims.Remove("acr"); break; + case "acr-other": claims["acr"] = "0"; break; + case "iat-missing": claims.Remove("iat"); break; + case "iat-out-of-range": claims["iat"] = long.MaxValue; break; + case "auth-time-missing": claims.Remove("auth_time"); break; + case "auth-time-out-of-range": claims["auth_time"] = long.MinValue; break; + case "lifetime-too-long": claims["exp"] = iat + 16 * 60; break; + case "lifetime-not-positive": claims["exp"] = iat; break; + case "auth-time-future": claims["auth_time"] = Now.ToUnixTimeSeconds() + 600; break; + case "auth-time-old": claims["auth_time"] = Now.ToUnixTimeSeconds() - 3600; break; + default: throw new ArgumentOutOfRangeException(nameof(defect)); + } + + PlatformOperatorTokenProfile.TryRead(Token(claims), Settings(), Now, null, out var witness, out var cause) + .Should().BeFalse(); + witness.Should().BeNull(); + cause.Should().Be(expected); + cause.Label().Should().NotBe("profile_invalid", "every cause has a closed counter label"); + } + + [Fact] + public void Every_Profile_Cause_Has_A_Distinct_Closed_Label() + { + var labels = Enum.GetValues().Select(cause => cause.Label()).ToList(); + + labels.Should().OnlyHaveUniqueItems().And.OnlyContain(label => label.StartsWith("profile_", StringComparison.Ordinal)); + } + + public static TheoryData Failures() => new() + { + { null, "token_missing" }, + { new PlatformOperatorProfileException("profile_azp"), "profile_azp" }, + { new SecurityTokenExpiredException("x"), "token_expired" }, + { new SecurityTokenNotYetValidException("x"), "token_lifetime" }, + { new SecurityTokenNoExpirationException("x"), "token_lifetime" }, + { new SecurityTokenInvalidSignatureException("x"), "token_signature" }, + { new SecurityTokenSignatureKeyNotFoundException("x"), "token_signature" }, + { new SecurityTokenInvalidIssuerException("x"), "token_issuer" }, + { new SecurityTokenInvalidAudienceException("x"), "token_audience" }, + { new SecurityTokenInvalidAlgorithmException("x"), "token_algorithm" }, + { new SecurityTokenInvalidTypeException("x"), "token_type" }, + { new AggregateException(new SecurityTokenExpiredException("x"), new IOException()), "token_expired" }, + { new InvalidOperationException("IDX20803: Unable to obtain configuration."), "metadata_unavailable" }, + { new InvalidOperationException("wrapped", new IOException("refused")), "metadata_unavailable" }, + { new HttpRequestException("down"), "metadata_unavailable" }, + { new FormatException("other"), "token_invalid" }, + }; + + [Theory] + [MemberData(nameof(Failures))] + public void An_Authentication_Failure_Maps_To_One_Closed_Label(Exception? failure, string expected) => + PlatformOperatorFailure.Classify(failure).Should().Be(expected); + + [Theory] + [InlineData("0")] + [InlineData("1")] + public void A_Single_Factor_Acr_Is_Not_An_Accepted_Assurance(string acr) + { + var act = () => FromConfiguration(("PlatformOperator:AcceptedAcr:0", "mfa"), ("PlatformOperator:AcceptedAcr:1", acr)); + + act.Should().Throw().WithMessage("*single-factor*"); + } + + [Fact] + public void The_Operator_Issuer_Cannot_Be_The_Tenant_Issuer() + { + var act = () => FromConfiguration((TenantAuthenticationOptions.IssuerConfigurationKey, Issuer + "/")); + + act.Should().Throw().WithMessage("*tenant issuer*"); + } + + [Fact] + public void A_Different_Tenant_Issuer_Leaves_The_Operator_Configuration_Valid() + { + var settings = FromConfiguration( + (TenantAuthenticationOptions.IssuerConfigurationKey, "https://identity.example.test/realms/learnstack")); + + settings.Should().NotBeNull(); + settings!.Issuer.Should().Be(Issuer); + } + + [Fact] + public void An_Unreadable_Maximum_Authentication_Age_Names_The_Expected_Format() + { + var act = () => FromConfiguration(("PlatformOperator:MaxAuthenticationAge", "fifteen minutes")); + + act.Should().Throw().WithMessage("*00:15:00*"); + } + + [Fact] + public void Operator_Metadata_Is_Honoured_Only_On_The_Operator_Surface_Behind_The_Operator_Policy() + { + var classifier = new OperationHttpClassifier(new EmptyCatalog()); + var operatorMetadata = InfrastructureOperationMetadata.PlatformOperator; + var policy = new AuthorizeAttribute(PlatformOperatorAuthentication.PolicyName); + + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Infrastructure); + Classify(classifier, "/API/Platform/V1/killswitches/{key}", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Infrastructure, "routing is case-insensitive, so is the prefix"); + + // The declaration alone proves nothing: a route off the prefix, a missing policy, another + // policy or an anonymous allowance is refused, so the metadata cannot be used to make a + // tenant route look like infrastructure and skip the tenant admission middlewares. + Classify(classifier, "/api/v1/public/site", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v2/killswitches", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, new AuthorizeAttribute("Other")) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, policy, new AllowAnonymousAttribute()) + .Should().Be(HttpOperationClassification.Refused); + } + + private static HttpOperationClassification Classify( + OperationHttpClassifier classifier, string pattern, params object[] metadata) => + classifier.Classify( + new RouteEndpoint( + _ => Task.CompletedTask, + RoutePatternFactory.Parse(pattern), + 0, + new EndpointMetadataCollection(metadata), + "test"), + out _); + + private static PlatformOperatorSettings Settings() => FromConfiguration()!; + + private static PlatformOperatorSettings? FromConfiguration(params (string Key, string Value)[] extra) + { + var values = new Dictionary + { + ["PlatformOperator:Issuer"] = Issuer, + ["PlatformOperator:AcceptedAcr:0"] = "mfa", + ["PlatformOperator:AuthorizedParties:0"] = "learnstack-operator", + }; + foreach (var (key, value) in extra) + { + values[key] = value; + } + + return PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(values).Build(), DeploymentMode.SaaS); + } + + private static Dictionary Claims() + { + var issued = Now.ToUnixTimeSeconds() - 5; + return new Dictionary + { + ["iss"] = Issuer, + ["sub"] = "operator-sub-1", + ["aud"] = "learnstack-platform", + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["iat"] = issued, + ["exp"] = issued + 600, + ["auth_time"] = Now.ToUnixTimeSeconds() - 30, + }; + } + + private static JsonWebToken Token(Dictionary? claims = null) => + new(Segment(new { alg = "RS256", typ = "JWT", kid = "owned-key" }) + "." + Segment(claims ?? Claims()) + ".c2ln"); + + private static string Segment(object value) => + Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value))); + + private sealed class EmptyCatalog : IOperationPolicyCatalog + { + public IReadOnlyCollection All => []; + public IReadOnlyCollection Definitions => []; + public bool TryGet(Type requestType, out OperationPolicy policy) + { + policy = null!; + return false; + } + + public bool TryGetDefinition(PermissionScope scope, string key, out PermissionRegistration definition) + { + definition = null!; + return false; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index f69458d2..1926a333 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -137,6 +137,58 @@ public async Task Ordinary_job_is_refused_before_credential_resolution() source.IsValueCreated.Should().BeFalse(); } + [Fact] + public async Task The_Gate_Stamps_The_Admission_With_Its_Own_Clock() + { + var instant = new DateTimeOffset(2026, 11, 19, 8, 0, 0, TimeSpan.Zero); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key), new FixedClock(instant)); + + var result = await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null); + + result.Admission!.IssuedAt.Should().Be(instant, "the scope bounds the admission's age from this stamp"); + } + + [Fact] + public async Task A_Stale_Admission_Never_Reaches_The_Credential_And_Is_Not_Spent() + { + var scope = Build(out var dataSource); + var stale = TestPlatformAdmissions.Admission( + issuedAt: DateTimeOffset.UtcNow - PlatformAdmission.MaximumAge - TimeSpan.FromSeconds(5)); + + var act = async () => await scope.EnterAsync(stale, CancellationToken.None); + + await act.Should().ThrowAsync().WithMessage("*stale*"); + dataSource.IsValueCreated.Should().BeFalse("the age check precedes the credential"); + stale.TryConsume().Should().BeTrue("a refused-as-stale admission was never spent"); + } + + [Fact] + public async Task An_Admission_Opens_One_Scope_Only() + { + // The first entry spends the admission and then fails at the absent credential; the + // second finds it spent and says so, rather than reaching for the credential again. + var scope = Build(out var dataSource); + var admission = TestPlatformAdmissions.Admission(); + + var first = async () => await scope.EnterAsync(admission, CancellationToken.None); + await first.Should().ThrowAsync().WithMessage("*not configured*"); + + var second = async () => await scope.EnterAsync(admission, CancellationToken.None); + await second.Should().ThrowAsync().WithMessage("*already used*"); + dataSource.IsValueCreated.Should().BeFalse(); + } + + [Fact] + public void An_Admission_Is_Consumed_By_Exactly_One_Caller_Even_Concurrently() + { + var admission = TestPlatformAdmissions.Admission(); + + var winners = Enumerable.Range(0, 64).AsParallel().WithDegreeOfParallelism(16) + .Select(_ => admission.TryConsume()).Count(won => won); + + winners.Should().Be(1); + } + [Fact] public async Task A_Permitted_Caller_Reaches_The_Credential_And_Fails_There_When_It_Is_Absent() { @@ -165,6 +217,21 @@ public async Task An_Operation_The_Catalogue_Does_Not_Declare_Never_Opens_A_Conn dataSource.IsValueCreated.Should().BeFalse("the refusal precedes the credential"); } + [Fact] + public async Task A_Catalogue_That_Lost_Only_The_Operation_Slug_Never_Opens_A_Connection() + { + // The entry slug is declared, the operation's result slug is not: the scope must refuse before + // the credential rather than enter, run the act and discover that its MUST row cannot be + // classified (ADR-0044 § 10). + var scope = Build(out var dataSource, new AuditCatalog([new EntryOnlyCatalogSource()])); + + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); + + (await act.Should().ThrowAsync()) + .Which.Message.Should().Contain(PlatformOperations.KillswitchToggle.AuditSlug); + dataSource.IsValueCreated.Should().BeFalse(); + } + [Fact] public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() { @@ -234,8 +301,47 @@ public async Task The_Configuration_Source_Matches_The_Digest_And_Fails_Closed_W (await noIssuer.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeFalse(); } - private static PlatformOperatorGate Gate(IPlatformOperatorGrantSource grants) => - new(grants, NullLogger.Instance); + [Fact] + public async Task A_Grant_Removed_From_A_Reloaded_Configuration_Is_Refused_On_The_Next_Act() + { + var options = new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }; + var monitor = new MutableMonitor(options); + var source = new ConfigurationPlatformOperatorGrantSource(monitor, NullLogger.Instance); + var gate = Gate(source); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)).IsAdmitted + .Should().BeTrue(); + + monitor.Replace(new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)).Refusal + .Should().Be(PlatformRefusal.MissingPermission, "withdrawal takes effect on the next act, not at token expiry"); + } + + [Fact] + public async Task A_Reload_That_Fails_Validation_Refuses_Every_Operator_Until_It_Is_Valid() + { + var monitor = new MutableMonitor(new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + var source = new ConfigurationPlatformOperatorGrantSource(monitor, NullLogger.Instance); + (await source.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeTrue(); + + monitor.FailWith(new OptionsValidationException( + nameof(PlatformOperatorGrantOptions), typeof(PlatformOperatorGrantOptions), ["a reload that is not valid"])); + + (await source.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeFalse( + "an invalid reload fails closed rather than keeping the last good grants"); + } + + private static PlatformOperatorGate Gate(IPlatformOperatorGrantSource grants, IClock? clock = null) => + new(grants, clock ?? new SystemClock(), NullLogger.Instance); private static CountingGrants Grants(string subject, params string[] keys) => new(TestPlatformAdmissions.Issuer, subject, keys); @@ -259,6 +365,11 @@ private static PlatformAdminScope Build(out PrivilegedDataSource dataSource, IAu NullLogger.Instance); } + private sealed class FixedClock(DateTimeOffset instant) : IClock + { + public DateTimeOffset UtcNow => instant; + } + private sealed class CountingGrants(string issuer, string subject, string[] keys) : IPlatformOperatorGrantSource { public int Reads { get; private set; } @@ -271,6 +382,27 @@ public ValueTask IsGrantedAsync(string subjectDigest, string permissionKey } } + private sealed class MutableMonitor(PlatformOperatorGrantOptions initial) : IOptionsMonitor + { + private PlatformOperatorGrantOptions _value = initial; + private Exception? _failure; + + public PlatformOperatorGrantOptions CurrentValue => _failure is null ? _value : throw _failure; + public void Replace(PlatformOperatorGrantOptions value) => _value = value; + public void FailWith(Exception failure) => _failure = failure; + public PlatformOperatorGrantOptions Get(string? name) => CurrentValue; + public IDisposable? OnChange(Action listener) => null; + } + + /// Declares the scope's entry slug and nothing else, as a deployment that lost a slug would. + private sealed class EntryOnlyCatalogSource : IAuditCatalogSource + { + public string ModuleName => "tenancy"; + + public void Describe(IAuditCatalogBuilder builder) => + builder.DeclareOffPath("platform.admin_scope.enter", OperationType.SecurityEvent, OperationClass.Must); + } + private sealed class FixedMonitor(PlatformOperatorGrantOptions value) : IOptionsMonitor { public PlatformOperatorGrantOptions CurrentValue => value; diff --git a/docs/architecture/21-feature-flags.md b/docs/architecture/21-feature-flags.md index 0b334978..1798dbe7 100644 --- a/docs/architecture/21-feature-flags.md +++ b/docs/architecture/21-feature-flags.md @@ -399,10 +399,11 @@ CREATE TABLE platform_killswitches ( - **Policies** are role-qualified in the `platform_host_to_tenant` shape, with the read widened rather than keyed — a killswitch is global by construction, and hiding it from the role that must honour it would only fail open. Every write is reserved to - `learnstack_platform` through the audited `EnterPlatformAdminScope(reason)` path, which - is what gives `tenancy.killswitch.toggle` a real actor. The class and its policy DDL - live in [Database Standards § Table classes](../standards/05-database.md); the clauses - are deliberately not restated here. + `learnstack_platform` through the audited, admission-gated platform scope, which is + what gives `tenancy.killswitch.toggle` a MUST result row naming the operator. The + class and its policy DDL live in + [Database Standards § Table classes](../standards/05-database.md); the clauses are + deliberately not restated here. - **Reads go through the L1 cache**, not to the table per request, and are invalidated on toggle. Holding the answer needs a second allowed platform cache-key family, `platform:tenancy:killswitch`; `CacheKey.EnsureValid` admits that family and the host @@ -455,12 +456,14 @@ Both surfaces are MUST-audit security-events (see the inbound Hub event carries `hub_event_id` and is mirrored into an audit entry (`tenancy.entitlement.refresh`) with `before` and `after` snapshots of the `features` / `limits` jsonb. -- Killswitch flips are logged as `tenancy.killswitch.toggle` with the platform-admin - actor and a free-text reason field that the operator console makes required. The - classification is written ahead of the command: Packet 9 ships no writer, and - [Phase 03](../roadmap/phase-03-identity-admin.md) lands the toggle that raises the row - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - The operation is not a MediatR request, so its catalogue entry is registered by slug +- Killswitch flips are logged as `tenancy.killswitch.toggle`, a MUST row written on the + flip's own transaction by the witness-bound result method. The row names the operator + in `metadata.operator` (issuer, subject digest, accepted `acr`, executor) and carries + the closed reason slug `killswitch_toggle`; the optional ticket is on the + sentinel-tenant row only + ([ADR-0101 § 9](../decisions/0101-platform-operator-authority.md), + [runbook](../runbooks/killswitch.md)). The operation is not a MediatR request, so its + catalogue entry is registered by slug ([ADR-0044 Amendment 3 § 1](../decisions/0044-audit-write-path.md)). ## Risks diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 34d8974f..579ba5d8 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -159,8 +159,8 @@ unmarked row is one a shipped command already raises. | `TenantSetting` | `tenancy.setting.soft_delete` `(planned)` | **MUST** | Removing a setting is a change to it, so the same baseline row covers it — and `ux_tenant_settings_tenant_id_organization_id_key` is partial on `deleted_at IS NULL`, so the key becomes free for a successor | | `Tenant` | `tenancy.locale.write` | SHOULD | Configuration; contained TenantLocale changes are captured with their owning Tenant root | | `TenantFeatureFlag` | `tenancy.feature_flag.write` `(planned)` | **MUST** | "Feature flag toggled" is on the same baseline row, and [Feature Flags § Audit](../../architecture/21-feature-flags.md) classes both flag surfaces as security events | -| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | -| `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, for the reason `tenancy.killswitch.toggle` carries both: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | +| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) shipped the table, its policies and the read path with no writer; P03-9 Step 1 ships the writer, `KillswitchToggle`, behind the operator gate with the `platform.killswitch.write` grant ([ADR-0101 § 13](../../decisions/0101-platform-operator-authority.md), [runbook](../../runbooks/killswitch.md)). The row is written on the work transaction through the witness-bound result method, so it commits with the flip or not at all | +| `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, as `tenancy.killswitch.toggle` carried both until its writer shipped: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | | `platform_host_to_tenant` | `tenancy.hostmapping.write` | **MUST** | The resolution index — the row that decides whose data an anonymous request sees | | `platform_host_to_tenant` | `tenancy.hostmapping.delete` `(planned)` | **MUST** | The same row removed. The table carries no `deleted_at`, so the delete is a row gone and a host that resolves to nobody | | `TenantAssertion` | `tenancy.tenant_assertion.reject` `(off-path)` | **MUST** for admitted events (`security-event`) | A validated header/claim mismatch with an independently defended host tenant is recorded under that host tenant, never the asserted tenant or sentinel; row 14 is counted only. [ADR-0065](../../decisions/0065-bounded-tenant-assertion-diagnostics.md) admits 600 authenticated standalone write attempts per host tenant per API instance per first-request-anchored monotonic minute, shared across scoped recorders, actors, sources and dimensions. Failed writes consume permits; later occurrences make no audit-store call and retain their refusal, count and exactly one attributed Warning (4006 replaces normal 4001). An attacker can exhaust the allowance, so later actors lose durable evidence; aggregate log volume remains unbounded. Admitted events retain MUST failure/health behavior, tenant-wide organization scope, exact actor/correlation and trusted organization in metadata. No tenant `AuditConfig` override or independent tenant-registry cap exists. General mutation MUST durability is unchanged. Packet 9 owns the recorder/decorator path; P02b-5 Steps 3–4 implement JWT attribution and HTTP activation under ADR-0064. ADR-0065 acceptance precedes the dependent budget implementation; the [merge closeout](../../roadmap/phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) owns its final delivery status | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 2e928ccb..843fb63c 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,10 +509,11 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 372 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 479 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines + - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 107 lines @@ -24542,3 +24543,110 @@ Not done here and owned elsewhere: manual accessibility needs no screen in this the runbooks were written and their requests are the ones the tests make, but no person ran them end to end; gateway exposure, production realm MFA enforcement and the grant table adapter are in Phase 11's list. + +### P03-9 Step 1 — review round 1 and its fixes (2026-11-19) + +Three independent reviewers read commit `bfba1228` with no knowledge of the process: +security and authentication, data and audit durability, and conformance and operability. +None reported a Blocker. Each finding was checked against the code before it was acted +on; the ones below changed the code, and the decisions that were recorded instead are +listed after them. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Authentication | The scheme fetched issuer metadata with the stock transport: redirects, no size cap, any origin named by the discovery document | Its own client: no redirect, five seconds, 256 KB, nothing outside the issuer's origin, no last known good, `TryAllIssuerSigningKeys` off. The tenant scheme's reader is now a shared helper (`BoundedMetadataReader`) with no behavior change | +| Authentication | `TryRead` was a public door to the witness minter, and the minter was an assembly-wide type | The minter is a private nested class of the profile, and a source census pins that only the authentication boundary names the profile, calls `TryRead` or names the minter base | +| Authentication | The profile relied on stock validation for `iss`; `iat` and `auth_time` were converted without a range check; path and `Bearer` matching were case-sensitive while routing is not | The profile restates the exact issuer, range-checks both claims, and both matches ignore case | +| Authentication | Accepted `acr` of `0` or `1`, or an operator issuer equal to the tenant issuer, would have started | Both are refused at start with a message that says why | +| Authentication | Every refusal was labelled `token_invalid` | A closed cause set from the profile and from the exception type, on the counter and in the Warning log; the response is unchanged | +| Classifier | The operator metadata alone made an endpoint infrastructure, which the tenant admission middlewares leave alone | Honoured only on a route under `api/platform/v1/`, behind exactly the operator policy and never anonymous | +| Scope | An admission could be kept and replayed, and a handle could commit a state change with no result row, run `COMMIT` or `SET` through the facade, or commit after a failed statement | The gate stamps the admission; the scope refuses one older than 30 seconds and spends it on entry. The facade takes one `SELECT`, `INSERT`, `UPDATE`, `DELETE` or `WITH` statement, refuses a commit with no result row, and is abandon-only after a failed statement. The result counter moves to the committed result | +| Audit store | The result row was bound to its admission by a substring search of `metadata` | `metadata.operator.issuer` and `subjectDigest` are parsed and compared, a ticket is accepted only on a sentinel row and only the admitted one, and the correlation id must match | +| Killswitch writer | Two first toggles of one key both read the registry default, because `FOR UPDATE` locks nothing when no row exists | The row is created at its default with `ON CONFLICT DO NOTHING`, then locked, read and updated. A cache removal failure is logged, and the commit no longer takes the caller's cancellation token | +| Operator endpoint | A missing `enabled` was answered before admission; a refused audit write left no signal | Admission first. The refusal logs at Error, counts `audit_failures` and carries `Retry-After`. The correlation id falls back to the request id, so a result row always has a handle | +| Operability | Counters used dotted names and had no row in Standard 10 | `learnstack_platform_operator_*_total`, five rows in Standard 10, and a new counter for failed metadata fetches | +| Realm | Password reset was on in the operator realm, a second path to a password that does not pass the second factor | `resetPasswordAllowed` is `false`; the README and runbook say so and give the order for a new operator: enrol the authenticator, confirm it, then grant | +| Tests | A result-row test wrote under a shared fixture tenant; assertions on `reason`, before and after state, `toggled_at`, the sentinel ticket, `issuer` and `executor` were missing; one expectation was inverted | Throwaway tenant id; the missing assertions; the inversion corrected | +| Docs | Runbooks omitted the full token profile, a decode recipe, executable commands, the audit query and the digest recipe; stale statements said the table had no writer | Runbooks rewritten; the statements corrected in CLAUDE.md, the Tenancy matrix, Standards 05, 18, 19 and 21, Architecture 21, the feature-key skill, the glossary and the compose and Keycloak READMEs | + +New cases: the admission age and single use (including 64 racing consumers), a catalogue +that lost only the operation slug, a grant withdrawn on reload and an invalid reload +failing closed, the profile cause matrix and the failure labels, the settings guards, +the classifier guard, redirect, oversized and foreign-origin metadata (the last with a +second live origin that would validate a token if it were followed), wrong `iss`, `typ`, +algorithm and signature isolated one at a time, case-insensitive matching, +`Retry-After`, a commit with no result row, a failed statement, the statement guard +(twelve refused forms, four accepted), the connection returned at commit with a pool of +one, the counter on commit only, two racing first toggles, the scripted writer order, an +indeterminate commit, a cache that cannot remove, and the store's refusal of fourteen +bound attributes after an accepted control. + +#### Recorded, not changed + +- **A start-time check that an operator issuer comes with the platform credential.** + Added and withdrawn: the closed credential-reader census + (`OutboxDispatchConventionTests`) permits no further reader of a connection string, + and the existing first-use error already names the key. The runbook lists the + credential as required for any act. +- **Requiring a platform host for `/api/platform`.** The surface is host-independent on + purpose (the target tenant is data of the act); the gateway that fronts it is Phase + 11's. +- **Keycloak `minimum.acr.value`.** Not adopted: the scheme refuses any `acr` outside + the accepted list whatever the flow produced, so a client that asked for a lower level + obtains a token that is refused, and an unverified realm attribute would add a second + control that nothing proves. +- **An end-to-end real-Keycloak token through the actual scheme.** The real-realm cases + prove the profile on a real token and the controlled-issuer cases prove the scheme on + real RS256; the two are not joined. Recorded as a gap, to be closed in Phase 11's + gateway proof. +- **A per-operation target kind** on `PlatformOperation`, so the store can also refuse a + tenant-targeted result for a platform-wide operation. Step 2 registers the first + tenant-targeted operation and adds it there. +- **The stock handler reports a disallowed algorithm as a signature failure,** so the + `token_algorithm` label is reachable only through a path the handler does not take; + the mapping stays for a future handler version and is covered by a unit case. +- **The marker clause.** The Standard 21 note that no handler carries both + `[AllowsUnresolvedTenantContext]` and a platform-scope entry is enforced as the holder + census (`Only_The_Operator_Services_Hold_The_Platform_Scope`), by path, because the + scope is a service and not a handler; the wording of the note says so. + +#### Mutation checks + +Eighteen mutations of the fix-pass guards, each applied, built, run and restored with +the restored file touched so the next build cannot reuse the mutated binary. Seventeen +were killed: the admission age unchecked, an admission reusable, a commit with no result +row, a failed statement leaving the scope usable, the statement guard off, the +connection kept past commit, the result counted when written, an unbound correlation id, +an unlocked first toggle (killed by the writer-order case; the race case is a regression +guard and is not deterministic against a plain read), a cancellable commit, an +unrestated issuer, a classifier trusting the metadata alone, a single-factor `acr` +allowed, a foreign origin followed, no `Retry-After`, and every cause reported as +generic. + +One mutant survived its first test and was killed after the case was strengthened: a +ticket accepted on a tenant row. The case's admission carried no ticket, so a second +condition refused the row for another reason; the admission now carries the ticket, so +only the sentinel rule can refuse it. + +One survives as an equivalent mutant: the scope's own refusal of a background-job frame. +The privileged data source refuses the same frame when the connection is opened, so the +property that matters, refusal before the credential is resolved, holds without it. The +scope's call stays as the named first refusal. + +#### Proof run locally + +| Suite | Result | +|---|---| +| Unit | 4,229 passed | +| Integration, the whole suite (Release, 1 h 33 m, real PostgreSQL and pinned Keycloak) | 4,433 passed | +| Integration, operator subset rerun on the final tree (platform scope, operator HTTP, killswitch writer order, realm file, real-realm login, job admission) | 115 passed | +| Contract | 13 passed | +| Architecture (Release): platform scope, audit and API conventions | 31 passed | +| Architecture (Release, 43 min): `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests` | 178 passed | + +The last row is the result the Step 1 record deferred to this entry. It is also the run +that found the withdrawn start-time credential check: a compiled census of +connection-string readers failed on the new reader, which is why the check is recorded +above and not shipped. diff --git a/docs/runbooks/killswitch.md b/docs/runbooks/killswitch.md index 66a0b98a..392e8f46 100644 --- a/docs/runbooks/killswitch.md +++ b/docs/runbooks/killswitch.md @@ -28,14 +28,52 @@ An operator holding the Platform permission `platform.killswitch.write`, a curre ## Switching a key off `PUT /api/platform/v1/killswitches/{key}` with body -`{"enabled": false, "ticket": "INC-123"}`. The answer is +`{"enabled": false, "ticket": "INC-123"}`, as shown in the +[operator access](operator-access.md#making-a-call) example. The answer is `{ "key", "before", "after", "correlationId" }`. `before` is `true` when no row existed, because absent and enabled mean the same. +Concurrent flips of one key take turns on the row, so each answer's `before` is the +previous flip's `after`, and a first flip of a key creates the row at the default before +it reads it. + Two audit rows are written under the platform sentinel, which no tenant can read: the entry into the platform scope, and the result row `tenancy.killswitch.toggle` with the before and after state and the operator's digest. The ticket is on those rows and in the -`reason` column of the switch's own row. Find them by the correlation id. +`reason` column of the switch's own row (empty again after a flip without one). Find the +rows by the correlation id. + +## Reading the record + +The sentinel rows are visible only to the platform credential, so a database +administrator reads them. By the correlation id the answer returned: + +```sql +SELECT timestamp, operation, reason, + metadata->'operator'->>'subjectDigest' AS operator_digest, + metadata->'operator'->>'ticket' AS ticket, + before_state, after_state +FROM audit_log +WHERE tenant_id = '00000000-0000-7000-8000-000000000002' + AND correlation_id = '' +ORDER BY timestamp; +``` + +The operator is recorded as a digest, never as the raw `sub`. To find every row one +operator wrote, compute their digest from the issuer and the `sub` and filter on +`metadata->'operator'->>'subjectDigest'`: + +```sh +printf 'learnstack.operator.subject.v1\n%s\n%s' "$ISSUER" "$SUB" \ + | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=' +``` + +The current state of a switch is its own row, if it has one: + +```sql +SELECT key, is_enabled, reason, toggled_at +FROM platform_killswitches WHERE key = ''; +``` ## When it takes effect @@ -52,12 +90,16 @@ the overlay's read-failure error, and repeat the flip if it appears. Send the same request with `"enabled": true`. There is no other restore, and no delete. Confirm by the response (`after` is `true`) and by the result row. -## If the answer is 503 +## If the answer is not 200 -The audit row could not be written, so the table was not changed. Repeat the request. +| Answer | What happened | What to do | +|---|---|---| +| 503 | The audit row could not be written, so the table was not changed | Repeat the request after `Retry-After` | +| 500 | Something failed unexpectedly. If it was the final commit, its outcome is unknown and the flip may have landed; the instance still dropped its cached copy | Read the switch's row (above) before repeating | +| 404 | The key is not one of the three in the table | Check the spelling | ## Not recoverable here A flip is not undone by the audit log: the log records it, and only another flip -reverses it. Two operators flipping the same key at once is last writer wins; the row -has no version, and both flips are in the audit log. +reverses it. Both flips of a pair are in the audit log with their true before and after +states. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 77d9adce..20ed48f6 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -17,43 +17,103 @@ The surface does not exist until an issuer is configured; with none, every | Setting | Meaning | |---|---| -| `PlatformOperator:Issuer` | The deployment-controlled OIDC issuer, for example the `learnstack-hub` realm. HTTPS only; loopback HTTP in Development | -| `PlatformOperator:AcceptedAcr` | The `acr` values that show the second factor. The shipped realm emits `mfa` | +| `PlatformOperator:Issuer` | The deployment-controlled OIDC issuer, for example the `learnstack-hub` realm. HTTPS only; loopback HTTP in Development. Never the tenant issuer | +| `PlatformOperator:AcceptedAcr` | The `acr` values that show the second factor. The shipped realm emits `mfa`. `0` and `1` are single-factor levels and are refused at start | | `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | -| `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, at most one hour; default 15 minutes | +| `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, as a time span such as `00:15:00`; at most one hour, default 15 minutes | | `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | - -Environment variables use double underscores, for example `PlatformOperator__Issuer`. - -A Self-Hosted issuer other than the shipped realm must issue access tokens with: -audience `learnstack-platform`; `azp` in the allowed list; an `acr` in the accepted list -that is reached only after a second factor; an `auth_time` claim; and a lifetime of at -most 15 minutes. If it cannot, no operator can act, by design. +| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the acts run under. Required for any act: without it the first act fails with an error that names this key | + +List settings are indexed in environment variables, and the double underscore is the +separator: + +```sh +PlatformOperator__Issuer=https://identity.example.com/realms/learnstack-hub +PlatformOperator__AcceptedAcr__0=mfa +PlatformOperator__AuthorizedParties__0=learnstack-operator +PlatformOperator__MaxAuthenticationAge=00:15:00 +PlatformOperator__Grants__0__Subject= +PlatformOperator__Grants__0__Permissions__0=platform.killswitch.write +``` + +A Self-Hosted issuer other than the shipped realm must issue access tokens that meet the +profile below. If it cannot, no operator can act, by design. + +## The token profile + +A token is accepted only when every line holds: + +- It is signed with RS256 by a key the issuer publishes, its header `typ` is `JWT`, and + it has not expired (30 seconds of clock skew). +- `iss` equals `PlatformOperator:Issuer` exactly. +- `aud` contains `learnstack-platform`. +- `azp` is one of `PlatformOperator:AuthorizedParties`. +- `acr` is one of `PlatformOperator:AcceptedAcr`. +- `auth_time` is present, not in the future, and no older than + `PlatformOperator:MaxAuthenticationAge`. +- `iat` and `exp` are present and `exp - iat` is at most 15 minutes. +- `sub` is present. + +Roles and every other claim carry no authority. To see what a token claims, decode its +middle segment: + +```sh +printf %s "$TOKEN" | cut -d. -f2 | tr '_-' '/+' \ + | awk '{ while (length($0) % 4) $0 = $0 "="; print }' | base64 -d | jq . +``` ## Getting a token The shipped realm provides the public client `learnstack-operator` (authorization code -with PKCE, redirect `http://127.0.0.1:8765/*`). The first login of the demo operator -asks it to set up an authenticator application. +with PKCE, redirect `http://127.0.0.1:8765/*`). In the compose stack the issuer is +`http://localhost:8080/realms/learnstack-hub`; the demo operator is +`demo-operator@learnstack.test` with the password `demo-dev-secret`, and its first login +asks it to set up an authenticator application (scan the code, or use the manual key +with any TOTP tool). 1. Make a verifier and its challenge: - `verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')` and - `challenge=$(printf %s "$verifier" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')`. -2. Open - `$ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator&response_type=code&scope=openid&redirect_uri=http://127.0.0.1:8765/callback&code_challenge=$challenge&code_challenge_method=S256&state=x` - and sign in with the password and the one-time code. + + ```sh + ISSUER=http://localhost:8080/realms/learnstack-hub + verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n') + challenge=$(printf %s "$verifier" | openssl dgst -sha256 -binary \ + | openssl base64 -A | tr '+/' '-_' | tr -d '=') + ``` + +2. Open this address in a browser. `prompt=login` makes the issuer ask again even when a + browser session exists; without it a stale `auth_time` is refused later: + + ```text + $ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator&response_type=code + &scope=openid&redirect_uri=http://127.0.0.1:8765/callback&prompt=login&state=x + &code_challenge=$challenge&code_challenge_method=S256 + ``` + + (one line; substitute the variables first), and sign in with the password and the + one-time code. 3. The browser lands on the callback address and shows a connection error. Copy `code` - from its address bar. -4. Redeem it: - `curl -s $ISSUER/protocol/openid-connect/token -d grant_type=authorization_code -d client_id=learnstack-operator -d redirect_uri=http://127.0.0.1:8765/callback -d code=$CODE -d code_verifier=$verifier`. - Use `access_token` as the bearer token. It lasts at most 15 minutes. + from its address bar into `CODE`. +4. Redeem it. The access token lasts at most 15 minutes: + + ```sh + TOKEN=$(curl -s "$ISSUER/protocol/openid-connect/token" \ + -d grant_type=authorization_code -d client_id=learnstack-operator \ + -d redirect_uri=http://127.0.0.1:8765/callback \ + -d code="$CODE" -d code_verifier="$verifier" | jq -r .access_token) + ``` ## Making a call -Send `Authorization: Bearer $TOKEN`. Every write may carry an optional `ticket` of 1 to -64 characters of `A-Z a-z 0-9 . _ : / # -`. The response carries a `correlationId`; -record it against your own ticket, because the audit rows a tenant can read never hold -the ticket. +Send `Authorization: Bearer $TOKEN` and `Content-Type: application/json`. Every write +may carry an optional `ticket` of 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`. The +response carries a `correlationId`; record it against your own ticket, because the audit +rows a tenant can read never hold the ticket. + +```sh +curl -sS -X PUT "$API/api/platform/v1/killswitches/killswitch.notifications.email" \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d '{"enabled": false, "ticket": "INC-123"}' +``` The operator contract is the document `/openapi/platform-v1.json`. It is served only when an issuer is configured and is not part of the tenant contract or SDK. @@ -67,6 +127,17 @@ provider that reloads (a file or a mounted secret) applies a change on the opera next act; one that cannot reload needs a restart. Withdrawal is the same edit, and it takes effect on the next act, not at the token's expiry. +**Grant only after the operator's authenticator exists.** In the shipped realm an +account that has no one-time-password credential is asked to enrol one at its first +login, and that login then carries `mfa`. Until the operator has enrolled, anyone who +knows the password could enrol their own device. So the order is: the operator signs in +once and sets up the authenticator, you confirm it in the realm's console, and only then +is the grant added. + +Password reset is switched off in the shipped realm, so a forgotten password or a lost +device is recovered by the realm's administrator, not by an emailed link that skips the +second factor. + The demo operator's grant is accepted in Development only; the process refuses to start in any other mode while it is present. Never import the shipped realm's demo user into a production realm. @@ -75,17 +146,31 @@ production realm. | Answer | Meaning | What to do | |---|---|---| -| 401, `Bearer` challenge | The token is missing, expired, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated more than the allowed age ago, or lives longer than 15 minutes | Sign in again; check the issuer settings | +| 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | | 403 | The token is good and this operator holds no grant for the act | Ask for the grant | | 400 | The ticket or the body is malformed | Fix the request | | 404 | Unknown killswitch key, or the surface is not configured | Check the key and the issuer setting | -| 503 | The audit row could not be written, so nothing changed | Retry; the act is safe to repeat | +| 415 | The body is not `application/json` | Send the header shown above | +| 503 | The audit row could not be written, so nothing changed. `Retry-After` says when to try again | Retry; the act is safe to repeat | +| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)) | -Signals: counters `learnstack.platform_operator.admissions`, `.refusals` and `.results`; -a Warning log for every refusal naming the operation and the operator's digest (event -7102 for a refused act, 7103 for a refused credential); and, for every admitted platform -act, the Warning log of the platform scope (event 7001). A refused operator leaves no -database row. +The answer to a refused credential is always the same; the reason is in the signals, not +the response. + +## Signals + +| Signal | Meaning | +|---|---| +| `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate | +| `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `InvalidTicket`, `MissingPermission`, `UnknownOperation`, `InvalidWitness` | +| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed | +| `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | +| `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs every operator is refused | + +A Warning log accompanies each: event 7102 for a refused act, 7103 for a refused +credential (with the cause), 7106 for a metadata failure; event 7105 is the Error log of +a refused audit write; and for every admitted platform act the Warning log of the +platform scope (event 7001). A refused operator leaves no database row. ## Not recoverable here diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index fe2a98ae..4aa2d439 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -925,9 +925,9 @@ CREATE POLICY platform_killswitches_read ON platform_killswitches USING (true); -- No write policy for learnstack_app, and no write privilege either — see the matrix --- below. Every toggle runs as learnstack_platform inside --- EnterPlatformAdminScope(reason), which is what gives tenancy.killswitch.toggle a real --- actor and a MUST-class audit row. No such caller ships in Packet 9 — see below. +-- below. Every toggle runs as learnstack_platform inside the admission-gated platform +-- scope, which is what gives tenancy.killswitch.toggle a MUST-class audit row that names +-- the operator. Its one writer shipped with P03-9 Step 1 — see below. ``` `USING (true)` widens nothing: there is no tenant term to widen, and the `GRANT` is what diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index 872bb808..cf266e1c 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -475,6 +475,11 @@ backend treat business rejections as system failures. | `learnstack_tenant_assertion_unresolved_total` | counter | dimension, source | | `learnstack_tenant_subject_admission_rejected_total` | counter | reason (`quota`, `registry_capacity`, `registry_fault`) | | `learnstack_tenant_subject_cleanup_failed_total` | counter | none | +| `learnstack_platform_operator_admissions_total` | counter | outcome (`admitted`, `refused`), operation (a registered slug or `unknown`) | +| `learnstack_platform_operator_refusals_total` | counter | cause (a closed set: token, profile and gate causes; [runbook](../runbooks/operator-access.md#signals)) | +| `learnstack_platform_operator_results_total` | counter | operation | +| `learnstack_platform_operator_audit_failures_total` | counter | operation | +| `learnstack_platform_operator_metadata_failures_total` | counter | none | | `learnstack_db_query_duration_seconds` | histogram | module, operation | | `learnstack_outbox_pending_count` | gauge | — | | `learnstack_outbox_dispatch_duration_seconds` | histogram | event_type | diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index ad90126d..96f41947 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -222,13 +222,13 @@ will raise them — which this standard requires it to do. matrix. A copy is a second answer that passes every comparison the moment it agrees, so the matrix → catalogue direction refuses it, and the catalogue → matrix direction compares every row that carries a slug rather than the first. -- **A row can carry both markers**. `tenancy.killswitch.toggle` is - `(off-path)` because every write runs inside `EnterPlatformAdminScope(reason)` rather - than through the pipeline, and `(planned)` because Packet 9 ships the table, the policies - and the read path but no writer — - [Phase 03](../roadmap/phase-03-identity-admin.md) owns the toggle command, its - Platform-scope permission and its runbook - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). +- **A row can carry both markers**. `tenancy.entitlement.refresh` is `(off-path)` + because its writer is a port method rather than a request, and `(planned)` because no + real provider exists yet. `tenancy.killswitch.toggle` carried both until P03-9 Step 1 + shipped its writer + ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)); it keeps + `(off-path)` because the write runs inside the platform scope rather than through the + pipeline. ## Baseline Coverage (LearnStack Core Modules) @@ -331,9 +331,13 @@ Rules: composite primary key `(id, timestamp)`. This describes ordinary resource reconciliation; [trusted denial occurrences](#trusted-authorization-evidence) instead retain one fixed key, timestamp and draft. -- `reason` is required when the operator is a platform admin acting on a tenant they are not a member of. It is `EnterPlatformAdminScope(reason)`'s short operator-authored slug naming the operation — never caller-supplied text — and it is surfaced in the tenant admin's audit view when the row targets that tenant. - Rows under the platform sentinel are visible to no tenant - ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 9, § 10). A refusal's cause is not a `reason`: it is the refusal's message key, in the `error_key` column. +- `reason` is required when the operator is a platform admin acting on a tenant they are + not a member of. It is the closed reason slug of the registered operator operation + (`PlatformOperation.ReasonSlug`) — never caller-supplied text — and it is surfaced in + the tenant admin's audit view when the row targets that tenant. Rows under the + platform sentinel are visible to no tenant + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 9, § 10). A refusal's + cause is not a `reason`: it is the refusal's message key, in the `error_key` column. - `correlationId` matches the trace id in logs and the value in the Problem Details response for failures. - `changes` is always a JSON **array** of `{ path, before, after }`, never the polymorphic object-or-array shape ADR-0016 described. A reader that has to branch on the shape gets diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 2612f74c..618766e6 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write`, `platform.tenant.write` (the registered catalogue of [ADR-0101](../decisions/0101-platform-operator-authority.md); other `platform.*` names are unregistered) | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write` (registered); `platform.tenant.write`, `platform.tenant_bootstrap.write` and the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue join with the step that ships the operation using them, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index f3fa4aab..58c9d931 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -5875,12 +5875,15 @@ structural test proves — and what it does not. #### `PlatformAdminScope_Entry_Requires_Platform_Permission` -- **Asserts:** entering the platform scope takes a `PlatformAdmission` and nothing else, and - the censuses that make an admission mean something are closed across every production - assembly: `PlatformAdmission.Minter` has exactly one subclass, the operator gate; - `PlatformOperatorWitness.Minter` has exactly one, the operator authentication boundary's; - `IPlatformOperatorGate` and `IPlatformOperatorGrantSource` each have exactly one - implementation. A second of any of them is how a permissive default ships. +- **Asserts:** entering the platform scope takes a `PlatformAdmission` and nothing else, + and the censuses that make an admission mean something are closed across every + production assembly: `PlatformAdmission.Minter` has exactly one subclass, the operator + gate; `PlatformOperatorWitness.Minter` has exactly one, the private nested minter of + `PlatformOperatorTokenProfile`; `IPlatformOperatorGate` and + `IPlatformOperatorGrantSource` each have exactly one implementation. The census + compares full type names and counts abstract subclasses, so a lookalike in another + namespace or an abstract stand-in is a failure. A second of any of them is how a + permissive default ships. - **Source:** ADR-0036 § The platform-admin override is not a resolution source; [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and § 8. - **Type:** xUnit — reflection over every production assembly, and behavioural cases without @@ -5898,11 +5901,26 @@ structural test proves — and what it does not. structural as well: `Only_The_Operator_Services_Hold_The_Platform_Scope` lists every file that may hold the scope, and no request handler is among them. +#### `The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only` + +- **Asserts:** the only source file that names `PlatformOperatorTokenProfile`, calls its + `TryRead` or names `PlatformOperatorWitness.Minter` is + `LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs`. A further caller + joins by an edit here: the offline rebind tool, in P03-9 Step 3. +- **Why it matters:** the witness is evidence that a token passed the closed profile, + and `TryRead` is the only door to the minter that makes one. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1 + review). +- **Phase:** P03-9. + #### `Only_The_Operator_Services_Hold_The_Platform_Scope` -- **Asserts:** the files that name `IPlatformAdminScope` are exactly the interface, the scope, - the persistence composition and the operator services that perform an admitted act - (today the killswitch toggle). Adding a service is a deliberate edit here, with its denied proof. +- **Asserts:** the files, by their path under `backend/src`, that name + `IPlatformAdminScope` are exactly the interface, the scope, the persistence + composition and the operator services that perform an admitted act (today the + killswitch toggle). Adding a service is a deliberate edit here, with its denied proof. - **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a tenant request path. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. @@ -5912,8 +5930,14 @@ structural test proves — and what it does not. #### `Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer` -- **Asserts:** the verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` against - `platform_killswitches` appear only in `KillswitchToggle`. The overlay's reads are unaffected. +- **Asserts:** the write verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` + against `platform_killswitches` appear only in `KillswitchToggle`, matched in any case + with an optional schema, quotes and `ONLY`, and that file uses `INSERT` and `UPDATE` + and never the other two. The overlay's reads and a `SELECT … FOR UPDATE` are + unaffected. A companion case, + `The_Killswitch_Write_Pattern_Can_Fail_And_Catches_The_Ordinary_Spellings`, checks the + pattern against shapes it must and must not catch, so a pattern that matches nothing + cannot pass the rule. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 13. - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). diff --git a/infra/compose/README.md b/infra/compose/README.md index c2549cf0..57868990 100644 --- a/infra/compose/README.md +++ b/infra/compose/README.md @@ -56,7 +56,12 @@ Two realms imported on first boot from `infra/keycloak/realms/`: - `learnstack` (tenant users) — confidential API and code/S256 web clients, with four declared tenant personas. The [realm guide](../keycloak/README.md) owns the exact identities, private secret source and callbacks. -- `learnstack-hub` (operators) — client `learnstack-hub-web` (public PKCE); demo user `demo-operator@learnstack.test` (`demo-dev-secret`). `CONFIGURE_TOTP` required-action present so the MFA flow surfaces in dev. +- `learnstack-hub` (operators) — clients `learnstack-hub-web` (the portal, public PKCE) + and `learnstack-operator` (LearnStack's platform surface, public PKCE with MFA + step-up); demo user `demo-operator@learnstack.test` (`demo-dev-secret`). + `CONFIGURE_TOTP` is a required action, so the first login sets up the authenticator + the step-up needs. A Keycloak volume from before the operator client keeps its old + realm; recreate it to import the new one. See [../keycloak/README.md](../keycloak/README.md) for the realm-isolation invariant, non-destructive reconciliation and the Phase 02b/03 wiring notes. diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index 110d030b..0850e6b1 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -196,10 +196,27 @@ has a pinned subject and sets up an authenticator at its first login; production for the realm stays [Phase 11](../../docs/roadmap/phase-11-production-hardening.md). A realm import into production never includes the demo user. -`learnstack-hub-web` keeps `fullScopeAllowed: true` as a development posture, because the Hub -operator portal maps the `hub-*` realm roles from its token. Narrowing it needs `scopeMappings` for -those roles and is coordinated with the Hub's operator-portal packet (P02c-4), since the realm export -is shared with the Hub repository. The `learnstack-operator` client is `false` and carries no realm +Three properties of the shared realm file that an operator of it should know: + +- **`browser-loa` is realm-wide.** It is the realm's browser flow, so the Hub portal's + login (`learnstack-hub-web`) goes through it too; the portal asks for no `acr`, so it + is satisfied at level 1 and sees no change. The file is shared with the Hub + repository, so a change to the flow is made in both. +- **Password reset is off.** `resetPasswordAllowed` is `false`: the reset-credentials + flow lets a user set a new password from an email link, which would be a second way to + a password that does not pass through the second factor. Operator credentials are + recovered by the realm administrator. The LearnStack scheme does not rely on this + alone: it accepts a token only when its `acr` is one the deployment lists, whatever + flow produced it. +- **An existing Keycloak volume keeps its old realm.** The import runs on an empty realm + only. A developer with a volume from before this change removes the volume (or the + realm) and starts again to get the flow, the client and the pinned demo subject. + +`learnstack-hub-web` keeps `fullScopeAllowed: true` as a development posture, because +the Hub operator portal maps the `hub-*` realm roles from its token. Narrowing it needs +`scopeMappings` for those roles and is coordinated with the Hub's operator-portal packet +(P02c-4), since the realm export is shared with the Hub repository. The +`learnstack-operator` client sets `fullScopeAllowed` to `false` and carries no realm roles. The procedure for getting a token is the [operator access runbook](../../docs/runbooks/operator-access.md). @@ -219,8 +236,10 @@ against it, including the host's default organization where applicable. [earlier adjustment](../../docs/roadmap/phase-02b-delivery-log.md#account-console-self-service-capability--proposal-2026-10-21) granted is retired by [ADR-0099](../../docs/decisions/0099-confined-tenant-federation.md): see [Account self-service retirement](#account-self-service-retirement). -- The operator account remains `demo-operator@learnstack.test`; its separate - realm is untouched. Neither realm's token is accepted by the other surface. +- The operator account remains `demo-operator@learnstack.test` in its separate realm, + which now also carries the `learnstack-operator` client and the `browser-loa` flow + ([above](#realms-and-accounts)). Neither realm's token is accepted by the other + surface. ## Local access and private sources diff --git a/infra/keycloak/realms/learnstack-hub.json b/infra/keycloak/realms/learnstack-hub.json index b792b670..029b3033 100644 --- a/infra/keycloak/realms/learnstack-hub.json +++ b/infra/keycloak/realms/learnstack-hub.json @@ -8,7 +8,7 @@ "verifyEmail": true, "loginWithEmailAllowed": true, "duplicateEmailsAllowed": false, - "resetPasswordAllowed": true, + "resetPasswordAllowed": false, "editUsernameAllowed": false, "bruteForceProtected": true, "permanentLockout": false, From e18032c4c6b1c5f01eae943a4dbb24aebe6d1cfb Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 16:45:23 +0300 Subject: [PATCH 06/28] fix(platform): close P03-9 step 1 review round 2 findings Round 2 found no Blocker. The gate now reads the grant before the ticket and the endpoint reads the body after the gate, so an ungranted operator learns nothing from a 400 or 415. Operator metadata gets a failure backoff and a 15-minute bound on keys a failed refresh could not renew. The killswitch writer leaves `reason` NULL (the ticket stays out of a table the application role reads; ADR-0101 erratum and Amendment 1, ADR-0045 Amendment 6), takes its time under the row lock and abandons a toggle whose lock or update found no row. The scope facade makes the result row its last write, refuses statements that name the audit log and validates result state as JSON. The platform credential refuses pool settings that let session state outlive a scope, the operator OpenAPI document gets a title, scheme, body and statuses, and the overlay's events are searchable. Two realm tests pin that a password-only account-console session cannot remove or add an authenticator. Runbooks and seven stale statements are corrected. ADR: 0101, 0045 Module: Tenancy, Audit, Api Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorAuthentication.cs | 41 +++- .../PlatformOperatorDocumentTransformer.cs | 135 +++++++++++++ .../PlatformOperatorMetadata.cs | 71 ++++++- .../PersistenceCompositionExtensions.cs | 10 + .../Platform/PlatformOperatorEndpoints.cs | 59 +++++- .../Versioning/ApiVersioningExtensions.cs | 1 + .../MultiTenancy/PlatformAdminScope.cs | 74 +++++++- .../PlatformOperator/PlatformOperatorGate.cs | 11 +- .../PlatformOperatorMetrics.cs | 11 +- .../KillswitchOverlay.cs | 4 +- .../KillswitchToggle.cs | 26 ++- .../Database/KillswitchToggleOrderingTests.cs | 33 +++- .../Database/PlatformAdminScopeTests.cs | 60 +++++- .../PlatformOperatorHttpTests.cs | 178 +++++++++++++++++- .../TenancyIdentity/KeycloakBrowserFlow.cs | 4 +- .../PlatformOperatorRealmTests.cs | 63 +++++++ .../PlatformOperatorAuthenticationTests.cs | 63 +++++++ .../PlatformOperatorMetadataHealthTests.cs | 103 ++++++++++ ...PlatformCredentialConnectionStringTests.cs | 32 ++++ .../MultiTenancy/PlatformAdminGateTests.cs | 62 +++++- docs/architecture/21-feature-flags.md | 11 +- docs/architecture/31-audit-subsystem.md | 13 +- ...045-entitlement-and-feature-flag-socket.md | 19 +- .../0101-platform-operator-authority.md | 19 ++ docs/glossary.md | 2 +- docs/modules/tenancy/README.md | 6 +- docs/modules/tenancy/permissions.md | 4 +- docs/roadmap/phase-03-delivery-log.md | 119 +++++++++++- docs/roadmap/phase-03-identity-admin.md | 21 ++- docs/runbooks/README.md | 6 +- docs/runbooks/killswitch.md | 33 ++-- docs/runbooks/operator-access.md | 50 ++--- docs/standards/05-database.md | 17 +- docs/standards/19-permissions.md | 6 +- docs/standards/20-infrastructure-stack.md | 6 +- .../21-architecture-tests-catalogue.md | 56 +++--- infra/keycloak/README.md | 23 ++- 37 files changed, 1288 insertions(+), 164 deletions(-) create mode 100644 backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs index 8c036484..10a6e2f1 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs @@ -37,8 +37,11 @@ namespace LearnStack.Api.Authentication; /// /// Bounded metadata. The discovery document and key set come through a client of the /// scheme's own that follows no redirect, waits five seconds, reads at most 256 KB and fetches -/// nothing outside the issuer's origin. The last known good configuration is off: an issuer -/// that cannot be reached refuses every operator, which is the safe side of an outage. +/// nothing outside the issuer's origin. A failed fetch makes the next one fail at once for 30 +/// seconds, and keys that a failed refresh could not renew for 15 minutes are no longer trusted +/// (): an issuer that stays unreachable refuses every +/// operator, which is the safe side of an outage. The stock manager's own last-known-good fallback +/// is off. /// /// internal static class PlatformOperatorAuthentication @@ -65,12 +68,14 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( services.AddSingleton(settings); services.TryAddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddAuthentication().AddJwtBearer(Scheme, _ => { }); services.AddAuthorization(options => options.AddPolicy( PolicyName, policy => policy.AddAuthenticationSchemes(Scheme).RequireAuthenticatedUser())); services.AddOptions(Scheme) - .Configure, ILogger>( - (options, backchannel, clock, logger, retrieverLogger) => + .Configure, ILogger, + PlatformOperatorMetadataHealth>( + (options, backchannel, clock, logger, retrieverLogger, health) => { options.Authority = settings.Issuer; options.MetadataAddress = settings.MetadataAddress; @@ -85,7 +90,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( options.ConfigurationManager = new ConfigurationManager( settings.MetadataAddress, new OpenIdConnectConfigurationRetriever(), - new PlatformOperatorDocumentRetriever(settings, backchannel, retrieverLogger), + new PlatformOperatorDocumentRetriever(settings, backchannel, health, retrieverLogger), new PlatformOperatorConfigurationValidator(settings)) { AutomaticRefreshInterval = options.AutomaticRefreshInterval, @@ -111,7 +116,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( LogTokenId = false, IncludeTokenOnFailedValidation = false, }; - options.Events = new PlatformOperatorEvents(settings, clock, logger); + options.Events = new PlatformOperatorEvents(settings, clock, health, logger); }); return services; } @@ -125,7 +130,10 @@ internal sealed class PlatformOperatorFeature(PlatformOperatorWitness witness) /// Scopes the scheme to its prefix and applies the closed token profile. internal sealed class PlatformOperatorEvents( - PlatformOperatorSettings settings, IClock clock, ILogger logger) : JwtBearerEvents + PlatformOperatorSettings settings, + IClock clock, + PlatformOperatorMetadataHealth health, + ILogger logger) : JwtBearerEvents { public override Task MessageReceived(MessageReceivedContext context) { @@ -154,6 +162,12 @@ public override Task TokenValidated(TokenValidatedContext context) // The correlation id is the request's trace when one exists and the server's request // id otherwise, so a result row is never recorded without a handle an operator can use. var correlationId = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier; + if (health.IsStale()) + { + context.Fail(new PlatformOperatorProfileException("metadata_stale")); + return Task.CompletedTask; + } + if (context.SecurityToken is not JsonWebToken token) { context.Fail(new PlatformOperatorProfileException("token_invalid")); @@ -183,7 +197,10 @@ public override Task Challenge(JwtBearerChallengeContext context) { // One answer for a missing, malformed, expired or wrongly profiled credential: no // detail a probing caller could use, a counter and a log an operator can alert on. - var cause = PlatformOperatorFailure.Classify(context.AuthenticateFailure); + // A caller that hung up mid-validation is not an issuer fault, whatever exception the abort raised. + var cause = context.HttpContext.RequestAborted.IsCancellationRequested && context.AuthenticateFailure is not null + ? "request_aborted" + : PlatformOperatorFailure.Classify(context.AuthenticateFailure); PlatformOperatorMetrics.Unauthenticated(cause); LogUnauthenticated(logger, cause, context.AuthenticateFailure?.GetType().Name ?? "none", null); context.HandleResponse(); @@ -339,12 +356,18 @@ internal static bool TryRead( return false; } - if (!token.TryGetPayloadValue("iat", out var iat) || !IsUnixSeconds(iat) || token.ValidTo == DateTime.MinValue) + if (!token.TryGetPayloadValue("iat", out var iat) || !IsUnixSeconds(iat)) { cause = PlatformOperatorTokenCause.IssuedAt; return false; } + if (token.ValidTo == DateTime.MinValue) + { + cause = PlatformOperatorTokenCause.Lifetime; + return false; + } + if (!token.TryGetPayloadValue("auth_time", out var authTime) || !IsUnixSeconds(authTime)) { cause = PlatformOperatorTokenCause.AuthenticationTime; diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs new file mode 100644 index 00000000..1e2e945b --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -0,0 +1,135 @@ +using LearnStack.Api.PublicReads; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; + +namespace LearnStack.Api.Authentication; + +/// +/// Gives the operator contract (document platform-v1) what a client author needs and the +/// default generator leaves out: a title, a stable servers list, the bearer scheme with the +/// token profile, and every status an operator can meet (ADR-0101 § 4). +/// +/// +/// servers is dropped for the reason the tenant document drops it: it is derived from the +/// caller's Host header, which no client input may decide. +/// +internal sealed class PlatformOperatorDocumentTransformer(string documentName) : IOpenApiDocumentTransformer +{ + internal const string Description = + "Operator-only platform operations. Authenticate with a short-lived access token issued by the " + + "deployment's operator issuer to the client learnstack-operator after a second factor; the token " + + "profile and the runbooks are in docs/runbooks/operator-access.md. Authentication grants no " + + "permission: each operation needs a Platform grant held by LearnStack and evaluated on every act."; + + public async Task TransformAsync( + OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(document); + document.Info.Title = "LearnStack Platform Operator API"; + document.Info.Version = documentName; + document.Info.Description = Description; + document.Servers?.Clear(); + + document.Components ??= new OpenApiComponents(); + document.Components.Schemas ??= new Dictionary(); + document.Components.Schemas["ProblemDetails"] = PublicReadDocumentTransformer.Problem(); + document.Components.SecuritySchemes ??= new Dictionary(); + document.Components.SecuritySchemes[PlatformOperatorAuthentication.Scheme] = new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = "bearer", + BearerFormat = "JWT", + Description = "A signed RS256 access token from the operator issuer: audience learnstack-platform, " + + "authorized party learnstack-operator, an accepted acr that shows the second factor, a recent " + + "auth_time, and a lifetime of at most 15 minutes.", + }; + + foreach (var path in document.Paths.Values) + { + if (path.Operations is null) + { + continue; + } + + foreach (var operation in path.Operations.Values) + { + operation.Security = + [ + new OpenApiSecurityRequirement + { + [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, document)] = [], + }, + ]; + DescribeResponses(document, operation); + if (operation.RequestBody is null) + { + // Declared here and not through `Accepts` on the endpoint: that metadata makes routing + // reject any other content type itself, before the handler can answer 415 as a problem. + var schema = await context.GetOrCreateSchemaAsync( + typeof(Platform.KillswitchToggleRequest), null, cancellationToken); + operation.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary { ["application/json"] = new() { Schema = schema } }, + }; + } + } + } + } + + private static void DescribeResponses(OpenApiDocument document, OpenApiOperation operation) + { + operation.Responses ??= []; + foreach (var (status, description) in Statuses) + { + operation.Responses[status] = new OpenApiResponse + { + Description = description, + Content = new Dictionary + { + ["application/problem+json"] = new() { Schema = new OpenApiSchemaReference("ProblemDetails", document) }, + }, + }; + } + + foreach (var (status, response) in operation.Responses) + { + if (response is not OpenApiResponse concrete) + { + continue; + } + + concrete.Headers ??= new Dictionary(); + if (status == "401") + { + concrete.Headers["WWW-Authenticate"] = new OpenApiHeader + { + Required = true, + Schema = new OpenApiSchema { Type = JsonSchemaType.String }, + Description = "Always Bearer; a refused credential is never explained in the response.", + }; + } + + if (status == "503") + { + concrete.Headers["Retry-After"] = new OpenApiHeader + { + Required = true, + Description = "Suggested retry delay in seconds; the act is safe to repeat.", + Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Minimum = "0" }, + }; + } + } + } + + private static readonly (string Status, string Description)[] Statuses = + [ + ("400", "validation_failed: the body is malformed, the required state is missing, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -."), + ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), + ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), + ("404", "not_found: the key is not a declared killswitch."), + ("415", "unsupported_media_type: the body is not application/json."), + ("500", "internal_error: an unexpected failure. A toggle whose final commit's outcome is unknown may have landed; read the switch before repeating."), + ("503", "audit_unavailable: the audit row could not be written, so nothing changed."), + ]; +} diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs index cf5d3e7f..ca23e027 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorMetadata.cs @@ -1,4 +1,5 @@ using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Time; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; @@ -44,6 +45,60 @@ internal PlatformOperatorBackchannel(SocketsHttpHandler handler) public void Dispose() => Client.Dispose(); } +/// +/// What the scheme knows about the health of its issuer metadata: when a fetch last succeeded and +/// last failed. +/// +/// +/// +/// Two decisions hang on it. While a fetch failed less than ago, +/// the next fetch fails at once instead of waiting on the network, so an issuer that is down cannot +/// hold a queue of unauthenticated requests each for the transport timeout. And when the newest +/// attempt failed and the last success is older than , tokens are +/// refused: the stock manager keeps serving the keys it last fetched when a refresh fails, which is +/// right for a blip and wrong for a key the issuer has since withdrawn. +/// +/// +/// A manager that has not tried to refresh has recorded no failure, so the first request after a long +/// idle still validates against the keys fetched before it, and triggers the refresh that records the +/// outcome. +/// +/// +internal sealed class PlatformOperatorMetadataHealth(IClock clock) +{ + /// How long after a failed fetch the next one is refused without trying. + internal static readonly TimeSpan RetryBackoff = TimeSpan.FromSeconds(30); + + /// How old the last successful fetch may be once a later one has failed. + internal static readonly TimeSpan MaximumStaleness = TimeSpan.FromMinutes(15); + + private long _lastSuccessTicks; + private long _lastFailureTicks; + + internal void RecordSuccess() => Volatile.Write(ref _lastSuccessTicks, clock.UtcNow.UtcTicks); + + internal void RecordFailure() => Volatile.Write(ref _lastFailureTicks, clock.UtcNow.UtcTicks); + + /// Whether a fetch failed within the backoff and none has succeeded since. + internal bool InBackoff() + { + // A failure and a success in the same tick count as the failure being later: the safe reading. + var failure = Volatile.Read(ref _lastFailureTicks); + return failure > 0 + && failure >= Volatile.Read(ref _lastSuccessTicks) + && clock.UtcNow.UtcTicks - failure < RetryBackoff.Ticks; + } + + /// Whether keys are being served that a failed refresh could not renew in time. + internal bool IsStale() + { + var success = Volatile.Read(ref _lastSuccessTicks); + return success > 0 + && Volatile.Read(ref _lastFailureTicks) >= success + && clock.UtcNow.UtcTicks - success > MaximumStaleness.Ticks; + } +} + /// /// Fetches the discovery document and the key set, and nothing at another origin. /// @@ -55,21 +110,31 @@ internal PlatformOperatorBackchannel(SocketsHttpHandler handler) internal sealed class PlatformOperatorDocumentRetriever( PlatformOperatorSettings settings, PlatformOperatorBackchannel backchannel, + PlatformOperatorMetadataHealth health, ILogger logger) : IDocumentRetriever { private const string Refusal = "Platform operator metadata refused."; public async Task GetDocumentAsync(string address, CancellationToken cancel) { + if (health.InBackoff()) + { + // Not counted or logged again: the failure that opened the window was. + throw new IOException(Refusal); + } + try { - return await ReadAsync(address, cancel); + var document = await ReadAsync(address, cancel); + health.RecordSuccess(); + return document; } catch (Exception failure) when (failure is not OperationCanceledException || !cancel.IsCancellationRequested) { // The request that triggered the fetch only learns that it found no key. The failure is // counted and logged here, where it happens, because an issuer that cannot be reached - // refuses every operator and that is a state an operator of the platform must see. + // refuses new operators and that is a state an operator of the platform must see. + health.RecordFailure(); PlatformOperatorMetrics.MetadataFailed(); LogMetadataFailed(logger, failure.GetType().Name, null); throw; @@ -103,7 +168,7 @@ private async Task ReadAsync(string address, CancellationToken cancel) LoggerMessage.Define( LogLevel.Warning, new EventId(7106, nameof(LogMetadataFailed)), - "Platform operator issuer metadata could not be read ({FailureType}); operators are refused until it can."); + "Platform operator issuer metadata could not be read ({FailureType}); new keys are not learned, and operators are refused once the keys already held are too old."); } /// Discovery cannot widen the issuer authority the stock manager trusts. diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index 4983bc60..d29fa85d 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -504,6 +504,16 @@ internal static void ValidatePlatformConnectionString(string? connectionString) + "connection string. It must be key/value form, not a URI DSN.", failure); } + // Session state must not outlive a scope on a pool whose connections see every tenant: the + // sibling privileged sources pin these off, and this one refuses a string that turns them on. + if (parsed.NoResetOnClose || parsed.Multiplexing) + { + throw new InvalidOperationException( + $"ConnectionStrings:{PlatformConnectionName} turns on 'No Reset On Close' or 'Multiplexing'. " + + "Either would let session state set in one platform scope reach the next on a connection " + + "that bypasses row level security, so the credential must leave both off."); + } + if (!string.Equals(parsed.Username, PlatformRole, StringComparison.Ordinal)) { var observed = string.IsNullOrEmpty(parsed.Username) ? "" : parsed.Username; diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index c88df1ff..4dffd693 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -1,5 +1,7 @@ using LearnStack.Api.Authentication; using System.ComponentModel.DataAnnotations; +using System.Text.Json; +using Microsoft.AspNetCore.Http.Features; using LearnStack.Api.Common; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Audit; @@ -20,7 +22,7 @@ internal sealed record KillswitchToggleRequest( string? Ticket); /// What a toggle changed, with the correlation id the operator records. -internal sealed record KillswitchToggleResponse(string Key, bool Before, bool After, string? CorrelationId); +internal sealed record KillswitchToggleResponse(string Key, bool Before, bool After, string CorrelationId); /// /// The platform operator surface: minimal endpoints under /api/platform/v1, present only @@ -62,13 +64,52 @@ internal static WebApplication MapLearnStackPlatformOperator(this WebApplication .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status403Forbidden) .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status415UnsupportedMediaType) + .ProducesProblem(StatusCodes.Status500InternalServerError) .ProducesProblem(StatusCodes.Status503ServiceUnavailable); return app; } + // The body is read by the handler and not bound by the framework, so that a body that cannot be + // read is answered only after admission: binding runs before any handler code, and an ungranted + // operator would otherwise learn from a 400 or 415 that their request was inspected. + private enum BodyState { Read, Missing, NotJson, Malformed } + + private const int MaximumBodyBytes = 4096; + + private static async Task<(KillswitchToggleRequest? Body, BodyState State)> ReadBodyAsync( + HttpRequest request, CancellationToken cancellationToken) + { + if (request.ContentLength is 0 || (request.ContentLength is null && !request.Headers.ContainsKey("Transfer-Encoding"))) + { + return (null, BodyState.Missing); + } + + if (!request.HasJsonContentType()) + { + return (null, BodyState.NotJson); + } + + var limit = request.HttpContext.Features.Get(); + if (limit is { IsReadOnly: false }) + { + limit.MaxRequestBodySize = MaximumBodyBytes; + } + + try + { + var body = await JsonSerializer.DeserializeAsync( + request.Body, JsonSerializerOptions.Web, cancellationToken); + return body is null ? (null, BodyState.Malformed) : (body, BodyState.Read); + } + catch (JsonException) + { + return (null, BodyState.Malformed); + } + } + private static async Task ToggleKillswitchAsync( string key, - KillswitchToggleRequest? body, HttpContext http, IPlatformOperatorGate gate, IKillswitchToggle toggle, @@ -81,8 +122,10 @@ private static async Task ToggleKillswitchAsync( return Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); } - // Admission first: an operator without the grant learns nothing about the body, so a - // malformed request is answered 400 only to someone who may act at all. + // Admission first: the gate checks the grant before the ticket, so an operator without + // the grant is answered 403 whatever the request carries, and a body that cannot be used is + // answered 400 or 415 only to someone who may act at all. + var (body, bodyState) = await ReadBodyAsync(http.Request, cancellationToken); var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body?.Ticket, cancellationToken); if (!admission.IsAdmitted) { @@ -94,6 +137,11 @@ private static async Task ToggleKillswitchAsync( }; } + if (bodyState == BodyState.NotJson) + { + return Problem(http, StatusCodes.Status415UnsupportedMediaType, "lockey_unsupported_media_type"); + } + if (body?.Enabled is not { } enabled) { return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); @@ -103,7 +151,8 @@ private static async Task ToggleKillswitchAsync( { var result = await toggle.ToggleAsync(admission.Admission!, new KillswitchKey(key), enabled, cancellationToken); return result.Outcome == KillswitchToggleOutcome.Applied - ? Results.Ok(new KillswitchToggleResponse(key, result.Before, result.After, admission.Admission!.Operator.CorrelationId)) + ? Results.Ok(new KillswitchToggleResponse( + key, result.Before, result.After, admission.Admission!.Operator.CorrelationId ?? http.TraceIdentifier)) : Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"); } catch (AuditWriteFailedException failure) diff --git a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs index e64b2aa6..615ecf9d 100644 --- a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs +++ b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs @@ -172,6 +172,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorOpenApiDocument( options.ShouldInclude = api => api.RelativePath?.StartsWith("api/platform/v1/", StringComparison.OrdinalIgnoreCase) == true; options.AddSchemaTransformer(new StronglyTypedIdSchemaTransformer()); + options.AddDocumentTransformer(new Authentication.PlatformOperatorDocumentTransformer(documentName)); }); return services; } diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index b256024c..f24128ff 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -199,12 +199,18 @@ public async Task EnterAsync( // back whatever is open on it. The connection disposal below is the one the // refused-entry case kills, and it is in the same catch because an entry that // threw must not keep the one connection that sees every tenant. - if (transaction is not null) + try { - await transaction.DisposeAsync(); + if (transaction is not null) + { + await transaction.DisposeAsync(); + } + } + finally + { + await connection.DisposeAsync(); } - await connection.DisposeAsync(); throw; } } @@ -258,6 +264,11 @@ private async Task WriteResultAsync( throw new ArgumentException("A result row needs an assigned tenant.", nameof(result)); } + // A caller's state is checked here, as a programming error, before it can reach the database + // and come back as a write failure the endpoint would report as an audit outage. + RequireJsonState(result.BeforeState, nameof(result.BeforeState)); + RequireJsonState(result.AfterState, nameof(result.AfterState)); + // The ticket stays out of a row a tenant can read: it appears only under the sentinel. var isSentinel = result.TenantId == TenantId.PlatformSentinel; var draft = new AuditEntryDraft @@ -292,6 +303,30 @@ await services.ServiceProvider .WritePlatformOperatorResultAsync(draft, admission, connection, transaction, cancellationToken); } + private const int MaximumStateBytes = 32 * 1024; + + private static void RequireJsonState(string? state, string name) + { + if (state is null) + { + return; + } + + if (System.Text.Encoding.UTF8.GetByteCount(state) > MaximumStateBytes) + { + throw new ArgumentException($"The {name} of a result row is larger than {MaximumStateBytes} bytes.", name); + } + + try + { + using var document = System.Text.Json.JsonDocument.Parse(state); + } + catch (System.Text.Json.JsonException) + { + throw new ArgumentException($"The {name} of a result row is not well-formed JSON.", name); + } + } + /// /// The row one entry writes: the sentinel tenant, the catalogue's tier, the operator and /// the caller's provenance. @@ -357,7 +392,7 @@ private static string OperatorMetadata(PlatformAdmission admission, bool include + ",\"executor\":" + AuditJson.Quote(op.Executor) + (includeTicket && admission.Ticket is not null ? ",\"ticket\":" + AuditJson.Quote(admission.Ticket) : string.Empty) + "}}"; - return AuditJson.CapObject(json); + return json; } private static string Provenance(string? callerMember, string? callerFile, int callerLine) => @@ -403,6 +438,16 @@ private static string ShortPath(string? path) /// statement that threw leaves PostgreSQL's transaction aborted, so a later commit would /// silently roll back. A read-only scope has nothing to commit and ends by disposal. /// + /// + /// The result row is last. A statement after it could change state the row does not + /// describe, so the facade refuses one. No statement may name audit_log either: the + /// platform role holds audit maintenance rights for retention, and a scope that rewrote the + /// record of its own act would defeat it. + /// + /// + /// One owner. A handle is used by the single call that entered it, on one logical + /// thread; it is not safe for concurrent use. + /// /// private sealed class Handle( NpgsqlConnection connection, @@ -423,6 +468,7 @@ public async Task ExecuteAsync( string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) { EnsureUsable(); + EnsureStatementsAllowed(); await using var command = Build(sql, parameters); try { @@ -442,6 +488,7 @@ public async Task> QueryAsync( CancellationToken cancellationToken = default) { EnsureUsable(); + EnsureStatementsAllowed(); ArgumentNullException.ThrowIfNull(map); await using var command = Build(sql, parameters); try @@ -469,8 +516,10 @@ public async Task WriteResultAsync(PlatformResult result, CancellationToken canc { await writeResult(result, cancellationToken); } - catch + catch (Exception failure) when (failure is not ArgumentException) { + // An argument the scope refused before it wrote anything leaves the transaction intact; + // anything else may have left it aborted. _faulted = true; throw; } @@ -574,6 +623,21 @@ private static void RequireOneStatement(string sql) "A platform scope statement is a single SELECT, INSERT, UPDATE, DELETE or WITH statement.", nameof(sql)); } + + if (text.Contains("audit_log", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("A platform scope statement cannot name the audit log.", nameof(sql)); + } + } + + private void EnsureStatementsAllowed() + { + if (_resultWritten) + { + throw new InvalidOperationException( + "A platform scope's result row is its last write. A statement after it could change " + + "state the row does not describe; run it before the row."); + } } private void EnsureUsable() diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs index 8ab7b6f9..8c42bf4b 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorGate.cs @@ -46,14 +46,17 @@ public async ValueTask AdmitAsync( return Refuse(PlatformRefusal.UnknownOperation, null, operatorWitness); } - if (!PlatformTicket.IsValid(ticket)) + // The grant first, then the ticket: an operator without the grant is refused as such whatever + // the request carries, so a malformed body teaches them nothing and their attempt is counted + // under the cause an alert on ungranted operators watches. + if (!await _grants.IsGrantedAsync(operatorWitness.SubjectDigest, operation.Permission.Key, cancellationToken)) { - return Refuse(PlatformRefusal.InvalidTicket, operation, operatorWitness); + return Refuse(PlatformRefusal.MissingPermission, operation, operatorWitness); } - if (!await _grants.IsGrantedAsync(operatorWitness.SubjectDigest, operation.Permission.Key, cancellationToken)) + if (!PlatformTicket.IsValid(ticket)) { - return Refuse(PlatformRefusal.MissingPermission, operation, operatorWitness); + return Refuse(PlatformRefusal.InvalidTicket, operation, operatorWitness); } PlatformOperatorMetrics.Admitted(operation); diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index e5e64204..6b8bb3c0 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -60,9 +60,18 @@ public static void Refused(PlatformRefusal refusal, PlatformOperation? operation { Admissions.Add(1, new KeyValuePair("outcome", "refused"), new KeyValuePair("operation", operation?.AuditSlug ?? "unknown")); - Refusals.Add(1, new KeyValuePair("cause", refusal.ToString())); + Refusals.Add(1, new KeyValuePair("cause", Cause(refusal))); } + private static string Cause(PlatformRefusal refusal) => refusal switch + { + PlatformRefusal.InvalidWitness => "invalid_witness", + PlatformRefusal.UnknownOperation => "unknown_operation", + PlatformRefusal.InvalidTicket => "invalid_ticket", + PlatformRefusal.MissingPermission => "missing_permission", + _ => "unknown", + }; + /// Counts a pre-authentication refusal, which never reaches the gate. public static void Unauthenticated(string cause) => Refusals.Add(1, new KeyValuePair("cause", cause)); diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs index 58b38ba4..4a32a816 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs @@ -173,12 +173,12 @@ private static async ValueTask CleanupUnownedAsync(NpgsqlDataReader? reader, Npg private static readonly Action LogReadFailed = LoggerMessage.Define( LogLevel.Error, - new EventId(1, nameof(LogReadFailed)), + new EventId(7107, nameof(LogReadFailed)), "The killswitch overlay could not be read for {Key}; it resolved to the key's default, which is enabled. A cache or database outage must not disable every gated path platform-wide."); private static readonly Action LogUndeclared = LoggerMessage.Define( LogLevel.Error, - new EventId(2, nameof(LogUndeclared)), + new EventId(7108, nameof(LogUndeclared)), "'{Key}' is not in KillswitchKeys, so nothing can flip it and no gated path should be reading it. It resolved to enabled."); } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs index 33952c80..1a133d46 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs @@ -46,8 +46,11 @@ public sealed partial class KillswitchToggle( private const string SelectBefore = "SELECT is_enabled FROM platform_killswitches WHERE key = @key FOR UPDATE"; + // `reason` stays NULL: the application role can read this table, and the ticket never appears in + // a row a tenant's connection can reach (ADR-0101 § 9, as corrected in Amendment 1). The ticket is + // on the sentinel audit rows. private const string Update = - "UPDATE platform_killswitches SET is_enabled = @enabled, reason = @reason, " + "UPDATE platform_killswitches SET is_enabled = @enabled, reason = NULL, " + "toggled_at = @at, toggled_by = NULL WHERE key = @key"; /// @@ -70,13 +73,12 @@ public async Task ToggleAsync( { await using var handle = await scope.EnterAsync(admission, cancellationToken); - var at = clock.UtcNow; await handle.ExecuteAsync( EnsureRow, [ new PlatformSqlParameter("key", key.Value), new PlatformSqlParameter("default", registryDefault), - new PlatformSqlParameter("at", at), + new PlatformSqlParameter("at", clock.UtcNow), ], cancellationToken); @@ -85,17 +87,29 @@ await handle.ExecuteAsync( [new PlatformSqlParameter("key", key.Value)], reader => reader.GetBoolean(0), cancellationToken); + if (rows.Count != 1) + { + throw new InvalidOperationException( + "The killswitch row was not there to lock after it was created; the toggle is abandoned."); + } + var before = rows[0]; - await handle.ExecuteAsync( + // The time is taken under the row lock, so a toggle that waited for another stamps the + // later time and the column agrees with the order of the result rows. + var updated = await handle.ExecuteAsync( Update, [ new PlatformSqlParameter("key", key.Value), new PlatformSqlParameter("enabled", enabled), - new PlatformSqlParameter("reason", admission.Ticket), - new PlatformSqlParameter("at", at), + new PlatformSqlParameter("at", clock.UtcNow), ], cancellationToken); + if (updated != 1) + { + throw new InvalidOperationException( + "The killswitch update changed no row, so no result row describes it; the toggle is abandoned."); + } await handle.WriteResultAsync( new PlatformResult( diff --git a/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs index 1399e8ad..dbf8657a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs @@ -54,6 +54,32 @@ public async Task A_Failure_Before_The_Commit_Leaves_The_Cache_Alone() handle.CommitCalls.Should().Be(0); } + [Fact] + public async Task A_Row_That_Is_Not_There_To_Lock_Abandons_The_Toggle_Without_A_Result_Row() + { + var handle = new ScriptedHandle { LockedRows = 0 }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync().WithMessage("*not there to lock*"); + handle.Steps.Should().NotContain("result").And.NotContain("commit"); + cache.Removed.Should().Be(0); + } + + [Fact] + public async Task An_Update_That_Changes_No_Row_Never_Gets_A_Result_Row_Describing_It() + { + var handle = new ScriptedHandle { UpdatedRows = 0 }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync().WithMessage("*changed no row*"); + handle.Steps.Should().NotContain("result").And.NotContain("commit"); + cache.Removed.Should().Be(0); + } + [Fact] public async Task The_Commit_Is_Not_Cancellable_By_The_Caller() { @@ -108,6 +134,8 @@ private sealed class ScriptedHandle : IPlatformAdminScopeHandle { public Exception? CommitFailure { get; init; } public Exception? ResultFailure { get; init; } + public int LockedRows { get; init; } = 1; + public int UpdatedRows { get; init; } = 1; public List Steps { get; } = []; public List Statements { get; } = []; public int CommitCalls { get; private set; } @@ -119,7 +147,7 @@ public Task ExecuteAsync( { Steps.Add("exec:" + sql.Split(' ')[0]); Statements.Add(sql); - return Task.FromResult(1); + return Task.FromResult(sql.StartsWith("UPDATE", StringComparison.Ordinal) ? UpdatedRows : 1); } public Task> QueryAsync( @@ -128,7 +156,8 @@ public Task> QueryAsync( { Steps.Add("query:" + sql.Split(' ')[0]); Statements.Add(sql); - return Task.FromResult>((IReadOnlyList)(object)new List { true }); + return Task.FromResult>( + (IReadOnlyList)(object)Enumerable.Repeat(true, LockedRows).ToList()); } public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index 08eff639..f32f7a44 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -750,6 +750,13 @@ public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_ { var off = await toggle.ToggleAsync( TestPlatformAdmissions.Admission(ticket: "INC-9", correlationId: correlation), key, false); + await using (var midway = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString)) + { + (await ScalarAsync(midway, null, + "SELECT coalesce(reason, 'null') FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().Be("null", "the ticket stays out of a table the application role can read"); + } + var back = await toggle.ToggleAsync( TestPlatformAdmissions.Admission(correlationId: correlation), key, true); @@ -786,7 +793,7 @@ public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_ (await ScalarAsync(read, null, "SELECT toggled_at FROM platform_killswitches WHERE key = @k", ("k", key.Value))) .Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(30)); (await ScalarAsync(read, null, "SELECT coalesce(reason, 'null') FROM platform_killswitches WHERE key = @k", ("k", key.Value))) - .Should().Be("null", "the second flip carried no ticket, so the reason column is empty again"); + .Should().Be("null"); } finally { @@ -954,6 +961,9 @@ public async Task A_Failed_Statement_Leaves_The_Scope_Only_To_Be_Abandoned_And_T [InlineData("DO $$ BEGIN END $$")] [InlineData("-- comment\nSELECT 1")] [InlineData(" ")] + [InlineData("SELECT count(*) FROM audit_log")] + [InlineData("DELETE FROM audit_log")] + [InlineData("UPDATE public.\"Audit_Log\" SET reason = 'x'")] public async Task The_Facade_Refuses_Anything_But_One_Dml_Statement_And_Stays_Usable(string sql) { await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); @@ -980,6 +990,54 @@ public async Task The_Facade_Accepts_One_Statement_Whatever_Its_Case_Or_Spacing( rows.Should().Equal(1); } + [Fact] + public async Task The_Result_Row_Is_The_Last_Write_Of_A_Scope() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"after-{Guid.NewGuid():N}.example.com"; + await using var handle = await Build(dataSource).EnterAsync(Admission()); + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, null, null, null, null)); + + var write = async () => await InsertHostAsync(handle, host); + var read = async () => await ScalarAsync(handle, "SELECT 1"); + + await write.Should().ThrowAsync().WithMessage("*last write*"); + await read.Should().ThrowAsync("a statement after the row could change state it does not describe"); + var commit = async () => await handle.CommitAsync(); + await commit.Should().NotThrowAsync("the refused statements did not fault the scope"); + } + + [Theory] + [InlineData("{")] + [InlineData("not json")] + [InlineData("")] + public async Task A_Result_State_That_Is_Not_Json_Is_A_Programming_Error_Not_An_Audit_Outage(string state) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var bad = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, state)); + + await bad.Should().ThrowAsync("not an AuditWriteFailedException, which the endpoint would report as a 503"); + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, "{\"ok\":true}")); + var commit = async () => await handle.CommitAsync(); + await commit.Should().NotThrowAsync("a refused argument leaves the transaction intact"); + } + + [Fact] + public async Task An_Oversized_Result_State_Is_Refused_Before_It_Reaches_The_Database() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + var oversized = "{\"padding\":\"" + new string('x', 40 * 1024) + "\"}"; + + var bad = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", oversized, null)); + + await bad.Should().ThrowAsync().WithMessage("*larger than*"); + } + [Fact] public async Task The_Connection_Is_Returned_At_Commit_Not_At_Disposal() { diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index 70c8c49b..dfe2e3e7 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -175,6 +175,82 @@ public async Task A_Missing_Credential_Is_Counted_As_Missing() counted.Causes.Should().Contain("token_missing"); } + [Fact] + public async Task Keys_That_A_Failed_Refresh_Could_Not_Renew_Stop_Being_Trusted_After_Fifteen_Minutes() + { + // The stock manager keeps serving the keys it last fetched when a refresh fails. Right for a blip, + // wrong for a key the issuer has since withdrawn while an attacker holds the network down. So + // once a later fetch has failed and the last success is older than the window, operator tokens + // are refused, whatever key signed them. + var clock = new MovableClock(DateTimeOffset.UtcNow); + var toggle = new RecordingToggle(); + await using var factory = new PlatformOperatorApiFactory( + _tenant, _operator, toggle, grantSubject: Subject, + services: registrations => registrations.AddSingleton(new PlatformOperatorMetadataHealth(clock))); + using var client = factory.CreateClient(); + using var counted = Counted(); + + // 1. A good token loads the keys. + (await Send(client, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); + + // 2. A token signed with a key the cache has never seen makes the scheme ask the issuer for a + // refresh, and the issuer is down. + _operator.DiscoveryStatusCode = StatusCodes.Status503ServiceUnavailable; + try + { + var unknownKey = await Send(client, _operator.Token(Payload([]), key: _operator.NewKey())); + unknownKey.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await unknownKey.Content.ReadAsStringAsync()); + // The refresh the unknown key asked for runs in the background, after the response. + for (var attempt = 0; attempt < 100 && counted.MetadataFailures == 0; attempt++) + { + await Task.Delay(50); + } + + counted.MetadataFailures.Should().BeGreaterThan(0); + + // 3. Within the window the keys already held still serve. + clock.Advance(TimeSpan.FromMinutes(5)); + (await Send(client, Valid())).StatusCode.Should().Be(HttpStatusCode.OK, "a blip is bridged"); + + // 4. Past the window they do not, and the cause says why. + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness); + await AssertUnauthorized(await Send(client, Valid())); + counted.Causes.Should().Contain("metadata_stale"); + } + finally + { + _operator.DiscoveryStatusCode = StatusCodes.Status200OK; + } + } + + [Fact] + public async Task An_Issuer_That_Is_Down_At_Start_Is_Asked_Once_Not_Once_Per_Waiting_Request() + { + // Each caller waiting for the first configuration would otherwise fetch it in turn, holding an + // unauthenticated request for the whole transport timeout apiece. A failed fetch makes the next + // ones fail at once for a short while. + var down = await TenantAuthenticationIssuer.StartAsync(); + down.DiscoveryStatusCode = StatusCodes.Status503ServiceUnavailable; + try + { + await using var factory = new PlatformOperatorApiFactory(_tenant, down, new RecordingToggle(), grantSubject: Subject); + using var client = factory.CreateClient(); + var token = down.Token(down.Payload( + ("aud", "learnstack-platform"), ("azp", "learnstack-operator"), ("acr", "mfa"), + ("auth_time", DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 30), ("sub", Subject))); + + var responses = await Task.WhenAll(Enumerable.Range(0, 12).Select(_ => Send(client, token))); + + responses.Should().OnlyContain(response => response.StatusCode == HttpStatusCode.Unauthorized); + down.MetadataRequests.Should().BeLessThanOrEqualTo(2, + "twelve waiting requests are answered from one failed fetch, not twelve"); + } + finally + { + await down.DisposeAsync(); + } + } + [Theory] [InlineData("redirect")] [InlineData("oversized-keys")] @@ -298,12 +374,56 @@ public async Task An_Unknown_Killswitch_Key_Is_Not_Found() public async Task A_Failed_Audit_Write_Is_A_Retryable_503_Not_A_Success() { _toggle.Failure = new AuditWriteFailedException("forced"); + using var counted = Counted(); var response = await Put(Valid(), """{"enabled":false}"""); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); await AssertProblem(response, "audit_unavailable"); response.Headers.RetryAfter.Should().NotBeNull("every 503 the API answers carries Retry-After"); + counted.AuditFailures.Should().Be(1, "a refused audit write is a signal an alert can watch"); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"enabled":false,"ticket":"has space"}""")] + [InlineData("""{"enabled":"not-a-bool"}""")] + public async Task An_Operator_Without_The_Grant_Is_Refused_As_Such_Whatever_The_Body_Says(string body) + { + // Admission comes first: a malformed body or ticket never earns an ungranted operator a 400, + // so the refusal teaches them nothing about the request and is counted as a missing permission. + using var counted = Counted(); + + var response = await Put(Sign(("sub", "someone-else")), body); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _toggle.Calls.Should().BeEmpty(); + counted.Causes.Should().Contain("missing_permission"); + } + + [Fact] + public async Task A_Body_That_Is_Not_Json_Or_Not_Valid_Json_Is_Answered_As_A_Problem_Not_A_Bare_Status() + { + using var wrongType = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "text/plain"), + }; + using var malformed = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{", System.Text.Encoding.UTF8, "application/json"), + }; + + var first = await _client.SendAsync(wrongType); + var second = await _client.SendAsync(malformed); + + first.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + second.StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await first.Content.ReadAsStringAsync()).Should().Contain("\"code\""); + (await second.Content.ReadAsStringAsync()).Should().Contain("\"code\""); + _toggle.Calls.Should().BeEmpty(); } [Fact] @@ -314,6 +434,26 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum operatorDocument.Should().Contain("/api/platform/v1/killswitches/{key}"); tenantDocument.Should().NotContain("/api/platform", "the tenant contract is pinned and untouched (ADR-0101 § 4)"); + + // What a client author needs: a title, no Host-derived servers, the bearer scheme and its token + // profile, a security requirement on the operation, and every status an operator can meet. + using var document = JsonDocument.Parse(operatorDocument); + var root = document.RootElement; + root.GetProperty("info").GetProperty("title").GetString().Should().Be("LearnStack Platform Operator API"); + root.TryGetProperty("servers", out var servers).Should().BeFalse("servers would be derived from the caller's Host header"); + _ = servers; + var scheme = root.GetProperty("components").GetProperty("securitySchemes").GetProperty("PlatformOperator"); + scheme.GetProperty("scheme").GetString().Should().Be("bearer"); + scheme.GetProperty("bearerFormat").GetString().Should().Be("JWT"); + var put = root.GetProperty("paths").GetProperty("/api/platform/v1/killswitches/{key}").GetProperty("put"); + put.GetProperty("security").GetArrayLength().Should().Be(1); + put.GetProperty("requestBody").GetProperty("content").TryGetProperty("application/json", out _).Should().BeTrue(); + put.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "404", "415", "500", "503"]); + put.GetProperty("responses").GetProperty("401").GetProperty("headers").TryGetProperty("WWW-Authenticate", out _) + .Should().BeTrue(); + put.GetProperty("responses").GetProperty("503").GetProperty("headers").TryGetProperty("Retry-After", out _) + .Should().BeTrue(); } [Fact] @@ -396,13 +536,16 @@ private sealed class CauseListener : IDisposable private readonly MeterListener _listener = new(); private readonly ConcurrentBag _causes = []; private long _metadataFailures; + private long _auditFailures; public CauseListener() { _listener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName - && instrument.Name is PlatformOperatorMetrics.RefusalCounterName or PlatformOperatorMetrics.MetadataFailureCounterName) + && instrument.Name is PlatformOperatorMetrics.RefusalCounterName + or PlatformOperatorMetrics.MetadataFailureCounterName + or PlatformOperatorMetrics.AuditFailureCounterName) { listener.EnableMeasurementEvents(instrument); } @@ -414,6 +557,11 @@ public CauseListener() Interlocked.Add(ref _metadataFailures, value); } + if (instrument.Name == PlatformOperatorMetrics.AuditFailureCounterName) + { + Interlocked.Add(ref _auditFailures, value); + } + foreach (var tag in tags) { if (tag is { Key: "cause", Value: string cause }) @@ -429,6 +577,8 @@ public CauseListener() public long MetadataFailures => Interlocked.Read(ref _metadataFailures); + public long AuditFailures => Interlocked.Read(ref _auditFailures); + public void Dispose() => _listener.Dispose(); } @@ -464,6 +614,23 @@ private string Payload((string Name, object? Value)[] replacements) return JsonSerializer.Serialize(claims); } + private static async Task Send(HttpClient client, string token) + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + token } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + return await client.SendAsync(request); + } + + private sealed class MovableClock(DateTimeOffset start) : LearnStack.SharedKernel.Time.IClock + { + public DateTimeOffset UtcNow { get; private set; } = start; + + public void Advance(TimeSpan by) => UtcNow += by; + } + private async Task Put(string token, string json) { using var request = new HttpRequestMessage(HttpMethod.Put, Path) @@ -509,7 +676,8 @@ private sealed class PlatformOperatorApiFactory( TenantAuthenticationIssuer @operator, IKillswitchToggle toggle, string grantSubject = Subject, - bool configured = true) : ConstructionOnlyApiFactory + bool configured = true, + Action? services = null) : ConstructionOnlyApiFactory { protected override void ConfigureTestHost(IWebHostBuilder builder) { @@ -524,7 +692,11 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", PlatformPermissions.KillswitchWrite.Key); } - builder.ConfigureTestServices(services => services.AddScoped(_ => toggle)); + builder.ConfigureTestServices(registrations => + { + registrations.AddScoped(_ => toggle); + services?.Invoke(registrations); + }); } } } diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs index 187c1cb9..470796ef 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs @@ -115,7 +115,7 @@ internal async Task CompleteBffLogoutAsync(Uri logout) internal async Task AuthorizeAsync(string username, string password, string redirectUri, KeycloakPkce pkce = KeycloakPkce.S256, string clientId = "learnstack-web", string scope = "openid profile email", - Func>? otpCode = null) + Func>? otpCode = null, IReadOnlyDictionary? extraQuery = null) { var state = RandomValue(); var verifier = RandomValue(); @@ -129,6 +129,8 @@ internal async Task AuthorizeAsync(string username, strin ["state"] = state, ["nonce"] = nonce, }; + if (extraQuery is not null) + foreach (var (name, value) in extraQuery) query[name] = value; if (pkce != KeycloakPkce.Missing) { query["code_challenge"] = pkce == KeycloakPkce.Plain ? verifier diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs index 1bc3d390..96e39522 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs @@ -43,6 +43,10 @@ public async Task InitializeAsync() var realm = JsonNode.Parse(await File.ReadAllTextAsync(KeycloakFixture.RealmPath("learnstack-hub")))!.AsObject(); var user = realm["users"]!.AsArray()[0]!.AsObject(); user["requiredActions"] = new JsonArray(); + // An operator created in the realm's console receives the realm's default roles, which carry the + // account console's `manage-account`. The shipped demo user omits them, so the fixture adds them + // to make the account-console cases below represent a normal operator account. + user["realmRoles"]!.AsArray().Add("default-roles-learnstack-hub"); user["credentials"]!.AsArray().Add(new JsonObject { ["type"] = "otp", @@ -116,6 +120,65 @@ public async Task A_Token_From_The_Portal_Client_Does_Not_Meet_The_Operator_Prof .Should().BeFalse("a portal token carries neither the operator client nor the platform audience"); } + [Fact] + public async Task A_Password_Only_Session_Cannot_Remove_The_Second_Factor_Through_The_Account_Console() + { + // The realm's browser flow asks for the second factor only when a level of two is requested, and + // the account console asks for none, so a password alone opens a console session. If that session + // could delete the authenticator, anyone holding the password could remove it and then enrol their + // own at the next operator login. Pinned Keycloak refuses the removal; this keeps it that way. + using var browser = _keycloak.Browser("learnstack-hub"); + var redirect = new Uri(_keycloak.BaseAddress, "realms/learnstack-hub/account/").AbsoluteUri; + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, redirect, + clientId: "account-console", scope: "openid", otpCode: null); + authorization.Authorized.Should().BeTrue( + "premise: the console accepts a password alone, so the removal below is what is being judged"); + + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + using var client = KeycloakHttp.Create(_keycloak.BaseAddress, _keycloak.RootCertificate); + client.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", exchange.AccessToken); + client.DefaultRequestHeaders.Accept.ParseAdd("application/json"); + using var listing = await client.GetAsync("realms/learnstack-hub/account/credentials"); + listing.StatusCode.Should().Be(System.Net.HttpStatusCode.OK, "premise: the session can manage credentials at all"); + var otpIds = JsonNode.Parse(await listing.Content.ReadAsStringAsync())!.AsArray() + .SelectMany(group => group!["userCredentialMetadatas"]!.AsArray()) + .Select(metadata => metadata!["credential"]!) + .Where(credential => credential["type"]!.GetValue() == "otp") + .Select(credential => credential["id"]!.GetValue()) + .ToList(); + otpIds.Should().NotBeEmpty("premise: the fixture user has an authenticator to try to remove"); + + foreach (var id in otpIds) + { + using var removal = await client.DeleteAsync("realms/learnstack-hub/account/credentials/" + id); + removal.StatusCode.Should().NotBe(System.Net.HttpStatusCode.NoContent, + "a password-only console session must not remove the authenticator"); + } + } + + [Fact] + public async Task A_Password_Only_Login_Is_Asked_For_The_Existing_Factor_Before_A_New_Authenticator_Is_Offered() + { + // The other way round the second factor: an account-console login that asks, in the same request, + // to set up an authenticator. For an operator who already has one, pinned Keycloak asks for the + // existing code first. If the password alone reached the set-up form, whoever holds the password + // could enrol a device of their own and obtain `mfa`. + using var browser = _keycloak.Browser("learnstack-hub"); + var redirect = new Uri(_keycloak.BaseAddress, "realms/learnstack-hub/account/").AbsoluteUri; + + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, redirect, + clientId: "account-console", scope: "openid", otpCode: null, + extraQuery: new Dictionary { ["kc_action"] = "CONFIGURE_TOTP" }); + + authorization.Error.Should().NotBe("mfa_action_required", "the set-up form is not reachable with the password alone"); + authorization.Authorized.Should().BeFalse(); + authorization.MfaChallenged.Should().BeTrue("the existing authenticator is asked for first"); + } + private async Task OperatorTokenAsync() { using var browser = _keycloak.Browser("learnstack-hub"); diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs index 904d165e..4c7d2784 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using Xunit; @@ -56,6 +57,7 @@ public void A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Pinned_Is [InlineData("iat-out-of-range", "IssuedAt")] [InlineData("auth-time-missing", "AuthenticationTime")] [InlineData("auth-time-out-of-range", "AuthenticationTime")] + [InlineData("exp-missing", "Lifetime")] [InlineData("lifetime-too-long", "Lifetime")] [InlineData("lifetime-not-positive", "Lifetime")] [InlineData("auth-time-future", "AuthenticationAge")] @@ -80,6 +82,7 @@ public void Each_Profile_Defect_Is_Refused_With_Its_Own_Closed_Cause(string defe case "iat-out-of-range": claims["iat"] = long.MaxValue; break; case "auth-time-missing": claims.Remove("auth_time"); break; case "auth-time-out-of-range": claims["auth_time"] = long.MinValue; break; + case "exp-missing": claims.Remove("exp"); break; case "lifetime-too-long": claims["exp"] = iat + 16 * 60; break; case "lifetime-not-positive": claims["exp"] = iat; break; case "auth-time-future": claims["auth_time"] = Now.ToUnixTimeSeconds() + 600; break; @@ -190,6 +193,66 @@ public void Operator_Metadata_Is_Honoured_Only_On_The_Operator_Surface_Behind_Th .Should().Be(HttpOperationClassification.Refused); } + [Fact] + public async Task A_Challenge_For_A_Caller_Who_Hung_Up_Is_Not_Counted_As_An_Issuer_Fault() + { + // The abort raises a cancellation that the failure mapping would read as a metadata fault, and a + // burst of aborted calls would then look like an outage on a dashboard. + var causes = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new System.Diagnostics.Metrics.MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.RefusalCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + causes.Add(cause); + } + } + }); + listener.Start(); + + using var aborted = new CancellationTokenSource(); + await aborted.CancelAsync(); + var http = new DefaultHttpContext + { + RequestAborted = aborted.Token, + RequestServices = new ServiceCollection().AddOptions().AddLogging().BuildServiceProvider(), + }; + http.Response.Body = new MemoryStream(); + var events = new PlatformOperatorEvents( + Settings(), new FixedClock(Now), new PlatformOperatorMetadataHealth(new FixedClock(Now)), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + var challenge = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerChallengeContext( + http, + new Microsoft.AspNetCore.Authentication.AuthenticationScheme( + PlatformOperatorAuthentication.Scheme, null, typeof(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler)), + new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions(), + new Microsoft.AspNetCore.Authentication.AuthenticationProperties()) + { + AuthenticateFailure = new TaskCanceledException(), + }; + + // Writing the 401 to a caller who has gone is itself cancelled; the counting precedes it. + await FluentActions.Awaiting(() => events.Challenge(challenge)).Should().ThrowAsync(); + + causes.Should().Contain("request_aborted"); + causes.Should().NotContain("metadata_unavailable"); + } + + private sealed class FixedClock(DateTimeOffset instant) : LearnStack.SharedKernel.Time.IClock + { + public DateTimeOffset UtcNow => instant; + } + private static HttpOperationClassification Classify( OperationHttpClassifier classifier, string pattern, params object[] metadata) => classifier.Classify( diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs new file mode 100644 index 00000000..49ded95f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs @@ -0,0 +1,103 @@ +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Time; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Authentication; + +/// +/// The memory the operator scheme keeps of its issuer metadata: when to refuse a fetch without +/// trying, and when to stop trusting keys a failed refresh could not renew (ADR-0101 § 2). +/// +public sealed class PlatformOperatorMetadataHealthTests +{ + private static readonly DateTimeOffset Start = new(2026, 11, 19, 9, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_Healthy_History_Is_Neither_In_Backoff_Nor_Stale() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromHours(3)); + + health.InBackoff().Should().BeFalse(); + health.IsStale().Should().BeFalse("no refresh has failed, so the keys held are the issuer's latest known"); + } + + [Fact] + public void A_Failure_Backs_Off_For_Thirty_Seconds_Then_Allows_A_Retry() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromMinutes(1)); + health.RecordFailure(); + + health.InBackoff().Should().BeTrue(); + clock.Advance(PlatformOperatorMetadataHealth.RetryBackoff - TimeSpan.FromSeconds(1)); + health.InBackoff().Should().BeTrue(); + clock.Advance(TimeSpan.FromSeconds(2)); + health.InBackoff().Should().BeFalse("the next request may try the issuer again"); + } + + [Fact] + public void Keys_Become_Stale_Only_When_A_Later_Fetch_Failed_And_The_Last_Success_Is_Old() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness + TimeSpan.FromMinutes(1)); + health.IsStale().Should().BeFalse("old but never failed since"); + + health.RecordFailure(); + + health.IsStale().Should().BeTrue(); + } + + [Fact] + public void A_Failure_Within_The_Staleness_Window_Does_Not_Refuse_Tokens() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromMinutes(5)); + health.RecordFailure(); + + health.IsStale().Should().BeFalse("a blip is bridged by the keys already held"); + } + + [Fact] + public void A_Later_Success_Clears_Both() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness + TimeSpan.FromMinutes(1)); + health.RecordFailure(); + clock.Advance(TimeSpan.FromSeconds(31)); + + health.RecordSuccess(); + + health.IsStale().Should().BeFalse(); + health.InBackoff().Should().BeFalse(); + } + + [Fact] + public void A_Scheme_That_Never_Loaded_Keys_Is_Not_Called_Stale() + { + var (health, _) = Build(); + health.RecordFailure(); + + health.IsStale().Should().BeFalse("with no keys held every token already fails, and for the right reason"); + health.InBackoff().Should().BeTrue(); + } + + private static (PlatformOperatorMetadataHealth Health, MovableClock Clock) Build() + { + var clock = new MovableClock(Start); + return (new PlatformOperatorMetadataHealth(clock), clock); + } + + private sealed class MovableClock(DateTimeOffset start) : IClock + { + public DateTimeOffset UtcNow { get; private set; } = start; + + public void Advance(TimeSpan by) => UtcNow += by; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs new file mode 100644 index 00000000..5cebaea1 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs @@ -0,0 +1,32 @@ +using FluentAssertions; +using LearnStack.Api.Composition; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Composition; + +/// What the platform credential may and may not turn on (ADR-0101 § 8). +public sealed class PlatformCredentialConnectionStringTests +{ + private const string Valid = "Host=localhost;Database=learnstack;Username=learnstack_platform;Password=synthetic-secret-canary"; // leakwatch:ignore + + [Fact] + public void The_Ordinary_Credential_Is_Accepted() + { + var act = () => PersistenceCompositionExtensions.ValidatePlatformConnectionString(Valid); + + act.Should().NotThrow(); + } + + [Theory] + [InlineData("No Reset On Close=true")] + [InlineData("Multiplexing=true")] + public void A_Setting_That_Lets_Session_State_Outlive_A_Scope_Is_Refused(string setting) + { + // Session state set in one platform scope would reach the next on a connection that bypasses row + // level security. The sibling privileged sources pin these off; this one refuses a string that + // turns them on. + var act = () => PersistenceCompositionExtensions.ValidatePlatformConnectionString(Valid + ";" + setting); + + act.Should().Throw().WithMessage("*No Reset On Close*"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 1926a333..e1924019 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -72,15 +72,52 @@ public async Task A_Grant_For_Another_Permission_Does_Not_Admit() [InlineData("has space")] [InlineData("semi;colon")] [InlineData("this-ticket-is-far-too-long-to-be-a-ticket-reference-it-exceeds-sixty-four")] - public async Task A_Malformed_Ticket_Is_Refused_Before_The_Grant_Is_Read(string ticket) + public async Task A_Malformed_Ticket_Is_Refused_For_An_Operator_Who_Holds_The_Grant_And_Only_For_Them(string ticket) { - var grants = Grants("operator-1", PlatformPermissions.KillswitchWrite.Key); - var gate = Gate(grants); + // The grant is read first: an operator without it is refused as such whatever the request + // carries, so a malformed ticket tells them nothing and is counted under the cause an alert on + // ungranted operators watches. + var granted = Grants("operator-1", PlatformPermissions.KillswitchWrite.Key); + (await Gate(granted).AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket)) + .Refusal.Should().Be(PlatformRefusal.InvalidTicket); + granted.Reads.Should().Be(1); + + var ungranted = Grants("someone-else", PlatformPermissions.KillswitchWrite.Key); + (await Gate(ungranted).AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission); + } + + [Fact] + public async Task Each_Refusal_Is_Counted_Under_A_Snake_Case_Cause() + { + var causes = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new System.Diagnostics.Metrics.MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name == PlatformOperatorMetrics.RefusalCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + causes.Add(cause); + } + } + }); + listener.Start(); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); - var result = await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket); + await gate.AdmitAsync(TestPlatformAdmissions.Witness("someone-else"), PlatformOperations.KillswitchToggle, null); + await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, "has space"); + await gate.AdmitAsync(null!, PlatformOperations.KillswitchToggle, null); - result.Refusal.Should().Be(PlatformRefusal.InvalidTicket); - grants.Reads.Should().Be(0, "the ticket grammar is checked before any grant is evaluated"); + causes.Should().Contain(["missing_permission", "invalid_ticket", "invalid_witness"]); } [Fact] @@ -162,6 +199,19 @@ public async Task A_Stale_Admission_Never_Reaches_The_Credential_And_Is_Not_Spen stale.TryConsume().Should().BeTrue("a refused-as-stale admission was never spent"); } + [Fact] + public async Task A_Future_Dated_Admission_Is_Refused_Like_A_Stale_One() + { + var scope = Build(out var dataSource); + var future = TestPlatformAdmissions.Admission( + issuedAt: DateTimeOffset.UtcNow + PlatformAdmission.MaximumAge + TimeSpan.FromHours(1)); + + var act = async () => await scope.EnterAsync(future, CancellationToken.None); + + await act.Should().ThrowAsync().WithMessage("*stale*"); + dataSource.IsValueCreated.Should().BeFalse(); + } + [Fact] public async Task An_Admission_Opens_One_Scope_Only() { diff --git a/docs/architecture/21-feature-flags.md b/docs/architecture/21-feature-flags.md index 1798dbe7..af3683c3 100644 --- a/docs/architecture/21-feature-flags.md +++ b/docs/architecture/21-feature-flags.md @@ -419,11 +419,12 @@ CREATE TABLE platform_killswitches ( **Packet 9 shipped the table and the read path, and no writer** ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). The reason was reachability rather than scheduling: every killswitch write runs inside -`EnterPlatformAdminScope`, and no Platform gate existed. **P03-9 Step 1 ships the writer** -as a service entered with an operator admission for `platform.killswitch.write`, with a -MUST result row on the same transaction and the overlay cache entry dropped after the -commit ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Other -instances see the flip within the overlay's 60-second TTL; the +`EnterPlatformAdminScope`, and no Platform gate existed. **P03-9 Step 1 ships the +writer** as a service entered with an operator admission for +`platform.killswitch.write`, with a MUST result row on the same transaction and the +overlay cache entry dropped after the commit +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Other instances see +the flip within the overlay's 60-second TTL; the [killswitch runbook](../runbooks/killswitch.md) says so, and that the read fails open. A flippable killswitch pairs with a runbook entry describing when to use it and how to diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index d162a52f..7bbf680f 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -1397,16 +1397,17 @@ guards are specified only in the Database standard: | Ordinary unresolved context, not provisioning/global identity | no row — there is no admitted attribution owner | — | **The third row has exactly one user in Packet 9**: entry into -`EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its own -row through the fourth write path. `tenancy.killswitch.toggle` — the operation +`EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its +own row through the fourth write path. `tenancy.killswitch.toggle` — the operation [ADR-0044 § 1](../decisions/0044-audit-write-path.md) names as the first to be performed -*inside* that scope — shipped no writer in Packet 9; P03-9 Step 1 ships it as a service entered with an -operator admission ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), +*inside* that scope — shipped no writer in Packet 9; P03-9 Step 1 ships it as a service +entered with an operator admission +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), [ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)). [The Tenancy matrix](../modules/tenancy/audit.md) classifies it MUST and marks it `(off-path)`: the scope is entered by a service method rather than by a MediatR request, -so there is no request type to key a catalogue entry on (§ 13). It carried `(planned)` as -well until its writer shipped; a cell carries every marker that applies. +so there is no request type to key a catalogue entry on (§ 13). It carried `(planned)` +as well until its writer shipped; a cell carries every marker that applies. The organization column is decided from the same source as the tenant and at the same moment, which is what keeps the two paths agreeing. On the in-transaction path the diff --git a/docs/decisions/0045-entitlement-and-feature-flag-socket.md b/docs/decisions/0045-entitlement-and-feature-flag-socket.md index 2bfeab9e..e60e925a 100644 --- a/docs/decisions/0045-entitlement-and-feature-flag-socket.md +++ b/docs/decisions/0045-entitlement-and-feature-flag-socket.md @@ -628,15 +628,24 @@ which records the mapping; and `EntitlementProjection`'s remarks in Accepted [ADR-0101](0101-platform-operator-authority.md) § 13 lifts the withholding of Amendment 1 § 4 once the writer ships. It is a service entered through the Platform gate, not a MediatR request. `toggled_by` stays NULL because an operator is not a -`users` row, the bounded ticket goes in the `reason` column, the MUST result row commits -on the work transaction, and the overlay cache entry is removed after the commit, -including an indeterminate one. Section 5's statement that the scope gives the row a -real actor is read as the `metadata.operator` attribution; the shipped scope writes a -null actor. +`users` row, the bounded ticket goes in the `reason` column (see Amendment 6), the MUST +result row commits on the work transaction, and the overlay cache entry is removed after +the commit, including an indeterminate one. Section 5's statement that the scope gives +the row a real actor is read as the `metadata.operator` attribution; the shipped scope +writes a null actor. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. +## Amendment 6 — The ticket is not stored in `platform_killswitches` (2026-11-19) + +Amendment 5 repeated [ADR-0101](0101-platform-operator-authority.md) § 13, which put the +bounded ticket in the `reason` column. +[ADR-0101 Amendment 1](0101-platform-operator-authority.md) corrects that: the +application role reads this table, and a ticket never appears in a row a tenant's +connection can reach. The writer leaves `reason` NULL and the ticket is on the sentinel +audit rows. Section 5's table definition is unchanged. + ## References - [ADR-0021 Feature-Based Entitlement Model](0021-feature-based-entitlement.md) diff --git a/docs/decisions/0101-platform-operator-authority.md b/docs/decisions/0101-platform-operator-authority.md index fb44de8a..3650049d 100644 --- a/docs/decisions/0101-platform-operator-authority.md +++ b/docs/decisions/0101-platform-operator-authority.md @@ -198,6 +198,12 @@ permission. `platform_killswitches` are confined to it by an architecture rule; the overlay's reads are unaffected. The runbook states the 60-second cross-instance lag, the fail-open read, and that no production code reads a killswitch yet. + + > **Erratum (2026-11-19, Amendment 1 below).** The text above puts the ticket in + > the `reason` column. That table is readable by the application role, which § 9 + > forbids for a ticket, so the two sections disagreed when this record was accepted. + > § 9 governs: the writer leaves `reason` NULL and the ticket is on the sentinel + > audit rows only. 14. **Signals.** Counters record admissions by outcome and operation, refusals by cause, and result rows by operation, so a monitoring owner can alert without a log search. @@ -279,6 +285,19 @@ ADR-0100 (a Platform key does not recur the refusal). Standards 04, 11, 12, 13, 20 and 21, Architecture 13, 28 and 30, the glossary, the Tenancy and Identity module specifications, and the Phase 03 and Phase 11 documents follow. +## Amendments + +### Amendment 1 — The ticket stays out of a table the application role reads (2026-11-19) + +Step 1 review found that § 13 stored the optional ticket in +`platform_killswitches.reason` while § 9 promises that a row a tenant can read never +carries it. The application role holds `SELECT` on that table under `USING (true)`, so +the overlay can read it; a ticket there would be reachable by any future module query, +including one an injection steered. The writer sets `reason` to NULL on every flip and +the ticket is recorded on the sentinel-tenant audit rows, where § 9 puts it. The column +stays for a future non-ticket explanation; nothing writes it. The Decision, Status, Date +and every other section are unchanged. + ## References - [ADR-0102](0102-production-tenant-onboarding.md), diff --git a/docs/glossary.md b/docs/glossary.md index f53f2ee3..8c215253 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -194,7 +194,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **`TenantContextFactory`** | The single entry point that constructs the sealed `TenantContext`: it returns `Result.Fail` on any disagreement between the signals and never a partially populated context. `TenantContext` has no public constructor; `TenantContext_Is_Constructed_Only_By_The_Factory` enforces both halves. Per [ADR-0036 § The reconciliation matrix](decisions/0036-tenant-resolution-trusted-inputs.md). | | **`IOrganizationScopeValidator`** | The reader that answers "does this organization belong to this tenant", resolving `organizations` by the composite key `(tenant_id, id)` in its own short read-only transaction that sets `app.tenant_id` as its first statement — one of the sanctioned out-of-band setters of that GUC ([Security Standards § The out-of-band setters](standards/11-security.md), per [ADR-0040 Amendment 3](decisions/0040-ambient-unit-of-work.md)). A valid organization id from another tenant is a mismatch, not an override. | | **`DenyAllTenantMembershipReader`** | The Packet 7 `ITenantMembershipReader` that denies every membership question, so the reconciliation matrix's rows 7, 10 and 14 fail closed until [Phase 03](roadmap/phase-03-identity-admin.md) ships `Membership`. It makes the Studio tenant switcher 404 for everyone in that window; that is correct and it will look like a bug. Per [ADR-0036](decisions/0036-tenant-resolution-trusted-inputs.md). | -| **`EnterPlatformAdminScope`** | The explicit, scoped entry to cross-tenant access: a connection and transaction opened on a second, separately-credentialed data source that connects as `learnstack_platform` — never `SET ROLE`, which would make the four-role separation a naming convention rather than a boundary. Not one of the `ITenantContextAccessor` writers, and not an out-of-band setter of `app.tenant_id` — a `BYPASSRLS` role has no policy to announce to. **Logged in Packet 7, audited in Packet 9:** Packet 7 records entry through `ILogger` at `Warning`; Packet 9 adds the durable `security-event` row, written through `IAuditStore.WritePlatformScopeAsync` — a fourth *write* method with exactly one caller, and no relaxation of "no update method" — on the scope's own platform-role connection, in a transaction of its own that commits **before** the operation's begins, so an operation that later fails — or is abandoned — is still recorded. That row carries `TenantId.PlatformSentinel` ([ADR-0044 §§ 1, 10](decisions/0044-audit-write-path.md)). The C# member is `IPlatformAdminScope.EnterAsync`; `EnterPlatformAdminScope(reason)` is how the corpus names the path. See [Database Standards § How `EnterPlatformAdminScope(reason)` reaches `learnstack_platform`](standards/05-database.md). | +| **`EnterPlatformAdminScope`** | The explicit, scoped entry to cross-tenant access: a connection and transaction opened on a second, separately-credentialed data source that connects as `learnstack_platform` — never `SET ROLE`, which would make the four-role separation a naming convention rather than a boundary. Not one of the `ITenantContextAccessor` writers, and not an out-of-band setter of `app.tenant_id` — a `BYPASSRLS` role has no policy to announce to. **Logged in Packet 7, audited in Packet 9:** Packet 7 records entry through `ILogger` at `Warning`; Packet 9 adds the durable `security-event` row, written through `IAuditStore.WritePlatformScopeAsync` — a fourth *write* method with exactly one caller, and no relaxation of "no update method" — on the scope's own platform-role connection, in a transaction of its own that commits **before** the operation's begins, so an operation that later fails — or is abandoned — is still recorded. That row carries `TenantId.PlatformSentinel` ([ADR-0044 §§ 1, 10](decisions/0044-audit-write-path.md)). The C# member is `IPlatformAdminScope.EnterAsync`; `EnterPlatformAdminScope(reason)` is how the corpus names the path. See [Database Standards § How `EnterPlatformAdminScope(reason)` reaches `learnstack_platform`](standards/05-database.md). Entry takes a `PlatformAdmission` minted by the operator gate; there is no caller-supplied reason ([ADR-0101 § 7](decisions/0101-platform-operator-authority.md)). | ## Extension Model diff --git a/docs/modules/tenancy/README.md b/docs/modules/tenancy/README.md index ab515fa4..5be3dcdc 100644 --- a/docs/modules/tenancy/README.md +++ b/docs/modules/tenancy/README.md @@ -47,9 +47,9 @@ Tenancy owns **who a request belongs to** and nothing about what they do with it - `platform_killswitches` — one platform-wide switch per key. Platform-scoped and tenant-blind: the only table in the schema for which "no tenant context implies zero rows" is deliberately false, because a switch the application role cannot read is one - that fails open. Shipped read-only in Packet 9 — every toggle runs inside - `EnterPlatformAdminScope`, so [Phase 03](../../roadmap/phase-03-identity-admin.md) - owns the writer. + that fails open. Packet 9 shipped it read-only; its one writer is `KillswitchToggle` + (P03-9 Step 1, [ADR-0101 § 13](../../decisions/0101-platform-operator-authority.md), + [runbook](../../runbooks/killswitch.md)). **Two read paths it owns, over tables it does not read directly:** diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index 401d578f..ffb1834d 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -110,8 +110,8 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi [Database Standards § GRANT matrix](../../standards/05-database.md) records that the widening it needs is an ADR's to make, not a migration's. -The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) is -separate and never assignable to a Role. Tenancy owns one key in it today, +The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) +is separate and never assignable to a Role. Tenancy owns one key in it today, `platform.killswitch.write`, which authorizes the operator surface to toggle `platform_killswitches`; operators hold it by configuration ([Standard 19](../../standards/19-permissions.md)). diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 843fb63c..6aaba743 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,11 +509,12 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 479 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 595 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 107 lines + - [P03-9 Step 1 — review round 2 and its fixes (2026-11-19)](#p03-9-step-1--review-round-2-and-its-fixes-2026-11-19) — 116 lines @@ -24650,3 +24651,119 @@ The last row is the result the Step 1 record deferred to this entry. It is also that found the withdrawn start-time credential check: a compiled census of connection-string readers failed on the new reader, which is why the check is recorded above and not shipped. + +### P03-9 Step 1 — review round 2 and its fixes (2026-11-19) + +Three further independent reviewers read the range from the accepted decisions to the +round 1 fixes: an adversarial security review, a review of correctness and test +validity, and a review of the operator experience and the documentation. None reported a +Blocker. Each finding was checked against the code, and for the security question that +could not be settled by reading, against the pinned Keycloak. + +#### Settled by running it: the second factor and the account console + +The security reviewer asked whether a password-only session on the operator realm could +remove or add an authenticator through the account console, which asks for no `acr`. +Both paths were run against Keycloak 26.7.5 with a normally-roled operator who has an +authenticator: the console accepts the password alone, a credential listing succeeds, +and removing the authenticator is refused ("Credential type cannot be removed"); a login +that asks for `kc_action=CONFIGURE_TOTP` is sent to the existing-code form, not to +set-up. Both are now realm tests, so a Keycloak upgrade that changed either fails them. +The window that remains is the first login before any authenticator exists, which the +runbook already closes by ordering enrolment before the grant. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Authentication | After one successful load, an issuer that stops answering left the last keys trusted indefinitely, so the claim "an outage refuses every operator" was false, and a withdrawn key stayed valid while egress was blocked | The scheme records when a fetch last succeeded and failed. Once a later fetch has failed and the last success is older than 15 minutes, tokens are refused (`metadata_stale`). The comment and runbook now say what an outage does | +| Authentication | While the first configuration was unavailable, every waiting unauthenticated request fetched it in turn, each holding its request for the transport timeout | A failed fetch makes the next ones fail at once for 30 seconds | +| Authentication | A caller who hung up during validation was counted as an issuer fault; a token with no `exp` was labelled as a bad `iat` | An `aborted` caller gets its own label; a missing `exp` is a lifetime cause | +| Gate | The ticket grammar was judged before the grant, so an ungranted operator's probe was filed as `InvalidTicket`, and the endpoint comment said the opposite | The grant is read first. An ungranted operator is refused as such whatever the request carries, and the refusal causes are snake case like the others | +| Endpoint | The framework bound the body before the handler ran, so a malformed body or a wrong content type was answered to an operator with no grant; outside Development it was a bare status | The handler reads the body after the gate has been asked, answers 415 and 400 as Problem Details, and caps the body at 4 KB. The response's correlation id is no longer optional in the contract | +| Killswitch writer | The ticket was stored in `platform_killswitches.reason`, a table the application role can read, against ADR-0101 § 9 | `reason` is NULL on every flip; the ticket is on the sentinel audit rows. [ADR-0101](../decisions/0101-platform-operator-authority.md) § 13 carries an erratum and Amendment 1; ADR-0045 Amendment 6 follows | +| Killswitch writer | The time was taken before the row lock; a toggle that waited stamped an earlier time than the one it followed. The lock result and the update count were trusted | The time is taken under the lock. A lock that finds no row, or an update that changes none, abandons the toggle before any result row exists | +| Scope | The facade accepted statements after the result row and any text naming `audit_log` (the platform role holds audit maintenance rights); a caller's state JSON reached the database unchecked and would have been reported as an audit outage; the entry's failure path could strand the connection if disposing the transaction threw; a size cap on the entry metadata could have dropped the operator and made the store refuse the row for good | The result row is the last write. No statement may name the audit log. State is checked as JSON and capped at 32 KB, and a refused argument does not fault the scope. The connection is disposed in a `finally`. The cap is removed | +| Credential | A connection string with `No Reset On Close` or `Multiplexing` would let session state outlive a scope on the pool that bypasses row level security | The platform credential is refused when either is on, as the sibling privileged sources pin them off | +| Contract | The operator document had a default title, Host-derived servers, no security scheme and no request body or error statuses beyond the generator's | A document transformer sets the title, drops `servers`, declares the bearer scheme and its token profile, a requirement on every operation, the request body, and 400, 401, 403, 404, 415, 500 and 503 with their headers | +| Operability | The overlay's two error events were numbered 1 and 2, which other components also use, so an operator could not search for them; the runbooks omitted events 7101, 7104 and two causes, did not define `API`, asked the operator to substitute variables by hand, and named a database administrator where the platform role is required | The events are 7107 and 7108 and the runbooks name every event, cause and role; the commands are runnable as written; the record-reading section names the role | +| Docs | Seven documents still described a writer-less table or the removed `EnterAsync(reason, …)` signature | Corrected: the Tenancy README, Standards 05 and 20, the glossary, the Phase 03 decision register, the Keycloak and compose READMEs | + +New cases: the future-dated admission, the grant-before-ticket order in the gate +(granted and ungranted operator, three malformed tickets) and over HTTP (three bodies, +including one the framework would have refused first), the audit-failure counter, the +415 and the malformed JSON as Problem Details, the operator document's title, servers, +scheme, body and statuses, stale keys after a failed refresh with a clock the test moves +(a blip within the window is bridged), twelve waiting requests answered from one failed +fetch, the aborted caller, the metadata health rules (six cases), the platform +credential's pool settings, the result row as the last write, three statements that name +the audit log, three non-JSON states and one oversized one with the scope still +committable afterwards, a lock that finds no row and an update that changes none, the +unreadable ticket column at the midpoint of a real toggle, and the two account-console +cases above. + +#### Recorded, not changed + +- **Pool settings in the builder.** `BuildPlatformDataSource` is inspected by a compiled + census of credential builders, so the platform source refuses a string that turns + session state on rather than rewriting it as its siblings do. Rewriting is a change to + that census and to every sibling at once, which belongs with Phase 11's credential + hardening. +- **The Development relaxations.** The loopback issuer and the demo grant depend on + `Deployment:Mode` alone, which the shipped development settings set. A host started in + the Development environment in production would honour both. This is the gate every + Development relaxation uses + ([ADR-0020](../decisions/0020-triple-deployment-hybrid-license.md)), a production + environment never loads that file, and the operator realm is not exposed by the + shipped compose; a second environment check would make this the one relaxation that + differs. +- **The internal Hub scheme.** When `/api/internal` gets a bearer scheme on the same + issuer, it must pin its own client and audience and refuse `learnstack-platform`, and + this scheme's `azp` list must never name a service client. Owned by the Hub contract + packet that adds it. +- **`IAuditStore.WritePlatformOperatorResultAsync` is a default interface method** that + throws, so a fake inherits a runtime failure and not a compile error. Making it + abstract touches ten test fakes for one production implementation; the architecture + census of store implementations is the guard, and a second production store would be a + decision of its own. +- **`TryConsume` and the minters are public.** A holder of an admission can spend it, + which only harms the holder. Narrowing them needs `InternalsVisibleTo` across three + assemblies for no gain the censuses do not already give. +- **Dead and decorative code.** `PlatformOperatorEvents.Forbidden` is unreachable under + the current policy and stays as the documented 403 mapping for the per-permission + policies the next operations add. The validation attributes on the request record + shape the contract and are not enforced by the framework; the gate and the handler + enforce the real rules. +- **Splitting `PlatformOperatorAuthentication.cs`.** It holds nine types, and an + architecture rule pins it as the authentication boundary. The split belongs with Step + 3, which adds the second caller of the profile and must edit that rule anyway. + +#### Mutation checks + +Twelve mutations of the round 2 guards, each applied, built, run and restored with the +restored file touched. All were killed: statements allowed after the result row, +statements that name the audit log, a result state that is not validated, an update row +count and a lock row count left unchecked, stale keys still trusted, no backoff after a +failed fetch, an aborted caller counted as an issuer fault, the ticket judged before the +grant, the ticket stored in the killswitch row, the unsafe pool settings accepted, and +the Host-derived `servers` left in the operator document. + +#### Proof run locally + +| Suite | Result | +|---|---| +| Unit | 4,242 passed | +| Contract | 13 passed | +| Integration, the whole suite (Release, 1 h 24 m) | 4,450 passed, 1 failed (below) | +| Integration, the account-console credential cases against pinned Keycloak 26.7.5 | 2 passed | +| Architecture (Release): platform scope, audit and API conventions | 31 passed | +| Architecture (Release, 46 min): `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests` | 178 passed | + +The one failure in the full integration run is +`AuthenticatedHttpSurfaceRuntimeTests.Production_endpoint_union_has_exact_patterns_methods_handlers_and_requests` +for the Development environment. Its message pattern names the asserted collection +(`authorizations`), which FluentAssertions reads back from the call-site source; the run +reported the generic wording instead, so the mutation control inside the case did not +match. The case passed alone, the whole class passed twice more, and the same case +passed in the earlier full run on the same code, so it is recorded as an inference flake +in an unrelated control and not as a defect of this change. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 82585b08..48265e7c 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -503,17 +503,18 @@ and provider token refresh alone cannot establish application permission freshne [Security Standards § Tenant Context](../standards/11-security.md). `Tenant_Scope_Widening_Is_Never_Set_From_Request_Input` becomes non-vacuous here. -- **The Platform-scope permission, and the writer it unlocks.** `EnterPlatformAdminScope` - is gated by `IPlatformAdminGate`, registered since - [Phase 02a Packet 9](phase-02a-kernel-tenancy.md) as `DenyAllPlatformAdminGate`, which - refuses everyone — so every operation that needs the scope is unreachable, every - killswitch toggle included. This phase replaces it with a gate that reads a - Platform-scope permission, and ships with it the killswitch writer, its - permission key and its incident runbook: the writer Packet 9 withheld on purpose +- **The Platform-scope permission, and the writer it unlocks.** The platform scope was + gated by a gate registered since [Phase 02a Packet 9](phase-02a-kernel-tenancy.md) + that refused everyone, so every operation that needs the scope, every killswitch + toggle included, was unreachable. This phase replaces it with the operator authority + of [ADR-0101](../decisions/0101-platform-operator-authority.md): an admission minted + for an authenticated operator who holds a Platform grant, and with it the killswitch + writer, its permission key and its incident runbook: the writer Packet 9 withheld on + purpose ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - [Permissions](../standards/19-permissions.md) reserves no killswitch or entitlement key - yet, so reserving them is part of the work. The toggle's row is already classified — - `tenancy.killswitch.toggle`, `(off-path)` `(planned)`, MUST, in the + [Permissions](../standards/19-permissions.md) registers `platform.killswitch.write`; + an entitlement key joins with the operation that uses it. The toggle's row is + classified — `tenancy.killswitch.toggle`, `(off-path)`, MUST, in the [Tenancy matrix](../modules/tenancy/audit.md). - **Audited job quarantine inspection and reconciliation.** ADR-0047 assigns this diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index 9a042b87..6150ffbe 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -1,9 +1,9 @@ # Runbooks Operational procedures, one per failure or privileged act. Each names the signal, the -diagnostic access, the safe recovery and what is not recoverable -([Documentation Standards](../standards/13-documentation.md)). Phase 03 begins this -directory with the platform operator runbooks; +diagnostic access, the safe recovery and what is not recoverable. They live under +`runbooks/` per [Documentation Standards](../standards/13-documentation.md). Phase 03 +begins this directory with the platform operator runbooks; [Phase 11](../roadmap/phase-11-production-hardening.md) completes the set. | Runbook | Use it when | diff --git a/docs/runbooks/killswitch.md b/docs/runbooks/killswitch.md index 392e8f46..7d4d9451 100644 --- a/docs/runbooks/killswitch.md +++ b/docs/runbooks/killswitch.md @@ -39,14 +39,16 @@ it reads it. Two audit rows are written under the platform sentinel, which no tenant can read: the entry into the platform scope, and the result row `tenancy.killswitch.toggle` with the -before and after state and the operator's digest. The ticket is on those rows and in the -`reason` column of the switch's own row (empty again after a flip without one). Find the -rows by the correlation id. +before and after state and the operator's digest. The ticket is on those rows. Find the +rows by the correlation id. The switch's own row keeps no ticket, because the +application role can read that table. ## Reading the record -The sentinel rows are visible only to the platform credential, so a database -administrator reads them. By the correlation id the answer returned: +The sentinel rows are visible only to the `learnstack_platform` role (the table owner is +filtered too, because row level security is forced), so a database administrator +connects with the `ConnectionStrings:PlatformAdmin` credential to read them. By the +correlation id the answer returned: ```sql SELECT timestamp, operation, reason, @@ -60,7 +62,8 @@ ORDER BY timestamp; ``` The operator is recorded as a digest, never as the raw `sub`. To find every row one -operator wrote, compute their digest from the issuer and the `sub` and filter on +operator wrote, compute their digest from the issuer and the `sub` (`ISSUER` must equal +`PlatformOperator:Issuer` byte for byte, a trailing slash included) and filter on `metadata->'operator'->>'subjectDigest'`: ```sh @@ -71,19 +74,22 @@ printf 'learnstack.operator.subject.v1\n%s\n%s' "$ISSUER" "$SUB" \ The current state of a switch is its own row, if it has one: ```sql -SELECT key, is_enabled, reason, toggled_at +SELECT key, is_enabled, toggled_at FROM platform_killswitches WHERE key = ''; ``` ## When it takes effect Immediately on the instance that handled the request, which drops its cached copy after -the commit. Every other instance refreshes within 60 seconds. Plan for that minute. +the commit. Every other instance refreshes within 60 seconds. Plan for that minute. If +the instance could not drop its copy it logs a Warning with event 7104, and then it too +serves the old state for up to 60 seconds. **The read fails open.** If the overlay cannot read the table or the cache, it answers the key's default, which is enabled. A switch flipped off during a database or cache incident can therefore read as on again once its cached copy expires. Watch the log for -the overlay's read-failure error, and repeat the flip if it appears. +event 7107 (Error, "The killswitch overlay could not be read"), and repeat the flip if +it appears. Event 7108 means a caller asked for a key that is not declared. ## Switching it back @@ -94,9 +100,14 @@ Confirm by the response (`after` is `true`) and by the result row. | Answer | What happened | What to do | |---|---|---| +| 400, 401, 403 | The body, the ticket, the token or the grant | See [operator access](operator-access.md#reading-a-refusal) | +| 404 | The key is not one of the three in the table, or no operator issuer is configured | Check the spelling and the issuer setting | | 503 | The audit row could not be written, so the table was not changed | Repeat the request after `Retry-After` | -| 500 | Something failed unexpectedly. If it was the final commit, its outcome is unknown and the flip may have landed; the instance still dropped its cached copy | Read the switch's row (above) before repeating | -| 404 | The key is not one of the three in the table | Check the spelling | +| 500 | Something failed unexpectedly: the platform credential is missing, or the final commit's outcome is unknown and the flip may have landed. The instance still dropped its cached copy | Read the switch's row (above) before repeating | + +An admission with neither a matching `results_total` increment nor an +`audit_failures_total` increment is an act whose outcome is unknown; read the row for it +too. ## Not recoverable here diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 20ed48f6..ba99e926 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -64,6 +64,9 @@ printf %s "$TOKEN" | cut -d. -f2 | tr '_-' '/+' \ ## Getting a token +You need `curl`, `openssl` and `jq`. In the local stack the API answers at +`http://localhost:5080`; set `API` to the address of the deployment you are calling. + The shipped realm provides the public client `learnstack-operator` (authorization code with PKCE, redirect `http://127.0.0.1:8765/*`). In the compose stack the issuer is `http://localhost:8080/realms/learnstack-hub`; the demo operator is @@ -80,19 +83,19 @@ with any TOTP tool). | openssl base64 -A | tr '+/' '-_' | tr -d '=') ``` -2. Open this address in a browser. `prompt=login` makes the issuer ask again even when a - browser session exists; without it a stale `auth_time` is refused later: +2. Open the address in a browser (`xdg-open` on Linux). `prompt=login` makes the issuer + ask again even when a browser session exists; without it a stale `auth_time` is + refused later. Sign in with the password and the one-time code: - ```text - $ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator&response_type=code - &scope=openid&redirect_uri=http://127.0.0.1:8765/callback&prompt=login&state=x - &code_challenge=$challenge&code_challenge_method=S256 + ```sh + URL="$ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator" + URL="$URL&response_type=code&scope=openid&prompt=login&state=x" + URL="$URL&redirect_uri=http://127.0.0.1:8765/callback" + URL="$URL&code_challenge=$challenge&code_challenge_method=S256" + open "$URL" ``` - - (one line; substitute the variables first), and sign in with the password and the - one-time code. 3. The browser lands on the callback address and shows a connection error. Copy `code` - from its address bar into `CODE`. + from its address bar and set `CODE` to it. 4. Redeem it. The access token lasts at most 15 minutes: ```sh @@ -106,10 +109,12 @@ with any TOTP tool). Send `Authorization: Bearer $TOKEN` and `Content-Type: application/json`. Every write may carry an optional `ticket` of 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`. The -response carries a `correlationId`; record it against your own ticket, because the audit -rows a tenant can read never hold the ticket. +response carries a `correlationId`, the request's W3C trace identifier, which is also +the trace id in the logs; record it against your own ticket, because the audit rows a +tenant can read never hold the ticket. ```sh +API=http://localhost:5080 curl -sS -X PUT "$API/api/platform/v1/killswitches/killswitch.notifications.email" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d '{"enabled": false, "ticket": "INC-123"}' @@ -146,7 +151,7 @@ production realm. | Answer | Meaning | What to do | |---|---|---| -| 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | +| 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached: at start, or for more than 15 minutes after its keys were last fetched | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | | 403 | The token is good and this operator holds no grant for the act | Ask for the grant | | 400 | The ticket or the body is malformed | Fix the request | | 404 | Unknown killswitch key, or the surface is not configured | Check the key and the issuer setting | @@ -161,16 +166,19 @@ the response. | Signal | Meaning | |---|---| -| `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate | -| `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `InvalidTicket`, `MissingPermission`, `UnknownOperation`, `InvalidWitness` | +| `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate; `operation` is the audit slug, for example `tenancy.killswitch.toggle` | +| `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `request_aborted`, `metadata_stale`, `metadata_unavailable`, `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_algorithm`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `invalid_ticket`, `missing_permission`, `unknown_operation`, `invalid_witness` | | `learnstack_platform_operator_results_total{operation}` | MUST result rows committed | | `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | -| `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs every operator is refused | - -A Warning log accompanies each: event 7102 for a refused act, 7103 for a refused -credential (with the cause), 7106 for a metadata failure; event 7105 is the Error log of -a refused audit write; and for every admitted platform act the Warning log of the -platform scope (event 7001). A refused operator leaves no database row. +| `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs, new keys are not learned; a fetch that failed is not retried for 30 seconds, and once the keys held are more than 15 minutes old with a later fetch failed, every operator is refused (`metadata_stale`) | + +A log line accompanies each. Search by event id: 7102 (Warning) a refused act, 7103 +(Warning) a refused credential with its cause, 7106 (Warning) a metadata failure, 7105 +(Error) a refused audit write, and 7101 (Error) a grant configuration that failed +validation on reload; while 7101 appears every operator act is refused until the +configuration is valid. Every admitted platform act logs a Warning with event 7001 and +the text "Platform-admin scope entered" (other hosts reuse the number for unrelated +lines, so match the text too). A refused operator leaves no database row. ## Not recoverable here diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 4aa2d439..8658ef28 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -958,8 +958,8 @@ Platform gate existed. P03-9 Step 1 ships the writer, a service entered with an admission for `platform.killswitch.write` ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), [ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)); an -architecture rule confines the table's write verbs to it. The `learnstack_platform` write -grant in the matrix below is that writer's. +architecture rule confines the table's write verbs to it. The `learnstack_platform` +write grant in the matrix below is that writer's. The overlay is read through the L1 cache and invalidated on toggle, so the table itself is touched on a cache miss rather than on every request @@ -1204,11 +1204,14 @@ composition root registers a keyed `PrivilegedDataSource` facade from `LearnStack.Infrastructure.MultiTenancy.PlatformAdminScope`. The facade owns the separately credentialed lazy Npgsql pool without exposing it. Every synchronous or asynchronous acquisition checks the independent ordinary-job ceiling before pool -creation or reuse, under [ADR-0047](../decisions/0047-transactional-background-job-runtime.md). -`IPlatformAdminScope.EnterAsync(reason, …)` opens a **connection and a transaction** on -that guarded source and returns an `IAsyncDisposable` handle carrying both; -disposing without committing rolls back. Module code cannot resolve the data source; -`Platform_DataSource_Resolved_Only_By_PlatformAdminScope` enforces that. +creation or reuse, under +[ADR-0047](../decisions/0047-transactional-background-job-runtime.md). +`IPlatformAdminScope.EnterAsync(admission, …)` takes the `PlatformAdmission` the +operator gate minted (there is no caller-supplied reason), opens a **connection and a +transaction** on that guarded source and returns an `IAsyncDisposable` facade over both, +which exposes neither; disposing without committing rolls back. Module code cannot +resolve the data source; `Platform_DataSource_Resolved_Only_By_PlatformAdminScope` +enforces that. An earlier wording here — and in the glossary — said the scope opens "a DI scope whose `DbContext` is built on that data source". A connection is what shipped, for a reason diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 618766e6..4905053b 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -97,9 +97,9 @@ nonempty foundation registry. | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | The registered Platform catalogue is `PlatformPermissions` in `LearnStack.SharedKernel`, -apart from the tenant registry and never assignable, so the served tenant document does not -change when it grows ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 5). A -key is registered with the operation that has a denied proof for it: +apart from the tenant registry and never assignable, so the served tenant document does +not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authority.md) § +5). A key is registered with the operation that has a denied proof for it: | Key | Operation | Packet | |---|---|---| diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index 44e617ae..a36b757c 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -259,9 +259,9 @@ adapter trigger. admits the two families by **enumeration**, so the overlay's own four-segment per-key spelling is refused rather than merely unused: one entry holds the whole switch set, because `ICacheService` has no `RemoveByPrefixAsync` for a toggle to - sweep a per-key family with. The toggle that invalidates it arrives with the - Platform-scope permission in [Phase 03](../roadmap/phase-03-identity-admin.md) - ([ADR-0045 Amendment 1](../decisions/0045-entitlement-and-feature-flag-socket.md)). + sweep a per-key family with. The toggle that invalidates it is + `KillswitchToggle`, which drops the entry after its commit + ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Every `ICacheService` implementation calls `CacheKey.EnsureValid`, and none re-prefixes. There is no query filter and no RLS policy in front of a dictionary, so the key is the entire isolation boundary — which is why the shape is validated rather diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 58c9d931..0310bb69 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -180,21 +180,20 @@ not implemented is the failure mode this column exists to prevent. **379 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), -[Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, Packet 7, -Packet 8, Packet 9, Packet 10, P02d-1, P02d-2, P02d-3, P02d-4 Steps 1–3, P02b-1, -P02b-2 Steps 2–4, P02b-3 Steps 3–6 and P02b-4 Steps 1–8, with further -source-boundary, observation and production-manifest companions in Step 9. -Its nineteen packet obligations are implemented with actual canonical owners and -complementary structural, native-runtime and PostgreSQL controls. The +[Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, +Packet 7, Packet 8, Packet 9, Packet 10, P02d-1, P02d-2, P02d-3, P02d-4 Steps 1–3, +P02b-1, P02b-2 Steps 2–4, P02b-3 Steps 3–6 and P02b-4 Steps 1–8, with further +source-boundary, observation and production-manifest companions in Step 9. Its nineteen +packet obligations are implemented with actual canonical owners and complementary +structural, native-runtime and PostgreSQL controls. The [P02b-4 merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) -owns its final review/CI qualification. Authentication, realm and BFF obligations -have unit/integration/frontend/offline owners in their entries below; the -[Phase 02b Status block](../roadmap/phase-02b-events-auth.md) links current delivery -and qualification. The analyzer and asynchronous inventory controls also have -actual owners; registration alone promotes none of these obligations. -Methods are not rows: -a `[Theory]` is one row and many cases, -and most rows pair a rule with the companion assertion that stops it passing vacuously. +owns its final review/CI qualification. Authentication, realm and BFF obligations have +unit/integration/frontend/offline owners in their entries below; the +[Phase 02b Status block](../roadmap/phase-02b-events-auth.md) links current delivery and +qualification. The analyzer and asynchronous inventory controls also have actual owners; +registration alone promotes none of these obligations. Methods are not rows: a +`[Theory]` is one row and many cases, and most rows pair a rule with the companion +assertion that stops it passing vacuously. **Every number in this section is recomputed by `The_Catalogue_Counts_Its_Own_Rules`.** They are a second copy of what the repository already knows, and the first version of this section @@ -5886,20 +5885,21 @@ structural test proves — and what it does not. permissive default ships. - **Source:** ADR-0036 § The platform-admin override is not a resolution source; [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and § 8. -- **Type:** xUnit — reflection over every production assembly, and behavioural cases without - Docker (`PlatformAdminGateTests`) and over HTTP with controlled signed tokens +- **Type:** xUnit — reflection over every production assembly, and behavioural cases + without Docker (`PlatformAdminGateTests`) and over HTTP with controlled signed tokens (`PlatformOperatorHttpTests`). **Kind:** structural + behavioural. -- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7; rewritten - against the real gate by P03-9 Step 1). +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7; + rewritten against the real gate by P03-9 Step 1). - **Phase:** 02a (Packet 7); P03-9. -- **Note:** the rule was live in its mechanism and vacuous in its subject while the registered - gate refused everyone. It now has a subject: a Platform permission exists (`PlatformPermissions`), - an operator can hold it through a grant, and a permitted entry is exercised. The ordering — - admission before the credential is touched — is behavioural and asserted in - `PlatformAdminGateTests`; a structural rule cannot see it. The marker clause, that no - handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry, is now - structural as well: `Only_The_Operator_Services_Hold_The_Platform_Scope` lists every file - that may hold the scope, and no request handler is among them. +- **Note:** the rule was live in its mechanism and vacuous in its subject while the + registered gate refused everyone. It now has a subject: a Platform permission exists + (`PlatformPermissions`), an operator can hold it through a grant, and a permitted + entry is exercised. The ordering — admission before the credential is touched — is + behavioural and asserted in `PlatformAdminGateTests`; a structural rule cannot see it. + The marker clause, that no handler carries both `[AllowsUnresolvedTenantContext]` and + a platform-scope entry, is now structural as well: + `Only_The_Operator_Services_Hold_The_Platform_Scope` lists every file that may hold + the scope, and no request handler is among them. #### `The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only` @@ -5921,8 +5921,8 @@ structural test proves — and what it does not. `IPlatformAdminScope` are exactly the interface, the scope, the persistence composition and the operator services that perform an admitted act (today the killswitch toggle). Adding a service is a deliberate edit here, with its denied proof. -- **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a - tenant request path. +- **Why it matters:** a request handler holding the scope would enter a cross-tenant + scope from a tenant request path. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index 0850e6b1..3d76c301 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -188,13 +188,15 @@ manual ledger deletion, history reset, reduced retention or tenant-copy purge. | `learnstack` | Tenant users; four declared development accounts | `learnstack-web`: confidential code/S256 BFF; `learnstack-api`: resource and legacy service account; `learnstack-event-reader`: confined history reader; `learnstack-federation-admin`: confined federation adapter ([below](#federation-administration-client)); `account` and `account-console`: retired, disabled | | `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE, the portal's; `learnstack-operator`: public PKCE for LearnStack's platform surface, audience `learnstack-platform`, 15-minute access tokens, MFA step-up | -The `learnstack-hub` realm's browser flow is `browser-loa`: password at level 1, a one-time -password at level 2, so a login through `learnstack-operator` (which asks for `acr` `mfa`) always -ends in an `acr` that LearnStack accepts only for an operator who passed the second factor -([ADR-0101](../../docs/decisions/0101-platform-operator-authority.md) § 3). The demo operator -has a pinned subject and sets up an authenticator at its first login; production MFA enforcement -for the realm stays [Phase 11](../../docs/roadmap/phase-11-production-hardening.md). A realm import -into production never includes the demo user. +The `learnstack-hub` realm's browser flow is `browser-loa`: password at level 1, a +one-time password at level 2, so a login through `learnstack-operator` (which asks for +`acr` `mfa`) always ends in an `acr` that LearnStack accepts only for an operator who +passed the second factor +([ADR-0101](../../docs/decisions/0101-platform-operator-authority.md) § 3). The demo +operator has a pinned subject and sets up an authenticator at its first login; +production MFA enforcement for the realm stays +[Phase 11](../../docs/roadmap/phase-11-production-hardening.md). A realm import into +production never includes the demo user. Three properties of the shared realm file that an operator of it should know: @@ -202,6 +204,13 @@ Three properties of the shared realm file that an operator of it should know: login (`learnstack-hub-web`) goes through it too; the portal asks for no `acr`, so it is satisfied at level 1 and sees no change. The file is shared with the Hub repository, so a change to the flow is made in both. +- **Credential changes need the existing second factor.** An account-console login needs + only the password, because the console asks for no `acr`. For an operator who already + has an authenticator, pinned Keycloak (26.7.5) then refuses to remove it, and asks for + the existing code before it offers to set up another; two realm tests pin both. The + window that remains is the first login, before any authenticator exists, which is why + a grant follows enrolment (see the + [operator access runbook](../../docs/runbooks/operator-access.md#giving-and-withdrawing-a-grant)). - **Password reset is off.** `resetPasswordAllowed` is `false`: the reset-credentials flow lets a user set a new password from an email link, which would be a second way to a password that does not pass through the second factor. Operator credentials are From 5555d72fb0204ebb98d091a921584de8cc92825d Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 18:10:20 +0300 Subject: [PATCH 07/28] feat(platform): add operator onboarding acts (ADR-0102 step 2) Five operator acts (provision a tenant, map its host, initialize a role template, create the first administrator, recover an administrator) run on the application role through the ordinary pipeline under a resolved ambient context the act executor installs for the admitted target tenant. A fourth trusted-operation source mints the PlatformOperator descriptor; the handlers share their cores with the seed handlers and restate source, context and transaction in OperatorActGuard. A confined definer resolves the named provider subject to an Active user. The seeder refuses outside Development. The real-database proofs show the last-administrator guard makes "no active administrator" unreachable by revocation, so recovery is a break-glass for repaired states; ADR-0102 Amendment 1 records it. Step 1 leftovers found by the fast architecture classes are fixed: the transport-holder census, the Docker-trait placement of the killswitch ordering test, the realm-file helper, a route-built killswitch key and the catalogue counts. ADR: 0102, 0101 Module: Tenancy, Identity Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 26 +- .../PlatformOperatorCompositionExtensions.cs | 16 + .../PlatformOperatorEndpoints.Onboarding.cs | 219 +++++++ .../Platform/PlatformOperatorEndpoints.cs | 19 +- .../Audit/AuthorizationEvidenceCoordinator.cs | 4 +- .../Pipeline/MediatRPipelineRegistration.cs | 4 + .../MultiTenancy/PlatformAdminScope.cs | 21 +- .../PlatformOperator/OperatorTenantContext.cs | 30 + .../PlatformOperatorActCatalog.cs | 45 ++ .../PlatformOperatorActExecutor.cs | 87 +++ .../PlatformOperatorOperationSource.cs | 113 ++++ .../Audit/AuditDraftComposer.cs | 8 +- .../Audit/AuthorizationAuditContext.cs | 8 +- .../Entitlements/KillswitchKeys.cs | 21 + .../Permissions/AuthorizationCandidate.cs | 2 +- .../Permissions/OperationPolicy.cs | 3 +- .../Permissions/OperatorActGuard.cs | 133 +++++ .../Permissions/TrustedOperationDescriptor.cs | 21 +- .../Platform/PlatformOperation.cs | 23 +- .../Platform/PlatformOperatorAttribution.cs | 75 +++ .../Platform/PlatformPermissions.cs | 10 +- .../src/LearnStack.Tools.Seeder/Program.cs | 11 + .../OperatorActs/OperatorIdentityCommands.cs | 45 ++ .../Abstractions/ContextualIdentityStores.cs | 6 + .../Abstractions/IOperatorSubjectResolver.cs | 18 + .../Audit/IdentityAuditCatalogSource.cs | 4 + .../IdentityOperationPolicySource.cs | 4 + .../OperatorActs/OperatorIdentityHandlers.cs | 229 +++++++ .../CreateSeedMembershipCommandHandlers.cs | 2 +- .../IdentityFoundationRegistration.cs | 1 + .../Persistence/ContextualIdentityStores.cs | 19 + ...119140000_add_operator_subject_resolver.cs | 14 + .../Persistence/OperatorSubjectResolver.cs | 43 ++ .../Persistence/OperatorSubjectResolverDdl.cs | 43 ++ .../Tenant/OperatorTenantCommands.cs | 36 ++ .../Audit/TenancyAuditCatalogSource.cs | 10 + .../TenancyOperationPolicySource.cs | 2 + .../Tenant/MapHostToTenantCommandHandler.cs | 86 ++- .../Tenant/OperatorTenantCommandValidators.cs | 43 ++ .../Tenant/ProvisionTenantCommandHandler.cs | 79 ++- .../FederationAdapterConventionTests.cs | 4 + ...itConventionTests.AuthorizationEvidence.cs | 3 + .../IdentityFoundationConventionTests.cs | 2 + .../PlatformAdminScopeConventionTests.cs | 2 +- .../PublicSurfaceTests.cs | 10 +- .../TenantContextConstructionTests.cs | 12 +- .../TrustedOperationSourceConventionTests.cs | 24 +- ...nistrationHttpTests.InvitationEntrySeal.cs | 1 + .../GlobalIdentitySchemaTests.Controls.cs | 4 +- .../Database/GlobalIdentitySchemaTests.cs | 4 +- .../Database/InvitationSmtpStorageTests.cs | 6 +- .../Database/MigrationRollbackTests.cs | 4 +- .../Database/OperatorSubjectResolverTests.cs | 170 ++++++ .../PlatformOperatorOnboardingTests.cs | 560 ++++++++++++++++++ .../KillswitchToggleOrderingTests.cs | 4 +- .../PlatformOperatorHttpTests.cs | 53 +- .../SeedOperationSourceTests.cs | 29 + .../SeederDevelopmentOnlyTests.cs | 86 +++ .../TenancyIdentity/KeycloakFixture.cs | 11 +- .../PlatformOperatorRealmFileTests.cs | 2 +- .../TenancyIdentity/RealmFiles.cs | 22 + .../OperationPolicyCatalogTests.cs | 46 +- .../Authorization/OperatorActGuardTests.cs | 335 +++++++++++ .../MultiTenancy/PlatformAdminGateTests.cs | 7 +- .../PlatformOperatorActExecutorTests.cs | 269 +++++++++ .../Tenancy/SeedTenantWriteGuardTests.cs | 6 + docs/decisions/0033-audit-durability-model.md | 17 + .../0036-tenant-resolution-trusted-inputs.md | 24 + docs/decisions/0040-ambient-unit-of-work.md | 30 + .../0102-production-tenant-onboarding.md | 79 +++ docs/glossary.md | 1 + docs/modules/identity/audit.md | 4 +- docs/modules/identity/permissions.md | 3 + docs/modules/tenancy/audit.md | 7 + docs/modules/tenancy/permissions.md | 13 +- docs/runbooks/README.md | 1 + docs/runbooks/operator-access.md | 2 +- docs/standards/05-database.md | 64 +- docs/standards/11-security.md | 10 +- docs/standards/18-audit-coverage.md | 31 +- docs/standards/19-permissions.md | 11 +- .../21-architecture-tests-catalogue.md | 42 +- 82 files changed, 3441 insertions(+), 157 deletions(-) create mode 100644 backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs create mode 100644 backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs create mode 100644 backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs create mode 100644 backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs rename backend/tests/LearnStack.Tests.Integration/{Database => }/KillswitchToggleOrderingTests.cs (98%) create mode 100644 backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 1e2e945b..4b85d9a6 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -66,7 +66,7 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum // Declared here and not through `Accepts` on the endpoint: that metadata makes routing // reject any other content type itself, before the handler can answer 415 as a problem. var schema = await context.GetOrCreateSchemaAsync( - typeof(Platform.KillswitchToggleRequest), null, cancellationToken); + BodyFor(operation.OperationId), null, cancellationToken); operation.RequestBody = new OpenApiRequestBody { Required = true, @@ -77,11 +77,28 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum } } + /// The request body each operation reads, by the name its endpoint declares. + private static Type BodyFor(string? operationId) => operationId switch + { + "PlatformKillswitchToggle" => typeof(Platform.KillswitchToggleRequest), + "PlatformTenantProvision" => typeof(Platform.TenantProvisionRequest), + "PlatformHostMap" => typeof(Platform.HostMapRequest), + "PlatformRoleInitialize" => typeof(Platform.RoleInitializeRequest), + "PlatformFirstAdminCreate" or "PlatformAdminRecover" => typeof(Platform.AdministratorRequest), + _ => throw new InvalidOperationException("An operator operation declares no request body: " + operationId), + }; + private static void DescribeResponses(OpenApiDocument document, OpenApiOperation operation) { operation.Responses ??= []; foreach (var (status, description) in Statuses) { + // 409 belongs to the acts that can meet a state they refuse; a switch toggle never answers it. + if (status == "409" && !operation.Responses.ContainsKey("409")) + { + continue; + } + operation.Responses[status] = new OpenApiResponse { Description = description, @@ -127,9 +144,10 @@ private static readonly (string Status, string Description)[] Statuses = ("400", "validation_failed: the body is malformed, the required state is missing, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), - ("404", "not_found: the key is not a declared killswitch."), + ("404", "not_found: the key is not a declared killswitch, or the tenant the route names does not exist."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (identifier taken, a person already bound, an administrator already exists, the tenant has history). The same request is safe to repeat once the state is as the reason says."), ("415", "unsupported_media_type: the body is not application/json."), - ("500", "internal_error: an unexpected failure. A toggle whose final commit's outcome is unknown may have landed; read the switch before repeating."), - ("503", "audit_unavailable: the audit row could not be written, so nothing changed."), + ("500", "internal_error: an unexpected failure. An act whose final commit's outcome is unknown may have landed; repeat the same request (every act is idempotent on its identifiers) or read the state before changing it."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or a dependency could not answer, so nothing changed. Retry after the delay."), ]; } diff --git a/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs index ad7b46f4..ec639575 100644 --- a/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs @@ -1,6 +1,8 @@ using LearnStack.Api.Authentication; using LearnStack.Api.Versioning; using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Hosting; using LearnStack.SharedKernel.Platform; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -28,6 +30,17 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthority( services.TryAddSingleton(); services.TryAddSingleton(); + // The five onboarding acts the operator may run through the ordinary pipeline on the application + // role (ADR-0102 § 2): the closed list the executor and the operator source both judge by. + services.AddPlatformOperatorActs(new PlatformOperatorActCatalog( + [ + Act(PlatformOperations.TenantProvision), + Act(PlatformOperations.HostMap), + Act(PlatformOperations.RoleInitialize), + Act(PlatformOperations.FirstAdminCreate), + Act(PlatformOperations.AdminRecover), + ])); + var settings = PlatformOperatorSettings.FromConfiguration(configuration, deploymentMode); if (settings is not null) { @@ -37,4 +50,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthority( return services; } + + private static KeyValuePair Act(PlatformOperation operation) => + new(typeof(TRequest), new PlatformOperatorAct(operation)); } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs new file mode 100644 index 00000000..cde90e96 --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs @@ -0,0 +1,219 @@ +using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using MediatR; +using LearnStack.Api.Common; + +namespace LearnStack.Api.Platform; + +/// The default organization of a tenant being provisioned. +internal sealed record DefaultOrganizationBody(Guid Id, string? Slug, string? DisplayName); + +/// The body of a tenant provisioning. +internal sealed record TenantProvisionRequest( + string? Slug, string? DisplayName, DefaultOrganizationBody? DefaultOrganization, string? Ticket); + +/// The body of a host mapping. +internal sealed record HostMapRequest(Guid? OrganizationId, bool? IsActive, bool? IsPubliclyLive, string? Ticket); + +/// The body of a role template initialization. +internal sealed record RoleInitializeRequest(string? BuiltInKey, string? CapabilityScope, string? Ticket); + +/// The body of a first-administrator or recovery act. +internal sealed record AdministratorRequest(Guid RoleId, string? ProviderSubject, string? Ticket); + +/// What an operator act answers: its result and the correlation id the operator records. +internal sealed record OperatorActResponse(T Result, string CorrelationId); + +/// +/// The onboarding routes of the operator surface (ADR-0102): provision a tenant, map its host, +/// initialize a role template, create the first administrator, recover an administrator. +/// +/// +/// Five idempotent PUTs on operator-supplied identifiers, so a reply lost on the wire is +/// repaired by sending the same request again. Each runs the gate first, then the act through the +/// ordinary pipeline on the tenant the route names (). +/// +internal static partial class PlatformOperatorEndpoints +{ + private static void MapOnboarding(RouteGroupBuilder group) + { + Describe( + group.MapPut("/tenants/{tenantId:guid}", ProvisionTenantAsync) + .WithName("PlatformTenantProvision") + .WithSummary("Provision a tenant and its default organization (idempotent on the id and slug)."), + typeof(OperatorActResponse)); + Describe( + group.MapPut("/tenants/{tenantId:guid}/host-mappings/{host}", MapHostAsync) + .WithName("PlatformHostMap") + .WithSummary("Map a host to a tenant; the operator asserts ownership of the host."), + typeof(OperatorActResponse)); + Describe( + group.MapPut("/tenants/{tenantId:guid}/roles/{roleId:guid}", InitializeRoleAsync) + .WithName("PlatformRoleInitialize") + .WithSummary("Initialize a built-in role template before any membership exists."), + typeof(OperatorActResponse)); + Describe( + group.MapPut("/tenants/{tenantId:guid}/first-administrator/{membershipId:guid}", CreateFirstAdminAsync) + .WithName("PlatformFirstAdminCreate") + .WithSummary("Create the first administrator of a tenant that has never had a member."), + typeof(OperatorActResponse)); + Describe( + group.MapPut("/tenants/{tenantId:guid}/administrator-recovery/{membershipId:guid}", RecoverAdminAsync) + .WithName("PlatformAdminRecover") + .WithSummary("Create a replacement administrator for a tenant with none active."), + typeof(OperatorActResponse)); + } + + private static void Describe(RouteHandlerBuilder route, Type success) => route + .Produces(StatusCodes.Status200OK, success, "application/json") + .ProducesProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status403Forbidden) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status409Conflict) + .ProducesProblem(StatusCodes.Status415UnsupportedMediaType) + .ProducesProblem(StatusCodes.Status500InternalServerError) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable); + + private static Task ProvisionTenantAsync( + Guid tenantId, HttpContext http, IPlatformOperatorGate gate, PlatformOperatorActExecutor executor, + ILoggerFactory loggers, CancellationToken cancellationToken) => + RunAsync( + http, tenantId, PlatformOperations.TenantProvision, gate, executor, loggers, + body => body.Ticket, + body => body.Slug is { } slug && body.DisplayName is { } name + && body.DefaultOrganization is { Slug: { } orgSlug, DisplayName: { } orgName } organization + && IsRoot(organization.Id) + ? new OperatorProvisionTenantCommand( + TenantId.From(tenantId), slug, name, OrganizationId.From(organization.Id), orgSlug, orgName) + : null, + cancellationToken); + + private static Task MapHostAsync( + Guid tenantId, string host, HttpContext http, IPlatformOperatorGate gate, PlatformOperatorActExecutor executor, + ILoggerFactory loggers, CancellationToken cancellationToken) => + RunAsync( + http, tenantId, PlatformOperations.HostMap, gate, executor, loggers, + body => body.Ticket, + body => new OperatorMapHostCommand( + host, body.OrganizationId is { } organization ? OrganizationId.From(organization) : null, + body.IsActive ?? true, body.IsPubliclyLive ?? true), + cancellationToken); + + private static Task InitializeRoleAsync( + Guid tenantId, Guid roleId, HttpContext http, IPlatformOperatorGate gate, PlatformOperatorActExecutor executor, + ILoggerFactory loggers, CancellationToken cancellationToken) => + RunAsync( + http, tenantId, PlatformOperations.RoleInitialize, gate, executor, loggers, + body => body.Ticket, + body => Enum.TryParse(body.BuiltInKey, ignoreCase: true, out var key) && Enum.IsDefined(key) + && Enum.TryParse(body.CapabilityScope, ignoreCase: true, out var scope) + && scope is PermissionScope.Tenant or PermissionScope.Organization + && IsRoot(roleId) + ? new OperatorInitializeRoleCommand(roleId, key, scope) + : null, + cancellationToken); + + private static Task CreateFirstAdminAsync( + Guid tenantId, Guid membershipId, HttpContext http, IPlatformOperatorGate gate, PlatformOperatorActExecutor executor, + ILoggerFactory loggers, CancellationToken cancellationToken) => + RunAsync( + http, tenantId, PlatformOperations.FirstAdminCreate, gate, executor, loggers, + body => body.Ticket, + body => body.ProviderSubject is { } subject && IsRoot(membershipId) && IsRoot(body.RoleId) + ? new OperatorCreateFirstAdminCommand(membershipId, body.RoleId, subject) : null, + cancellationToken); + + private static Task RecoverAdminAsync( + Guid tenantId, Guid membershipId, HttpContext http, IPlatformOperatorGate gate, PlatformOperatorActExecutor executor, + ILoggerFactory loggers, CancellationToken cancellationToken) => + RunAsync( + http, tenantId, PlatformOperations.AdminRecover, gate, executor, loggers, + body => body.Ticket, + body => body.ProviderSubject is { } subject && IsRoot(membershipId) && IsRoot(body.RoleId) + ? new OperatorRecoverAdminCommand(membershipId, body.RoleId, subject) : null, + cancellationToken); + + /// + /// The shared flow of an onboarding act: the credential, the body read after admission, the gate, + /// the act, and the answer. + /// + private static async Task RunAsync( + HttpContext http, + Guid tenantRoute, + PlatformOperation operation, + IPlatformOperatorGate gate, + PlatformOperatorActExecutor executor, + ILoggerFactory loggers, + Func ticketOf, + Func>?> build, + CancellationToken cancellationToken) + where TBody : class + { + var witness = http.Features.Get()?.Witness; + if (witness is null) + { + return Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"); + } + + // Admission first, as the killswitch route does: the body is read before the gate is asked + // (the gate needs its ticket) but never answered until the gate has admitted the act. + var (body, bodyState) = await ReadBodyAsync(http.Request, cancellationToken); + var admission = await gate.AdmitAsync(witness, operation, body is null ? null : ticketOf(body), cancellationToken); + if (!admission.IsAdmitted) + { + return RefusalProblem(http, admission.Refusal); + } + + if (bodyState == BodyState.NotJson) + { + return Problem(http, StatusCodes.Status415UnsupportedMediaType, "lockey_unsupported_media_type"); + } + + if (body is null || !IsRoot(tenantRoute) || build(body) is not { } request) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await executor.ExecuteAsync(admission.Admission!, TenantId.From(tenantRoute), request, cancellationToken); + return result.IsSuccess + ? Results.Ok(new OperatorActResponse( + result.Value!, admission.Admission!.Operator.CorrelationId ?? http.TraceIdentifier)) + : ResultProblem(http, result.Error!); + } + catch (AuditWriteFailedException failure) + { + PlatformOperatorMetrics.AuditFailed(operation); + LogAuditRefused(loggers.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), failure); + RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); + return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); + } + } + + private static bool IsRoot(Guid id) => id != Guid.Empty && id.Version == 7; + + private static IResult RefusalProblem(HttpContext http, PlatformRefusal refusal) => refusal switch + { + PlatformRefusal.InvalidTicket => Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"), + PlatformRefusal.InvalidWitness => Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"), + _ => Problem(http, StatusCodes.Status403Forbidden, "lockey_forbidden"), + }; + + /// An act's own refusal, in the status and shape the API gives every other failed result. + private static IResult ResultProblem(HttpContext http, Error error) => + Results.Json( + ProblemDetailsFactory.For(error, http), + options: null, + contentType: ProblemDetailsMediaType.Value, + statusCode: HttpStatusMap.For(error)); +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index 4dffd693..a5d9c946 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -40,7 +40,7 @@ internal sealed record KillswitchToggleResponse(string Key, bool Before, bool Af /// counter and a log (ADR-0101 § 11). /// /// -internal static class PlatformOperatorEndpoints +internal static partial class PlatformOperatorEndpoints { internal const string Prefix = "/api/platform/v1"; @@ -67,6 +67,7 @@ internal static WebApplication MapLearnStackPlatformOperator(this WebApplication .ProducesProblem(StatusCodes.Status415UnsupportedMediaType) .ProducesProblem(StatusCodes.Status500InternalServerError) .ProducesProblem(StatusCodes.Status503ServiceUnavailable); + MapOnboarding(group); return app; } @@ -77,8 +78,9 @@ private enum BodyState { Read, Missing, NotJson, Malformed } private const int MaximumBodyBytes = 4096; - private static async Task<(KillswitchToggleRequest? Body, BodyState State)> ReadBodyAsync( + private static async Task<(TBody? Body, BodyState State)> ReadBodyAsync( HttpRequest request, CancellationToken cancellationToken) + where TBody : class { if (request.ContentLength is 0 || (request.ContentLength is null && !request.Headers.ContainsKey("Transfer-Encoding"))) { @@ -98,7 +100,7 @@ private enum BodyState { Read, Missing, NotJson, Malformed } try { - var body = await JsonSerializer.DeserializeAsync( + var body = await JsonSerializer.DeserializeAsync( request.Body, JsonSerializerOptions.Web, cancellationToken); return body is null ? (null, BodyState.Malformed) : (body, BodyState.Read); } @@ -125,7 +127,7 @@ private static async Task ToggleKillswitchAsync( // Admission first: the gate checks the grant before the ticket, so an operator without // the grant is answered 403 whatever the request carries, and a body that cannot be used is // answered 400 or 415 only to someone who may act at all. - var (body, bodyState) = await ReadBodyAsync(http.Request, cancellationToken); + var (body, bodyState) = await ReadBodyAsync(http.Request, cancellationToken); var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body?.Ticket, cancellationToken); if (!admission.IsAdmitted) { @@ -147,9 +149,16 @@ private static async Task ToggleKillswitchAsync( return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); } + // The registry resolves the name; a switch it does not declare is answered as it always was, + // without a scope entered or a row written. + if (!KillswitchKeys.TryResolve(key, out var registryKey)) + { + return Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"); + } + try { - var result = await toggle.ToggleAsync(admission.Admission!, new KillswitchKey(key), enabled, cancellationToken); + var result = await toggle.ToggleAsync(admission.Admission!, registryKey, enabled, cancellationToken); return result.Outcome == KillswitchToggleOutcome.Applied ? Results.Ok(new KillswitchToggleResponse( key, result.Before, result.After, admission.Admission!.Operator.CorrelationId ?? http.TraceIdentifier)) diff --git a/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs b/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs index ab369d6a..aa5e5f6b 100644 --- a/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs +++ b/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs @@ -167,6 +167,8 @@ public async Task RecordConfirmedAssertionAsync(ConfirmedClaimAssertion assertio private void RecordDenial(OperationInvocation invocation, ProtectedOperationDecision? decision, AuthorizationRefusalReason reason, string errorKey = "lockey_forbidden", AuthorizationAuditContext? observedContext = null) { + // An operator's refused act leaves a counter and a log line and no durable row (ADR-0101 § 11). + if (invocation.TrustedSource is { SourceKind: AuthorizationSourceKind.PlatformOperator }) return; if (_entries.ContainsKey(invocation) || !HasAttribution(invocation)) return; try { @@ -180,7 +182,7 @@ private void RecordDenial(OperationInvocation invocation, ProtectedOperationDeci private void RecordObservedDenial(OperationInvocation invocation, AuthorizationAuditContext context, AuthorizationRefusalReason reason, string errorKey) { - if (_entries.ContainsKey(invocation)) return; + if (_entries.ContainsKey(invocation) || context.SourceKind == AuthorizationSourceKind.PlatformOperator) return; capture.AttachAuthorization(context); var metadata = "{\"authorization\":" + context.ToJson() + ",\"denial_reason\":" + AuditJson.Quote(reason switch diff --git a/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs b/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs index 26808f1f..f0e04d71 100644 --- a/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs +++ b/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs @@ -68,6 +68,10 @@ public static IServiceCollection AddLearnStackMediatRPipeline( services.TryAddScoped>(provider => () => provider.GetRequiredService()); services.TryAddSingleton(); + // The handler-side check of an operator act (ADR-0102). Registered with the pipeline so every + // host that resolves a module's handlers resolves it, and inert unless the operator source minted + // the descriptor. + services.TryAddScoped(); // MediatR 12.x throws if no assemblies are registered for handler // scanning. Fall back to the LearnStack.Application assembly itself — diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index f24128ff..8fc55f44 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -379,21 +379,12 @@ private AuditEntryDraft ComposeEntry( Metadata = OperatorMetadata(admission, includeTicket: true, Provenance(callerMember, callerFile, callerLine)), }; - private static string OperatorMetadata(PlatformAdmission admission, bool includeTicket, string? provenance) - { - var op = admission.Operator; - var json = "{" - + (provenance is null ? string.Empty : "\"caller\":" + provenance + ",") - + "\"operator\":{" - + "\"issuer\":" + AuditJson.Quote(op.Issuer) - + ",\"subjectDigest\":" + AuditJson.Quote(op.SubjectDigest) - + ",\"kind\":\"human\"" - + ",\"acr\":" + AuditJson.Quote(op.Acr) - + ",\"executor\":" + AuditJson.Quote(op.Executor) - + (includeTicket && admission.Ticket is not null ? ",\"ticket\":" + AuditJson.Quote(admission.Ticket) : string.Empty) - + "}}"; - return json; - } + private static string OperatorMetadata(PlatformAdmission admission, bool includeTicket, string? provenance) => + "{" + + (provenance is null ? string.Empty : "\"caller\":" + provenance + ",") + + "\"operator\":" + + PlatformOperatorAttribution.From(admission).ToOperatorJson(includeTicket ? admission.Ticket : null) + + "}"; private static string Provenance(string? callerMember, string? callerFile, int callerLine) => "{" diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs new file mode 100644 index 00000000..b043f56d --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs @@ -0,0 +1,30 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// The immutable tenant context of one admitted operator act on an existing tenant (ADR-0102 § 1). +/// +/// +/// Resolved and ambient, as a seed, event or job context is, with no actor: the business columns of +/// an operator act carry the registry actor and the audit rows carry the operator in metadata +/// (ADR-0101 § 9), so nothing here names a user. Only +/// constructs one. +/// +internal sealed class OperatorTenantContext(TenantId tenantId, string? correlationId) : ITenantContext +{ + public bool IsResolved => true; + + public TenantContextOrigin? Origin => TenantContextOrigin.Ambient; + + public TenantId TenantId { get; } = tenantId; + + public OrganizationId? OrganizationId => null; + + public UserId? UserId => null; + + public string? CorrelationId { get; } = correlationId; + + public string? ModuleName => null; +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs new file mode 100644 index 00000000..92d4ba38 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs @@ -0,0 +1,45 @@ +using System.Collections.Frozen; +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// What the operator source needs to know about one request type it may capture. +/// The registered operation that admits the request. +public sealed record PlatformOperatorAct(PlatformOperation Operation); + +/// +/// The closed set of request types an operator act may run, each bound to its operation (ADR-0102 § 2). +/// +/// +/// Built once by the composition root from the five command types and never changed, so the source +/// and the executor judge the same list and a request outside it is never captured. +/// +public sealed class PlatformOperatorActCatalog +{ + private readonly FrozenDictionary _acts; + + /// Builds the catalog; every operation must be a registered one that needs no platform role. + public PlatformOperatorActCatalog(IEnumerable> acts) + { + ArgumentNullException.ThrowIfNull(acts); + var list = acts.ToList(); + if (list.Count == 0 + || list.Any(pair => pair.Key.IsAbstract || !PlatformOperations.IsRegistered(pair.Value.Operation) + || pair.Value.Operation.NeedsPlatformRole)) + { + throw new ArgumentException("The operator act catalog needs registered operations that use the application role."); + } + + _acts = list.ToFrozenDictionary(); + } + + /// The request types in the catalog. + public IReadOnlyCollection RequestTypes => _acts.Keys; + + /// Finds the act a request type belongs to. + public bool TryGet(Type requestType, out PlatformOperatorAct act) + { + ArgumentNullException.ThrowIfNull(requestType); + return _acts.TryGetValue(requestType, out act!); + } +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs new file mode 100644 index 00000000..3711ea36 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs @@ -0,0 +1,87 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; +using Microsoft.Extensions.DependencyInjection; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// Runs one admitted operator act through the ordinary request pipeline, on the application role, +/// against the tenant the operator named (ADR-0102 § 1). +/// +/// +/// +/// The confined tenant setter. This is the one place a tenant chosen by an operator reaches the +/// pipeline. It consumes the admission, opens a fresh scope, installs an immutable +/// in the accessor for the length of the act (or leaves the +/// context unresolved when the act creates its tenant, which then announces itself through +/// IProvisionsTenant as the seed's provisioning does), enters the one-frame operator source, +/// sends the request and restores the accessor. The target is never read from a header, a host or an +/// ambient value, and a request outside the closed catalog, or one the admission's operation does not +/// cover, is refused before any scope exists. +/// +/// +/// It is a context writer, and says so. Installing a context in the accessor is what makes the +/// EF query filters and the handlers read the target tenant; the architecture rule that enumerates +/// accessor writers lists this file beside the resolver, the two asynchronous executors and the job +/// runtime. The platform role is not used, and nothing here opens a connection. +/// +/// +public sealed class PlatformOperatorActExecutor( + IServiceScopeFactory scopeFactory, + ITenantContextAccessor accessor, + PlatformOperatorActCatalog acts, + IClock clock) +{ + /// Runs for under . + /// The admission or the request is not admissible. + public async Task ExecuteAsync( + PlatformAdmission admission, + TenantId tenantId, + IRequest request, + CancellationToken cancellationToken = default) + where TResponse : IResultBase + { + ArgumentNullException.ThrowIfNull(admission); + ArgumentNullException.ThrowIfNull(request); + if (!PlatformOperations.IsRegistered(admission.Operation) || admission.Operation.NeedsPlatformRole + || !acts.TryGet(request.GetType(), out var act) || !ReferenceEquals(act.Operation, admission.Operation) + || !StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel) + { + throw new InvalidOperationException("The operator act is not admissible."); + } + + if ((clock.UtcNow - admission.IssuedAt).Duration() > PlatformAdmission.MaximumAge) + { + throw new InvalidOperationException("The platform admission is stale. An act asks the gate again."); + } + + if (!admission.TryConsume()) + { + throw new InvalidOperationException("The platform admission was already used. One admission admits one act."); + } + + var previous = accessor.Current; + await using var scope = scopeFactory.CreateAsyncScope(); + var services = scope.ServiceProvider; + try + { + // Install in this async method, not a helper: an AsyncLocal write in a helper does not + // flow back to this scope's later resolutions. + ITenantContext context = new OperatorTenantContext(tenantId, admission.Operator.CorrelationId); + accessor.Current = context; + + var source = services.GetServices().OfType().Single(); + using var frame = source.Enter(admission, context); + return await services.GetRequiredService().Send(request, cancellationToken); + } + finally + { + accessor.Current = previous; + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs new file mode 100644 index 00000000..a5eeeba6 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs @@ -0,0 +1,113 @@ +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// Mints the trusted-operation descriptor of one admitted operator act, and of nothing else +/// (ADR-0102 § 1). +/// +/// +/// +/// One frame, one act. The executor enters it with the admission and the context it built; +/// then answers only for the request types the catalog binds to that +/// admission's operation, in that context object, while the frame is open. Every other request in +/// the scope, and every request outside an entered frame, gets null, which is what the one-descriptor +/// rule of the authorization coordinator needs from a source that does not own the request. +/// +/// +/// The descriptor carries the operator attribution of the admission, which the audit composer +/// records as metadata.operator and the reason slug. It carries no ticket. +/// +/// +internal sealed class PlatformOperatorOperationSource( + IOperationPolicyCatalog policies, + PlatformOperatorActCatalog acts, + ITenantContextAccessor accessor) : TrustedOperationDescriptor.MintingSource, ITrustedOperationSource +{ + private Frame? _frame; + + internal IDisposable Enter(PlatformAdmission admission, ITenantContext context) + { + ArgumentNullException.ThrowIfNull(admission); + ArgumentNullException.ThrowIfNull(context); + if (!CanIssue || _frame is not null || !PlatformOperations.IsRegistered(admission.Operation) + || admission.Operation.NeedsPlatformRole) + { + throw new InvalidOperationException("Operator act provenance is invalid."); + } + + var frame = new Frame(admission, context); + _frame = frame; + if (!IsEvidenceCurrent(frame)) + { + frame.Close(); + throw new InvalidOperationException("Operator act provenance is invalid."); + } + + return new Scope(frame); + } + + public TrustedOperationDescriptor? Capture(Type requestType, ITenantContext context) + { + ArgumentNullException.ThrowIfNull(requestType); + ArgumentNullException.ThrowIfNull(context); + if (!CanIssue || _frame is not { } frame || !ReferenceEquals(frame.Context, context) || !IsEvidenceCurrent(frame) + || !acts.TryGet(requestType, out var act) + || !ReferenceEquals(act.Operation, frame.Admission.Operation) + || !policies.TryGet(requestType, out var policy) + || policy.Kind != OperationPolicyKind.FiniteTrusted + || policy.AllowedSources is not [AuthorizationSourceKind.PlatformOperator]) + { + return null; + } + + return ForOperation( + AuthorizationSourceKind.PlatformOperator, requestType, context, frame, PlatformOperatorAttribution.From(frame.Admission)); + } + + protected override bool IsEvidenceCurrent(object? evidence) => evidence is Frame frame + && ReferenceEquals(frame, _frame) && frame.IsOpen + && frame.Context.HostScope is null && frame.Context.UserId is null + && frame.Context.IsResolved && frame.Context.Origin == TenantContextOrigin.Ambient + && ReferenceEquals(accessor.Current, frame.Context); + + private sealed class Frame(PlatformAdmission admission, ITenantContext context) + { + private int _closed; + + internal PlatformAdmission Admission { get; } = admission; + + internal ITenantContext Context { get; } = context; + + internal bool IsOpen => Volatile.Read(ref _closed) == 0; + + internal void Close() => Interlocked.Exchange(ref _closed, 1); + + public override string ToString() => nameof(Frame); + } + + private sealed class Scope(Frame frame) : IDisposable + { + public void Dispose() => frame.Close(); + } +} + +/// Registers the operator-act source and executor over a closed act catalog. +public static class PlatformOperatorActRegistration +{ + /// Adds the executor, the catalog and the scoped source (ADR-0102 § 1). + public static IServiceCollection AddPlatformOperatorActs( + this IServiceCollection services, PlatformOperatorActCatalog catalog) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(catalog); + services.AddSingleton(catalog); + services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + return services; + } +} diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs b/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs index 5e03bd62..9a4ac26b 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs @@ -148,7 +148,8 @@ private static AuditEntryDraft Compose( EntityId = intent.ProviderEvent?.AffectedUserId.Value.ToString("D") ?? subject.EntityId, Outcome = outcome, ErrorKey = errorKey, - Reason = null, + // The closed reason slug of an operator act (ADR-0101 § 9); null for every other source. + Reason = intent.Authorization?.Operator?.ReasonSlug, // The subject's EARLIEST capture's before and its LATEST capture's after, nulls // included. Skipping nulls looks like tidying and is not: the interceptor sets @@ -199,6 +200,11 @@ private static AuditEntryDraft Compose( || intent.ActorUserId != authorization.Actor) throw new ArgumentException("Resource audit authorization attribution is invalid.", nameof(intent)); fields.Add("\"authorization\":" + authorization.ToJson()); + if (authorization.Operator is { } attribution) + { + // Attribution only: the ticket never rides on a row a tenant can read. + fields.Add("\"operator\":" + attribution.ToOperatorJson()); + } } if (intent.CausationId is { } causation) { diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuthorizationAuditContext.cs b/backend/src/LearnStack.SharedKernel/Audit/AuthorizationAuditContext.cs index 6596d561..dbb08fcc 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/AuthorizationAuditContext.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/AuthorizationAuditContext.cs @@ -3,6 +3,7 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; namespace LearnStack.SharedKernel.Audit; @@ -21,7 +22,7 @@ private AuthorizationAuditContext(OperationInvocation invocation, ProtectedOpera if (!invocation.IsActive || target is not { } tenant || !StronglyTypedId.IsAssigned(tenant) || tenant == TenantId.PlatformSentinel || invocation.Actor is { } actor && !StronglyTypedId.IsAssigned(actor) - || invocation.Actor is null && invocation.TrustedSource is not { SourceKind: AuthorizationSourceKind.Seed } + || invocation.Actor is null && invocation.TrustedSource is not { SourceKind: AuthorizationSourceKind.Seed or AuthorizationSourceKind.PlatformOperator } || invocation.Candidate is { } candidate && invocation.Actor != candidate.Actor || (decision is not null && (!ReferenceEquals(decision.Invocation, invocation) || !decision.IsActive)) || (invocation.Candidate is null) == (invocation.TrustedSource is null) @@ -33,6 +34,7 @@ private AuthorizationAuditContext(OperationInvocation invocation, ProtectedOpera Actor = invocation.Actor; PolicyId = invocation.Policy.Id; SourceKind = invocation.Candidate?.SourceKind ?? invocation.TrustedSource!.SourceKind; + Operator = invocation.TrustedSource?.Operator; MembershipIds = decision?.MembershipIds ?? []; RoleIds = decision?.RoleIds ?? []; Route = transport?.Route; @@ -59,6 +61,9 @@ private AuthorizationAuditContext(OperationInvocation invocation, ProtectedOpera public UserId? Actor { get; } public string PolicyId { get; } public AuthorizationSourceKind SourceKind { get; } + + /// The admitted operator and closed reason of an operator act; null for every other source. + public PlatformOperatorAttribution? Operator { get; } public ImmutableArray MembershipIds { get; } public ImmutableArray RoleIds { get; } public string? Route { get; } @@ -80,6 +85,7 @@ public string ToJson() { AuthorizationSourceKind.Http => "http", AuthorizationSourceKind.Seed => "seed", AuthorizationSourceKind.IntegrationEvent => "event", AuthorizationSourceKind.BackgroundJob => "job", + AuthorizationSourceKind.PlatformOperator => "operator", _ => throw new InvalidOperationException("Authorization source is unknown."), }), "\"memberships\":[" + string.Join(',', MembershipIds.Select(id => AuditJson.Quote(id.ToString("D")))) + "]", diff --git a/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs b/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs index b4a747d2..5e544477 100644 --- a/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs +++ b/backend/src/LearnStack.SharedKernel/Entitlements/KillswitchKeys.cs @@ -59,4 +59,25 @@ public static class KillswitchKeys [EmailDispatchEnabled] = true, [AnalyticsIngestEnabled] = true, }.ToFrozenDictionary(); + + private static readonly FrozenDictionary ByName = + All.Keys.ToFrozenDictionary(key => key.Value, StringComparer.Ordinal); + + /// + /// Resolves a switch the wire names to the registry's own member, so a caller reads a key from here + /// and never spells one. + /// + /// The key as an operator or a route carries it. + /// The registry member when the name is one. + /// false for a name the registry does not declare. + public static bool TryResolve(string? name, out KillswitchKey key) + { + if (name is not null && ByName.TryGetValue(name, out key)) + { + return true; + } + + key = default; + return false; + } } diff --git a/backend/src/LearnStack.SharedKernel/Permissions/AuthorizationCandidate.cs b/backend/src/LearnStack.SharedKernel/Permissions/AuthorizationCandidate.cs index dc215528..42c91fb9 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/AuthorizationCandidate.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/AuthorizationCandidate.cs @@ -3,7 +3,7 @@ namespace LearnStack.SharedKernel.Permissions; -public enum AuthorizationSourceKind { Http = 1, Seed = 2, IntegrationEvent = 3, BackgroundJob = 4 } +public enum AuthorizationSourceKind { Http = 1, Seed = 2, IntegrationEvent = 3, BackgroundJob = 4, PlatformOperator = 5 } /// A question from an enumerated trusted owner, never authority supplied by a UserId alone. public sealed class AuthorizationCandidate diff --git a/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs index 988a23c3..f94e3fc9 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs @@ -55,7 +55,8 @@ private OperationPolicy(Type requestType, string id, OperationPolicyKind kind, || (requiresOrglessWrite && alternatives.Any(clause => clause.ReadScope != OperationReadScope.Scoped)) || (kind == OperationPolicyKind.FiniteTrusted) != !allowedSources.IsDefaultOrEmpty || allowedSources.Any(source => source is not (AuthorizationSourceKind.Seed - or AuthorizationSourceKind.IntegrationEvent or AuthorizationSourceKind.BackgroundJob)) + or AuthorizationSourceKind.IntegrationEvent or AuthorizationSourceKind.BackgroundJob + or AuthorizationSourceKind.PlatformOperator)) || allowedSources.Distinct().Count() != allowedSources.Length || allowedSources.Contains(AuthorizationSourceKind.IntegrationEvent) != (eventHandler is not null) || eventHandler is { IsAbstract: true } or { ContainsGenericParameters: true } diff --git a/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs new file mode 100644 index 00000000..c88ff545 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs @@ -0,0 +1,133 @@ +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.SharedKernel.Permissions; + +/// Proof that one operator act is current on its own owner and holds its ordered locks. +public sealed class OperatorActAdmission +{ + internal OperatorActAdmission(OperationInvocation invocation, object request, TenantId tenantId, IdentityMutationLockPlan plan) + { + Invocation = invocation; + Request = request; + TenantId = tenantId; + Plan = plan; + } + + /// The invocation the act runs under. + public OperationInvocation Invocation { get; } + + /// The exact request object. + public object Request { get; } + + /// The tenant the operator named and the context carries. + public TenantId TenantId { get; } + + /// The ordered lock plan held for the act. + public IdentityMutationLockPlan Plan { get; } + + /// + public override string ToString() => nameof(OperatorActAdmission); +} + +/// +/// The handler-side check of an operator act, the counterpart of the seed guards (ADR-0102 § 1, § 7). +/// +/// +/// +/// The pipeline has already refused any request whose policy does not list the operator source and +/// whose descriptor was not minted for an admitted act. This guard restates that on the handler's own +/// owner, so a handler can be called only from that pipeline: the invocation is the live one for this +/// exact request object and context, its policy is finite and names the operator source alone, its +/// descriptor still matches, the context is the ambient one the executor installed for the tenant the +/// act names (no organization, no host scope, no user), and the transaction is the single ordinary +/// read-write owner that announced exactly that tenant. +/// +/// +/// It then takes the ordered locks of the plan before any read the act decides on, and +/// asks again before each write, as the seed guards do. +/// +/// +public sealed class OperatorActGuard( + IOperationInvocationContext execution, + ITenantContext context, + IUnitOfWork unit, + IIdentityMutationLocks locks) +{ + /// Checks the act and acquires the plan; a refusal is a Problem Details-ready failure. + public async Task> AdmitAsync( + object request, IdentityMutationLockPlan plan, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(plan); + var invocation = execution.CurrentInvocation; + if (!HasInvocation(invocation, request) || !HasOwner(plan.TenantId)) + { + return Refused(); + } + + var admission = new OperatorActAdmission(invocation!, request, plan.TenantId, plan); + try + { + await locks.AcquireAsync(plan, cancellationToken); + } + catch (IdentityMutationLockException) + { + unit.MarkRollbackOnly(); + return Unavailable(); + } + + return RequireCurrent(admission) is { IsFailure: true } failure + ? Result.Fail(failure.Error) + : Result.Ok(admission); + } + + /// Asks again, before a write, whether the act is still the live one and its locks still held. + public Result RequireCurrent(OperatorActAdmission admission) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(execution.CurrentInvocation, admission.Invocation) + || !HasInvocation(admission.Invocation, admission.Request) || !HasOwner(admission.TenantId)) + { + return RefusedNone(); + } + + try + { + locks.RequireCurrent(admission.Plan); + return Result.Ok(None.Value); + } + catch (IdentityMutationLockException) + { + unit.MarkRollbackOnly(); + return Result.Fail(new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + } + } + + private bool HasInvocation(OperationInvocation? invocation, object request) => invocation is { IsActive: true, EntryKind: OperationEntryKind.Application } + && ReferenceEquals(invocation.Operation, request) && ReferenceEquals(invocation.Context, context) + && invocation.Policy.RequestType == request.GetType() && invocation.Policy.Kind == OperationPolicyKind.FiniteTrusted + && invocation.Policy.AllowedSources is [AuthorizationSourceKind.PlatformOperator] + && invocation.TrustedSource is { SourceKind: AuthorizationSourceKind.PlatformOperator } source + && source.Matches(request.GetType(), context); + + private bool HasOwner(TenantId tenantId) => context.IsResolved && context.TenantId == tenantId + && context.OrganizationId is null && context.HostScope is null && context.UserId is null + && unit.HasActiveTransaction && !unit.IsRollbackOnly && unit.Mode == TransactionMode.ReadWrite + && unit.Transaction is not null && unit is not IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } + && unit.GetTenantContextAnnouncement(unit.Transaction) is { Generation: > 0 } announcement + && announcement.TenantId == tenantId; + + private static Result Refused() => + Result.Fail(new Error(new LocalizedMessage("lockey_forbidden"))); + + private static Result Unavailable() => + Result.Fail(new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + + private static Result RefusedNone() => Result.Fail(new Error(new LocalizedMessage("lockey_forbidden"))); +} diff --git a/backend/src/LearnStack.SharedKernel/Permissions/TrustedOperationDescriptor.cs b/backend/src/LearnStack.SharedKernel/Permissions/TrustedOperationDescriptor.cs index fd5a9e92..84e3e1c2 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/TrustedOperationDescriptor.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/TrustedOperationDescriptor.cs @@ -1,9 +1,10 @@ using System.Diagnostics.CodeAnalysis; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; namespace LearnStack.SharedKernel.Permissions; -/// Captures only the current finite seed, delivery or job owner. +/// Captures only the current finite seed, delivery, job or operator-act owner. public interface ITrustedOperationSource { TrustedOperationDescriptor? Capture(Type requestType, ITenantContext context); @@ -17,19 +18,28 @@ public sealed class TrustedOperationDescriptor private readonly object? _evidence; private TrustedOperationDescriptor(MintingSource source, AuthorizationSourceKind kind, - Type requestType, ITenantContext context, object? evidence) + Type requestType, ITenantContext context, object? evidence, PlatformOperatorAttribution? @operator) { if (kind is not (AuthorizationSourceKind.Seed or AuthorizationSourceKind.IntegrationEvent - or AuthorizationSourceKind.BackgroundJob) || requestType.IsAbstract || requestType.ContainsGenericParameters) + or AuthorizationSourceKind.BackgroundJob or AuthorizationSourceKind.PlatformOperator) + || requestType.IsAbstract || requestType.ContainsGenericParameters + || (kind == AuthorizationSourceKind.PlatformOperator) != (@operator is not null)) throw new ArgumentException("Trusted operation provenance is invalid."); _source = source; _context = context; _evidence = evidence; SourceKind = kind; RequestType = requestType; + Operator = @operator; } public AuthorizationSourceKind SourceKind { get; } + + /// + /// The admitted operator and closed reason of an operator act, present exactly when + /// is . + /// + public PlatformOperatorAttribution? Operator { get; } public Type RequestType { get; } public bool IsActive => _source.IsActive && _source.MatchesEvidence(_evidence); @@ -51,12 +61,13 @@ public abstract class MintingSource : IDisposable protected abstract bool IsEvidenceCurrent(object? evidence); protected TrustedOperationDescriptor ForOperation(AuthorizationSourceKind kind, - Type requestType, ITenantContext context, object? evidence = null) + Type requestType, ITenantContext context, object? evidence = null, + PlatformOperatorAttribution? @operator = null) { ArgumentNullException.ThrowIfNull(requestType); ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(!IsActive, this); - return new(this, kind, requestType, context, evidence); + return new(this, kind, requestType, context, evidence, @operator); } public void Dispose() diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index 7beebcba..1a26534b 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -47,8 +47,29 @@ public static class PlatformOperations public static PlatformOperation KillswitchToggle { get; } = new( "tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true); + /// Provision a Tenant and its default Organization (ADR-0102 § 2). + public static PlatformOperation TenantProvision { get; } = new( + "tenancy.tenant.create", "tenant_provision", PlatformPermissions.TenantWrite, false); + + /// Map a host to a Tenant (ADR-0102 § 2, § 4). + public static PlatformOperation HostMap { get; } = new( + "tenancy.hostmapping.write", "host_map", PlatformPermissions.TenantWrite, false); + + /// Create one finite Role template (ADR-0102 § 2). + public static PlatformOperation RoleInitialize { get; } = new( + "identity.role.initialize", "role_initialize", PlatformPermissions.TenantBootstrapWrite, false); + + /// Create the first tenant-wide administrator Membership (ADR-0102 § 7). + public static PlatformOperation FirstAdminCreate { get; } = new( + "identity.membership.create_first_admin", "first_admin_create", PlatformPermissions.TenantBootstrapWrite, false); + + /// Create a replacement administrator for a Tenant that has none (ADR-0102 § 8). + public static PlatformOperation AdminRecover { get; } = new( + "identity.membership.recover_admin", "admin_recover", PlatformPermissions.TenantBootstrapWrite, false); + /// Every registered operation. - public static IReadOnlyList All { get; } = [KillswitchToggle]; + public static IReadOnlyList All { get; } = + [KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover]; /// Whether is one of the registered instances. public static bool IsRegistered(PlatformOperation? operation) => diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs new file mode 100644 index 00000000..7b86c4a6 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs @@ -0,0 +1,75 @@ +using LearnStack.SharedKernel.Audit; + +namespace LearnStack.SharedKernel.Platform; + +/// +/// Who acted and under which closed reason, as the audit rows of an operator act record it +/// (ADR-0101 § 9). +/// +/// +/// +/// Taken from an admission and from nothing else, so a row cannot name an operator who was not +/// admitted. It holds no ticket: the ticket appears only in rows a tenant cannot read, and an +/// attribution rides on rows a tenant can. +/// +/// +/// One definition of the metadata.operator shape, used by the platform scope's rows and by +/// the pipeline's rows alike, so the two cannot drift. +/// +/// +public sealed class PlatformOperatorAttribution +{ + private PlatformOperatorAttribution(string issuer, string subjectDigest, string acr, string executor, string reasonSlug) + { + ArgumentException.ThrowIfNullOrWhiteSpace(issuer); + ArgumentException.ThrowIfNullOrWhiteSpace(subjectDigest); + ArgumentException.ThrowIfNullOrWhiteSpace(acr); + ArgumentException.ThrowIfNullOrWhiteSpace(executor); + ArgumentException.ThrowIfNullOrWhiteSpace(reasonSlug); + Issuer = issuer; + SubjectDigest = subjectDigest; + Acr = acr; + Executor = executor; + ReasonSlug = reasonSlug; + } + + /// The pinned operator issuer. + public string Issuer { get; } + + /// The operator's non-reversible subject handle. + public string SubjectDigest { get; } + + /// The accepted acr the token carried. + public string Acr { get; } + + /// The component that took the request. + public string Executor { get; } + + /// The closed reason slug of the admitted operation. + public string ReasonSlug { get; } + + /// The attribution of an admitted act. + public static PlatformOperatorAttribution From(PlatformAdmission admission) + { + ArgumentNullException.ThrowIfNull(admission); + var op = admission.Operator; + return new(op.Issuer, op.SubjectDigest, op.Acr, op.Executor, admission.Operation.ReasonSlug); + } + + /// + /// The operator object of metadata, as JSON text: issuer, subject digest, kind, + /// accepted acr and executor, and the ticket only when one is supplied. + /// + public string ToOperatorJson(string? ticket = null) => + "{" + + "\"issuer\":" + AuditJson.Quote(Issuer) + + ",\"subjectDigest\":" + AuditJson.Quote(SubjectDigest) + + ",\"kind\":\"human\"" + + ",\"acr\":" + AuditJson.Quote(Acr) + + ",\"executor\":" + AuditJson.Quote(Executor) + + (ticket is null ? string.Empty : ",\"ticket\":" + AuditJson.Quote(ticket)) + + "}"; + + /// + public override string ToString() => nameof(PlatformOperatorAttribution); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs index e5a21d7e..ded690a5 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -24,8 +24,16 @@ public static class PlatformPermissions public static PermissionDefinition KillswitchWrite { get; } = new(PermissionScope.Platform, "platform.killswitch.write"); + /// Provision a Tenant and map its hosts (ADR-0102). + public static PermissionDefinition TenantWrite { get; } = + new(PermissionScope.Platform, "platform.tenant.write"); + + /// Initialize Role templates, create the first administrator and recover an administrator (ADR-0102). + public static PermissionDefinition TenantBootstrapWrite { get; } = + new(PermissionScope.Platform, "platform.tenant_bootstrap.write"); + /// Every registered Platform permission. - public static IReadOnlyList All { get; } = [KillswitchWrite]; + public static IReadOnlyList All { get; } = [KillswitchWrite, TenantWrite, TenantBootstrapWrite]; /// Finds a registered Platform permission by its key. public static bool TryGet(string? key, out PermissionDefinition definition) diff --git a/backend/src/LearnStack.Tools.Seeder/Program.cs b/backend/src/LearnStack.Tools.Seeder/Program.cs index 14406dba..73b1931e 100644 --- a/backend/src/LearnStack.Tools.Seeder/Program.cs +++ b/backend/src/LearnStack.Tools.Seeder/Program.cs @@ -39,6 +39,17 @@ return 2; } +// The seed capability is a development capability (ADR-0102 § 10). Production tenants are onboarded +// through the operator surface, so a seeder started anywhere but a Development deployment refuses +// before it reads a credential or opens a connection. +if (!string.Equals(Environment.GetEnvironmentVariable("Deployment__Mode"), "Development", StringComparison.Ordinal)) +{ + Console.Error.WriteLine( + "seed: the seeder runs only when Deployment__Mode is Development. Production tenants are " + + "onboarded through the operator surface (docs/runbooks/tenant-onboarding.md)."); + return 2; +} + // The seeder is a host without an HTTP surface, and it exists so the two demo tenants are // written by the same commands a request writes them with — ADR-0042 requires that: a // seeder inserting the tenant and its default organization itself would be a second copy diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs new file mode 100644 index 00000000..5732419f --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs @@ -0,0 +1,45 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Contracts.OperatorActs; + +/// +/// Creates one finite Role template in an operator-named Tenant (ADR-0102 § 2, § 6). +/// +/// +/// Reachable only through the operator source. Naming the same role again with the same template is +/// the same act; a tenant that already has any Membership refuses, because a template is a +/// pristine-prefix operation. +/// +public sealed record OperatorInitializeRoleCommand(Guid RoleId, BuiltInRoleKey BuiltInKey, PermissionScope CapabilityScope) + : IRequest>; + +/// +/// Creates the first tenant-wide administrator of a Tenant that has never had a Membership +/// (ADR-0102 § 5, § 7). +/// +/// The new Membership's id, supplied so a retry is exact. +/// The administrator Role template the operator initialized. +/// +/// The person's sub at the identity authority's issuer. The person must already have signed in +/// once at the tenant's host, so a User exists; an email address is never an identifier. +/// +public sealed record OperatorCreateFirstAdminCommand( + Guid MembershipId, + Guid RoleId, + [property: PiiSensitive] string ProviderSubject) : IRequest>; + +/// +/// Creates a replacement tenant-wide administrator for a Tenant that has Membership history but no +/// active administrator (ADR-0102 § 8). +/// +/// +/// The only act that may add an administrator to a tenant with history, and only while none is active. +/// +public sealed record OperatorRecoverAdminCommand( + Guid MembershipId, + Guid RoleId, + [property: PiiSensitive] string ProviderSubject) : IRequest>; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs index d587189f..fd690df5 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs @@ -29,6 +29,12 @@ public interface IMembershipWriteStore : IAggregateWriteStoreRetains the exact scoped root after the complete User/tenant plan; reread before mutation. Task LockAsync(MembershipId membershipId, CancellationToken cancellationToken = default); Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default); + + /// + /// Whether the tenant has an Active, undeleted, tenant-wide Membership holding a tenant administrator + /// Role (ADR-0102 § 8). The recovery predicate; read under the ordered locks. + /// + Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default); Task ValidateGraphAsync(CancellationToken cancellationToken = default); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs new file mode 100644 index 00000000..5c7e65a1 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs @@ -0,0 +1,18 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.Abstractions; + +/// +/// Resolves an operator-supplied provider subject to the Active User it names, under the stored +/// identity authority (ADR-0102 § 5). +/// +/// +/// A confined single-act resolver: the request supplies only the provider subject, never the authority +/// or the derived key, and an unknown or non-Active subject answers null. The operator creates no +/// User and an email address is never an identifier. +/// +public interface IOperatorSubjectResolver +{ + /// The Active user for , or null. + Task ResolveActiveUserAsync(string providerSubject, CancellationToken cancellationToken = default); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs index 4696fa92..a47b4a9a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs @@ -3,6 +3,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Entry; @@ -40,6 +41,9 @@ public void Describe(IAuditCatalogBuilder builder) builder.MustAudit("identity.membership.create_first_seed_admin", OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.membership.create_seed", OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.membership_profile.set_seed_profile", OperationType.Update, typeof(Membership)); + builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); + builder.MustAudit("identity.membership.create_first_admin", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.membership.recover_admin", OperationType.SecurityEvent, typeof(Membership)); builder.Off(); builder.Off(); builder.MustAudit(IdentityOperationPolicySource.MembershipDirectoryOperation, OperationType.ReadSensitive, typeof(Membership)); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs index d219221e..2051c359 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -2,6 +2,7 @@ using LearnStack.Modules.Identity.Application.Contracts.CustomFields; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Federation; @@ -124,6 +125,9 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("identity.membership_profile.set_seed_profile", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("identity.role.verify_seed", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("identity.membership.verify_seed", AuthorizationSourceKind.Seed), + OperationPolicy.ForTrusted("identity.operator.initialize_role", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("identity.operator.create_first_admin", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("identity.operator.recover_admin", AuthorizationSourceKind.PlatformOperator), ]; private static OperationPolicy Federation(string id) => diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs new file mode 100644 index 00000000..b1cb11e7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs @@ -0,0 +1,229 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Identity.Application.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.OperatorActs; + +/// The operator acts' answers: a refusal an operator can act on, in the shapes the API already uses. +internal static class OperatorIdentityFailures +{ + internal static Result NotFound() => Result.Fail(new Error(new LocalizedMessage("lockey_not_found"))); + + internal static Result Unavailable() => Result.Fail(new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + + /// + /// A 409 with the reason on the field it concerns. The top-level code stays + /// business_rule_violation because the status map is closed and a module-specific code would + /// answer 500. + /// + internal static Result Rule(string field, string reason) => Result.Fail(new Error( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage(reason)], + })); +} + +/// +/// Creates one finite Role template for an operator (ADR-0102 § 2, § 6): under the tenant's ordered +/// lock, before any Membership exists, once. +/// +internal sealed class OperatorInitializeRoleCommandHandler( + IRoleWriteStore store, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public async Task> Handle(OperatorInitializeRoleCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!context.IsResolved || context.OrganizationId is not null || !SeedFoundationGate.ValidRoot(request.RoleId)) + return OperatorIdentityFailures.Rule("RoleId", "lockey_validation_failed"); + if (IdentityFoundationManifest.Version1.FindTemplate(request.BuiltInKey, request.CapabilityScope) is null) + return OperatorIdentityFailures.Rule("BuiltInKey", "lockey_role_template_unknown"); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + var plan = new IdentityMutationLockPlan([], context.TenantId, IdentityTenantLockMode.Exclusive); + var admission = await guard.AdmitAsync(request, plan, cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + try + { + var id = RoleId.From(request.RoleId); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + // The same template named again is the same act, so a reply lost on the wire costs nothing. + if (await store.FindAsync(id, cancellationToken) is { } existing) + { + return existing.TenantId == context.TenantId && existing.BuiltInKey == request.BuiltInKey + && existing.PermissionScope == request.CapabilityScope && existing.CreatedBy == UserId.SystemActor + && existing.MatchesInitialTemplate() + ? Result.Ok(request.RoleId) + : OperatorIdentityFailures.Rule("RoleId", "lockey_identifier_taken"); + } + + if (await store.HasMembershipHistoryAsync(cancellationToken)) + return OperatorIdentityFailures.Rule("$", "lockey_tenant_has_memberships"); + if (guard.RequireCurrent(admission.Value) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + + var role = Role.Create( + id, context.TenantId, request.BuiltInKey, request.CapabilityScope, clock.UtcNow, UserId.SystemActor); + if (role.IsFailure) return Result.Fail(role.Error); + await store.AddAsync(role.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(request.RoleId); + } + catch (IdentityFoundationStorageException) + { + return OperatorIdentityFailures.Rule("$", "lockey_identity_foundation_refused"); + } + catch (IdentityMutationLockException) + { + return OperatorIdentityFailures.Unavailable(); + } + } +} + +/// +/// The shared core of the two administrator acts: name the person, take the ordered locks, judge the +/// act's own predicate under them, create the Membership (ADR-0102 § 5, § 7, § 8). +/// +internal static class OperatorAdministratorCreation +{ + internal static async Task> CreateAsync( + object request, + Guid membershipId, + Guid roleId, + string providerSubject, + bool firstAdmin, + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock, + CancellationToken cancellationToken) + { + if (!context.IsResolved || context.OrganizationId is not null || !SeedFoundationGate.ValidRoot(membershipId) + || !SeedFoundationGate.ValidRoot(roleId) || string.IsNullOrWhiteSpace(providerSubject) || providerSubject.Length > 255) + return OperatorIdentityFailures.Rule("MembershipId", "lockey_validation_failed"); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + // The person first: naming a person who has not signed in refuses before any lock or write. + if (await subjects.ResolveActiveUserAsync(providerSubject, cancellationToken) is not { } userId + || !SeedFoundationGate.ValidUser(userId)) + return OperatorIdentityFailures.Rule("ProviderSubject", "lockey_bootstrap_required"); + + // The User fence before the tenant fence, as every Membership admission takes them. + var plan = new IdentityMutationLockPlan([userId], context.TenantId, IdentityTenantLockMode.Exclusive); + var admission = await guard.AdmitAsync(request, plan, cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + try + { + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + var id = MembershipId.From(membershipId); + var role = await roles.ReadAsync(RoleId.From(roleId), cancellationToken); + if (!IsAdministratorRole(role, context.TenantId, firstAdmin)) + return OperatorIdentityFailures.Rule("RoleId", "lockey_role_not_initialized"); + + // The same act named again finds its Membership, so a reply lost on the wire costs nothing. + if (await store.FindAsync(id, cancellationToken) is { } existing) + { + return existing.TenantId == context.TenantId && existing.UserId == userId + && existing.OrganizationId is null && existing.Status == MembershipStatus.Active + && existing.RoleAssignments.Any(assignment => assignment.RoleId.Value == roleId) + ? Result.Ok(membershipId) + : OperatorIdentityFailures.Rule("MembershipId", "lockey_identifier_taken"); + } + + // The act's own predicate, under the locks. The first administrator refuses any Membership + // history, so it is not a way to add an administrator to a tenant that has had members; the + // recovery refuses while an active tenant-wide administrator exists. + if (firstAdmin ? await store.HasMembershipHistoryAsync(cancellationToken) + : await store.HasActiveTenantAdministratorAsync(cancellationToken)) + { + return OperatorIdentityFailures.Rule( + "$", firstAdmin ? "lockey_tenant_has_memberships" : "lockey_administrator_exists"); + } + + if (guard.RequireCurrent(admission.Value) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + var membership = Membership.Create( + id, context.TenantId, null, userId, role!, clock.UtcNow, UserId.SystemActor); + if (membership.IsFailure) return Result.Fail(membership.Error); + await store.AddAsync(membership.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(membershipId); + } + catch (IdentityFoundationStorageException) + { + return OperatorIdentityFailures.Rule("$", "lockey_identity_foundation_refused"); + } + catch (IdentityMutationLockException) + { + return OperatorIdentityFailures.Unavailable(); + } + } + + // The first administrator takes the pristine template the operator initialized; a recovery takes any + // current tenant administrator Role of the tenant, because the Role may have been edited since. + private static bool IsAdministratorRole(Role? role, TenantId tenant, bool firstAdmin) => firstAdmin + ? SeedMembershipCreation.IsDeclaredRole(role, tenant, PermissionScope.Tenant, firstAdmin: true) + : role is not null && role.TenantId == tenant && role.PermissionScope == PermissionScope.Tenant + && role.IsTenantAdministrator; +} + +/// Creates the first tenant-wide administrator of a tenant that has never had a Membership. +internal sealed class OperatorCreateFirstAdminCommandHandler( + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public Task> Handle(OperatorCreateFirstAdminCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return OperatorAdministratorCreation.CreateAsync( + request, request.MembershipId, request.RoleId, request.ProviderSubject, true, + store, roles, subjects, context, lifecycle, guard, clock, cancellationToken); + } +} + +/// Creates a replacement administrator for a tenant that has none active. +internal sealed class OperatorRecoverAdminCommandHandler( + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public Task> Handle(OperatorRecoverAdminCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return OperatorAdministratorCreation.CreateAsync( + request, request.MembershipId, request.RoleId, request.ProviderSubject, false, + store, roles, subjects, context, lifecycle, guard, clock, cancellationToken); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs index 488a2471..72b50b9a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs @@ -92,7 +92,7 @@ internal static async Task> CreateAsync(object request, Guid member } } - private static bool IsDeclaredRole(Role? role, TenantId tenant, PermissionScope scope, bool firstAdmin) => + internal static bool IsDeclaredRole(Role? role, TenantId tenant, PermissionScope scope, bool firstAdmin) => role is { Version: 0, UpdatedAt: null, UpdatedBy: null } && role.TenantId == tenant && role.CreatedBy == UserId.SystemActor && role.CreatedAt != default && role.AdoptedReleaseVersion == 1 diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs index 892df9d5..ed675559 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs @@ -43,6 +43,7 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs index 6cfb96e7..710618d7 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs @@ -2,6 +2,7 @@ using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Identity.Application.Abstractions; using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Errors; using Microsoft.EntityFrameworkCore; @@ -276,6 +277,24 @@ public Task LockAsync(MembershipId membershipId, CancellationToken cancellationT public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.AnyAsync(cancellationToken)); + + public Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default) => + ContextualIdentityStorageControl.ReadAsync(async () => + { + // The administrator Roles first, judged by the domain's own definition (kernel grants + // included), then whether an Active tenant-wide Membership holds one of them. + var candidates = await db.Roles.Include(role => role.Grants) + .Where(role => role.BuiltInKey == BuiltInRoleKey.TenantAdmin && role.DeletedAt == null) + .ToListAsync(cancellationToken); + var administratorRoles = candidates.Where(role => role.IsTenantAdministrator).Select(role => role.Id).ToList(); + return administratorRoles.Count != 0 + && await db.Memberships.AnyAsync( + membership => membership.Status == MembershipStatus.Active && membership.DeletedAt == null + && membership.OrganizationId == null + && membership.RoleAssignments.Any(assignment => administratorRoles.Contains(assignment.RoleId)), + cancellationToken); + }); + public Task ValidateGraphAsync(CancellationToken cancellationToken = default) => control.ValidateGraphAsync(cancellationToken); public Task AddAsync(Membership aggregate, CancellationToken cancellationToken = default) { diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs new file mode 100644 index 00000000..18826988 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs @@ -0,0 +1,14 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261119140000_add_operator_subject_resolver")] +public sealed class add_operator_subject_resolver : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => OperatorSubjectResolverDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => OperatorSubjectResolverDdl.Remove(migrationBuilder); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs new file mode 100644 index 00000000..0e13ef85 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs @@ -0,0 +1,43 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// Resolves an operator-named provider subject to its Active User through the confined definer +/// (ADR-0102 § 5), on the tenant transaction the act already owns. +/// +/// +/// The stored authority comes from the deployment's qualified registration and the key is derived +/// here, so the request supplies the provider subject and nothing else. A subject the key derivation +/// refuses, an unknown subject and a non-Active user all answer null. +/// +public sealed class OperatorSubjectResolver(IdentityDbContext db, IdentityAuthorityQualification qualification) + : IOperatorSubjectResolver +{ + /// + public async Task ResolveActiveUserAsync(string providerSubject, CancellationToken cancellationToken = default) + { + var registration = qualification.Current + ?? throw new InvalidOperationException("Identity authority qualification is unavailable."); + IdentitySubjectKey key; + try + { + key = IdentitySubjectKey.Compute(registration.AuthorityId, providerSubject); + } + catch (ArgumentException) + { + return null; + } + + var authority = registration.AuthorityId.Value; + var bytes = key.ToByteArray(); + var found = await db.Database + .SqlQuery($"SELECT public.fn_identity_operator_resolve_user({authority}, {bytes}) AS \"Value\"") + .SingleAsync(cancellationToken); + return found is { } id ? UserId.From(id) : null; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs new file mode 100644 index 00000000..57d8cc0d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs @@ -0,0 +1,43 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The confined definer that resolves an operator-named provider subject to an Active User inside a +/// tenant transaction (ADR-0102 § 5). +/// +/// +/// users is under forced row security keyed by identity settings that every tenant announcement +/// blanks, so a tenant transaction cannot read it. This function runs as the migration owner, whose +/// policy branch sees the table, and takes the stored authority and the derived subject key as +/// arguments. It refuses any session but the application role, any transaction that is not an ordinary +/// read-write tenant one, any authority other than the stored one, and any key that is not 32 bytes; +/// it answers the id of an Active, undeleted user or null. It reads nothing else and writes nothing. +/// +internal static class OperatorSubjectResolverDdl +{ + internal static void Add(MigrationBuilder migration) => migration.Sql(""" + CREATE FUNCTION public.fn_identity_operator_resolve_user(selected_authority uuid, selected_subject_key bytea) + RETURNS uuid LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog AS $resolve$ + DECLARE found uuid; + BEGIN + IF session_user <> 'learnstack_app' + OR NULLIF(current_setting('app.tenant_id',true),'') IS NULL + OR current_setting('transaction_read_only') <> 'off' + OR current_setting('transaction_isolation') <> 'read committed' + OR selected_authority IS NULL OR selected_subject_key IS NULL OR length(selected_subject_key) <> 32 + OR NOT EXISTS (SELECT FROM public.identity_authority a WHERE a.id=1 AND a.authority_id=selected_authority) + THEN RAISE EXCEPTION 'Operator subject resolution refused.' USING ERRCODE='23514'; END IF; + SELECT u.id INTO found FROM public.users u + WHERE u.authority_id=selected_authority AND u.subject_key=selected_subject_key + AND u.status='Active' AND u.deleted_at IS NULL; + RETURN found; + END $resolve$; + REVOKE ALL ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) TO learnstack_app; + """); + + internal static void Remove(MigrationBuilder migration) => migration.Sql(""" + DROP FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea); + """); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs new file mode 100644 index 00000000..2e6d72a8 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs @@ -0,0 +1,36 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Tenancy.Application.Contracts.Tenant; + +/// +/// Provisions a Tenant and its default Organization for an admitted operator (ADR-0102 § 2, § 3). +/// +/// +/// The operator supplies the tenant's id and slug, and the act is idempotent on that pair: the same +/// pair finds the tenant already there, a known slug under another id refuses. Reachable only through +/// the operator source; the seed's own is a different request +/// with a different policy, so neither authority can perform the other's act. +/// +public sealed record OperatorProvisionTenantCommand( + TenantId TenantId, + string Slug, + string DisplayName, + OrganizationId DefaultOrganizationId, + string DefaultOrganizationSlug, + string DefaultOrganizationDisplayName) + : IRequest>; + +/// +/// Maps a host to the operator-named Tenant through the host-mapping store (ADR-0102 § 2, § 4). +/// +/// +/// The tenant comes from the context the executor installed for the act, not from this body. The +/// operator asserts ownership of the host; LearnStack verifies no DNS. +/// +public sealed record OperatorMapHostCommand( + string Host, + OrganizationId? OrganizationId = null, + bool IsActive = true, + bool IsPubliclyLive = true) : IRequest>; diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 43483b17..6c83f9f5 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -93,6 +93,16 @@ public void Describe(IAuditCatalogBuilder builder) .MustAudit( "tenancy.organization.create", OperationType.Create, typeof(Organization)) + // The operator's production provisioning writes the same two rows under the same two slugs + // (ADR-0102 § 9); the act differs in its source and in the operator it records, not in what + // happened, so the matrix keeps one row per operation. + .MustAudit( + "tenancy.tenant.create", OperationType.Create, typeof(Domain.Tenant)) + .MustAudit( + "tenancy.organization.create", OperationType.Create, typeof(Organization)) + .MustAudit( + "tenancy.hostmapping.write", OperationType.Create, typeof(PlatformHostMapping)) + .MustAudit( "tenancy.hostmapping.write", OperationType.Create, typeof(PlatformHostMapping)) .MustAudit( diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs index 38164652..8fa391a2 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs @@ -55,5 +55,7 @@ public sealed class TenancyOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("tenancy.seed.add_locale", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("tenancy.seed.set_locale", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("tenancy.seed.set_branding", AuthorizationSourceKind.Seed), + OperationPolicy.ForTrusted("tenancy.operator.provision_tenant", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("tenancy.operator.map_host", AuthorizationSourceKind.PlatformOperator), ]; } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs index cc950def..445e565b 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs @@ -3,7 +3,10 @@ using LearnStack.Modules.Tenancy.Application.Seeding; using LearnStack.Modules.Tenancy.Domain; using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; @@ -34,8 +37,10 @@ internal sealed class MapHostToTenantCommandHandler( IOrganizationScopeValidator organizations, IReservedHostRegistry reservedHosts, IHostResolutionInvalidator resolutionCache, - ITenantContext tenantContext, SeedTenantWriteGuard seedGuard) - : IRequestHandler> + ITenantContext tenantContext, SeedTenantWriteGuard seedGuard, OperatorActGuard operatorGuard, + ITenantExistenceReader tenantExistence) + : IRequestHandler>, + IRequestHandler> { public async Task> Handle( MapHostToTenantCommand request, CancellationToken cancellationToken) @@ -56,13 +61,52 @@ public async Task> Handle( var admission = await seedGuard.AdmitAsync(request, cancellationToken); if (admission.IsFailure) return Result.Fail(admission.Error); + return await MapAsync( + request.Host, request.OrganizationId, request.IsActive, request.IsPubliclyLive, + () => seedGuard.VerifyAsync(admission.Value, request, cancellationToken), idempotent: false, cancellationToken); + } + + /// + /// The operator's act: the same mapping through the same store and rules, for the tenant the executor + /// resolved. The operator asserts ownership of the host; the act is idempotent, so a mapping this + /// tenant already holds, identical to the request, is the answer rather than a collision. + /// + public async Task> Handle( + OperatorMapHostCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!tenantContext.IsResolved) + { + return Result.FailFor>(TenantContextMissing); + } + + var admission = await operatorGuard.AdmitAsync( + request, new IdentityMutationLockPlan([], tenantContext.TenantId, IdentityTenantLockMode.Exclusive), cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + + // The tenant must be there: the foreign key would answer 23503, which has no arm in the status + // map and would be a 500 after the transaction opened. Read under the tenant's own lock. + if (!await tenantExistence.ExistsAsync(cancellationToken)) + { + return Result.FailFor>(new Error(new LocalizedMessage("lockey_not_found"))); + } + + return await MapAsync( + request.Host, request.OrganizationId, request.IsActive, request.IsPubliclyLive, + () => Task.FromResult(operatorGuard.RequireCurrent(admission.Value)), idempotent: true, cancellationToken); + } + + private async Task> MapAsync( + string host, OrganizationId? requestedOrganization, bool isActive, bool isPubliclyLive, + Func>> verify, bool idempotent, CancellationToken cancellationToken) + { // The organization must be one of this tenant's. Nothing else checks it before // the insert: the composite foreign key does, but it raises 23503, which has no // arm in HttpStatusMap and therefore answers 500 — after the transaction opened // and the tenant was announced. Reading it here turns a caller's mistake into a // refusal they can act on, and the foreign key stays as the layer that makes the // race impossible rather than merely unlikely. - if (request.OrganizationId is { } organizationId + if (requestedOrganization is { } organizationId && !await organizations.BelongsToTenantAsync( tenantContext.TenantId, organizationId, cancellationToken)) { @@ -77,11 +121,11 @@ [new LocalizedMessage("lockey_organization_not_in_tenant")], } var mapping = PlatformHostMapping.Create( - request.Host, + host, tenantContext.TenantId, - request.OrganizationId, - request.IsActive, - request.IsPubliclyLive); + requestedOrganization, + isActive, + isPubliclyLive); // A host on Tenancy:PlatformHosts is classified before the resolver is called at // all, so a row naming it would be inert — never read, never logged, never @@ -101,8 +145,18 @@ [new LocalizedMessage("lockey_host_reserved")], })); } - if (await seedGuard.VerifyAsync(admission.Value, request, cancellationToken) is { IsFailure: true } changed) + if (await verify() is { IsFailure: true } changed) return Result.Fail(changed.Error); + + if (idempotent && await hosts.FindForUpdateAsync(mapping.Host, cancellationToken) is { } existing) + { + return existing.OrganizationId == mapping.OrganizationId && existing.IsActive == mapping.IsActive + && existing.IsPubliclyLive == mapping.IsPubliclyLive + ? Result.Ok(new HostMappingDto( + existing.Host, existing.TenantId, existing.OrganizationId, existing.IsActive, existing.IsPubliclyLive)) + : Result.FailFor>(HostTaken()); + } + try { await hosts.AddAsync(mapping, cancellationToken); @@ -114,14 +168,7 @@ [new LocalizedMessage("lockey_host_reserved")], // another tenant, which is why the answer says only that it is taken. Naming // the holder would turn this endpoint into an oracle for which hostnames // belong to which customers. - return Result.FailFor>( - new Error( - new LocalizedMessage("lockey_business_rule_violation"), - new Dictionary>(StringComparer.Ordinal) - { - [nameof(MapHostToTenantCommand.Host)] = - [new LocalizedMessage("lockey_host_taken")], - })); + return Result.FailFor>(HostTaken()); } // The negative cache remembers hosts that resolved to nothing, and this host just @@ -150,6 +197,13 @@ [new LocalizedMessage("lockey_host_taken")], mapping.IsPubliclyLive)); } + private static Error HostTaken() => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [nameof(MapHostToTenantCommand.Host)] = [new LocalizedMessage("lockey_host_taken")], + }); + /// /// The pipeline's own answer for an unresolved context, reused rather than restated. /// diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs new file mode 100644 index 00000000..2f8d8e75 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs @@ -0,0 +1,43 @@ +using FluentValidation; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; + +namespace LearnStack.Modules.Tenancy.Application.Tenant; + +/// +/// The operator's provisioning command refuses exactly what the seed's does: the same shared rules, run +/// on the same fields, so a refusal reaches the operator in the same Problem Details shape and the two +/// cannot drift. +/// +internal sealed class OperatorProvisionTenantCommandValidator : AbstractValidator +{ + private static readonly ProvisionTenantCommandValidator Rules = new(); + + public OperatorProvisionTenantCommandValidator() => + RuleFor(command => command).Custom((command, context) => + { + var result = Rules.Validate(new ProvisionTenantCommand( + command.TenantId, command.Slug, command.DisplayName, command.DefaultOrganizationId, + command.DefaultOrganizationSlug, command.DefaultOrganizationDisplayName)); + foreach (var failure in result.Errors) + { + context.AddFailure(failure); + } + }); +} + +/// The operator's host-mapping command refuses what the seed's does, for the same reasons. +internal sealed class OperatorMapHostCommandValidator : AbstractValidator +{ + private static readonly MapHostToTenantCommandValidator Rules = new(); + + public OperatorMapHostCommandValidator() => + RuleFor(command => command).Custom((command, context) => + { + var result = Rules.Validate(new MapHostToTenantCommand( + command.Host, command.OrganizationId, command.IsActive, command.IsPubliclyLive)); + foreach (var failure in result.Errors) + { + context.AddFailure(failure); + } + }); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs index 41c2daa3..49597297 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs @@ -3,6 +3,8 @@ using LearnStack.Modules.Tenancy.Application.Seeding; using LearnStack.Modules.Tenancy.Domain; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Persistence; @@ -49,13 +51,22 @@ namespace LearnStack.Modules.Tenancy.Application.Tenant; /// Cross_Aggregate_Writes_Are_Confined_To_Tenant_Provisioning asserts. A combined /// port would hide the cross-aggregate write from the rule that exists to count it. /// +/// +/// One class, two commands. The operator's production provisioning +/// (, ADR-0102) is handled here too, so the three-write +/// order, the conflict mapping and the two-port exception exist once; the seed and operator paths +/// differ only in their guard and in what they do when the tenant is already there. The operator act +/// runs on a context the executor resolved for the tenant it names, so the tenant it creates is +/// announced by the ordinary setter and row security admits the insert. +/// /// internal sealed class ProvisionTenantCommandHandler( ITenantWriteStore tenants, IOrganizationWriteStore organizations, IClock clock, - IGuidFactory guids, SeedTenantWriteGuard seedGuard) - : IRequestHandler> + IGuidFactory guids, SeedTenantWriteGuard seedGuard, OperatorActGuard operatorGuard) + : IRequestHandler>, + IRequestHandler> { public async Task> Handle( ProvisionTenantCommand request, CancellationToken cancellationToken) @@ -72,7 +83,7 @@ public async Task> Handle( try { - return await ProvisionAsync(request, actor, admission.Value, cancellationToken); + return await ProvisionAsync(request, actor, () => seedGuard.RequireCurrent(admission.Value, request), cancellationToken); } catch (AggregateConflictException conflict) { @@ -96,11 +107,65 @@ public async Task> Handle( } } + /// + /// The operator's act: the same three writes, once the act is known to be the live admitted one and + /// no tenant already carries the operator's id. + /// + public async Task> Handle( + OperatorProvisionTenantCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + + var admission = await operatorGuard.AdmitAsync( + request, new IdentityMutationLockPlan([], request.TenantId, IdentityTenantLockMode.Exclusive), cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + + // The act is idempotent on the pair (id, slug), so a reply lost on the wire costs nothing: the + // tenant is already there and the same pair finds it. A known slug under another id is the + // database's own answer, below, because row security hides another tenant's row from this read. + var existing = await tenants.FindAsync(request.TenantId, cancellationToken); + if (existing is not null) + { + return existing.Slug == request.Slug && existing.DefaultOrganizationId == request.DefaultOrganizationId + ? Result.Ok(new ProvisionedTenantDto( + request.TenantId, existing.Slug, request.DefaultOrganizationId, request.DefaultOrganizationSlug)) + : Result.FailFor>(TakenFor(nameof(OperatorProvisionTenantCommand.TenantId))); + } + + try + { + return await ProvisionAsync( + new ProvisionTenantCommand( + request.TenantId, request.Slug, request.DisplayName, request.DefaultOrganizationId, + request.DefaultOrganizationSlug, request.DefaultOrganizationDisplayName), + UserId.SystemActor, + () => operatorGuard.RequireCurrent(admission.Value), + cancellationToken); + } + catch (AggregateConflictException conflict) + { + var (field, reason) = ConflictFor(conflict.ConstraintName); + return Result.FailFor>(new Error( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage(reason)], + })); + } + } + + private static Error TakenFor(string field) => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage("lockey_identifier_taken")], + }); + /// The three writes, in the one order the schema permits. private async Task> ProvisionAsync( - ProvisionTenantCommand request, UserId actor, SeedTenantWriteAdmission admission, CancellationToken cancellationToken) + ProvisionTenantCommand request, UserId actor, Func> requireCurrent, CancellationToken cancellationToken) { - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changed) + if (requireCurrent() is { IsFailure: true } changed) return Result.Fail(changed.Error); var tenant = Domain.Tenant.Create( request.TenantId, request.Slug, request.DisplayName, clock, actor); @@ -109,7 +174,7 @@ private async Task> ProvisionAsync( // (tenant_id, id), so its row has nothing to reference until this one lands. await tenants.AddAsync(tenant, cancellationToken); - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changedAfterTenant) + if (requireCurrent() is { IsFailure: true } changedAfterTenant) return Result.Fail(changedAfterTenant.Error); var organization = Organization.Create( request.DefaultOrganizationId, @@ -125,7 +190,7 @@ private async Task> ProvisionAsync( // at a row that does not exist when the tenant is inserted, and the foreign key // behind it is MATCH SIMPLE — which skips the check only while the column is // null. Setting it on the insert would defeat that and fail. - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changedAfterOrganization) + if (requireCurrent() is { IsFailure: true } changedAfterOrganization) return Result.Fail(changedAfterOrganization.Error); tenant.AssignDefaultOrganization(request.DefaultOrganizationId, clock, guids, actor); await tenants.UpdateAsync(tenant, cancellationToken); diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index 05b241ed..d094aeb5 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -204,6 +204,10 @@ [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison "JWT bearer metadata and JWKS (ADR-0064): the fixed Authentication:Tenant:Issuer only", ["LearnStack.Api/Authentication/CurrentInvitationRecipientReader.cs"] = "the invitation recipient's UserInfo read (ADR-0093): the fixed tenant-realm issuer only", + ["LearnStack.Api/Authentication/BoundedMetadataReader.cs"] = + "the bounded metadata read both bearer schemes share (ADR-0064, ADR-0101 § 2): the fixed issuer each scheme configures only", + ["LearnStack.Api/Authentication/PlatformOperatorMetadata.cs"] = + "the operator scheme's metadata and JWKS client (ADR-0101 § 2): the one pinned PlatformOperator:Issuer, never a followed redirect", ["LearnStack.Infrastructure/Email/Smtp/SmtpEmailProvider.cs"] = "operator-configured SMTP host for invitation mail; not a tenant URL", }; diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 4c1c7234..8adedabb 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -43,6 +43,7 @@ public sealed partial class IdentityAuditConventionTests private const string OrdinaryAuditOwner = "LearnStack.Application.Audit.AuditExecutionCoordinator"; private static readonly string[] AuthorizationPrimaryKeyFilter = ["23505", "public", "audit_log", "audit_log_pkey"]; private const string SeedTenancyGuard = "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard"; + private const string OperatorActGuard = "LearnStack.SharedKernel.Permissions.OperatorActGuard"; private const string SeedCustomizationGuard = "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard"; private const string SeedEducationGuard = "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard"; private const string SeedOriginHandler = "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler"; @@ -99,6 +100,8 @@ private static readonly (string Owner, string Method, int Count)[] CurrentInvoca (FixedCompletionSource, "HasInvocation", 1), (SeedTenancyGuard, "AdmitAsync", 1), (SeedTenancyGuard, "RequireCurrent", 1), + (OperatorActGuard, "AdmitAsync", 1), + (OperatorActGuard, "RequireCurrent", 1), (SeedTenancyGuard, "AllowsIdentityContinuationAsync", 1), (SeedTenancyGuard, "AllowsContentContinuationAsync", 1), (SeedTenancyGuard, "g__Current|14_0", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs index 6be1572d..4f03f1d8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -116,6 +116,7 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.Modules.Tenancy.Application.Authorization.TenancyAdministrationAuthorization.AdmitWriteAsync", "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard.PrepareAsync", "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard.PrepareAsync", + "LearnStack.SharedKernel.Permissions.OperatorActGuard.AdmitAsync", "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard.AdmitAsync", "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler.Handle", "LearnStack.Modules.Identity.Application.Federation.FederationCommandHandlers.ActAsync", @@ -139,6 +140,7 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard.IsCurrent", "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard.IsCurrent", "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard.RequireCurrent", + "LearnStack.SharedKernel.Permissions.OperatorActGuard.RequireCurrent", "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler.Handle", "LearnStack.Modules.Identity.Infrastructure.Persistence.SeedIdentityStageReader.HasNoRoleHistoryAsync", "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationPrerequisiteReader.IsCompleteAsync", diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 46b0108f..cc1b070a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -307,7 +307,7 @@ private static List FullNames(IEnumerable types, Type baseType) => public void The_Platform_Scope_Writes_No_Tenant_Context_And_Sets_No_Session_Variable() { // Two closed sets it must stay outside of, both stated in Accepted ADRs. It is - // not one of the four writers of ITenantContextAccessor.Current — ADR-0036 names + // not one of the writers of ITenantContextAccessor.Current — ADR-0036 names // it as explicitly not one — and it is not a ninth setter of app.tenant_id beside // ADR-0040's eight, because the role bypasses policies and there is nothing to // announce to. SetTenant_Callers_Are_The_Enumerated_Four covers the first diff --git a/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs index 982e76ef..c2eff745 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs @@ -305,7 +305,15 @@ internal static bool SkipValue(Mono.Collections.Generic.Collection .Where(type => type.IsDefined(typeof(PublicSurfaceAttribute), false)) .Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); - private static IEnumerable MinimalBypasses(ModuleDefinition module) => Types([module]).Where(type => + // The platform operator surface (ADR-0101 § 4) is its own closed surface with its own scheme: minimal + // endpoints in a group, one verb, one policy, one fixed metadata. It is excluded by exact type (and the + // compiler's nested types of it), so a mapping anywhere else is still a bypass; its own population is + // asserted in PlatformOperatorHttpTests. + private const string OperatorSurface = "LearnStack.Api.Platform.PlatformOperatorEndpoints"; + + private static IEnumerable MinimalBypasses(ModuleDefinition module) => Types([module]) + .Where(type => type.FullName != OperatorSurface && !type.FullName.StartsWith(OperatorSurface + "/", StringComparison.Ordinal)) + .Where(type => { var methods = Il.Methods(type).Where(method => method.Definition.HasBody).ToArray(); var composition = methods.SelectMany(method => method.Definition.Body.Instructions diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs index f9e7fbf0..02cdde90 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs @@ -174,7 +174,10 @@ public void SetTenant_Callers_Are_The_Enumerated_Four() // handler scope (integration events). HTTP and the acceptance/execution // halves of the integration-event scope and the job executor exist today; // the rule is written over the whole set so the next writer is a deliberate edit here rather - // than a silent addition there. + // than a silent addition there. The operator act executor (ADR-0102, ADR-0036 Amendment 3) + // is that deliberate edit: a fifth logical writer, which installs the resolved context + // of the tenant an admitted operator act names. The method keeps the name three Accepted + // ADRs and the catalogue cite. // // The needle is receiver-agnostic — a future `Activity.Current =` anywhere in // backend/src would trip this, which is a false positive to exempt by path @@ -212,10 +215,11 @@ public void SetTenant_Callers_Are_The_Enumerated_Four() "LearnStack.Infrastructure/Jobs/JobExecutor.ExternalCheckpoints.cs", "LearnStack.Infrastructure/Jobs/JobExecutor.External.cs", "LearnStack.Infrastructure/Jobs/JobExecutor.Recipients.cs", + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs", ], - "three of the four logical writers have landed — HTTP, jobs and the integration-event " - + "acceptance/execution scopes; all JobExecutor partials belong to one logical writer. " - + "HubCorrelationMiddleware belongs to its later phase; a fifth writer is how a " + "four of the five logical writers have landed — HTTP, jobs, the integration-event " + + "acceptance/execution scopes and the operator act executor; all JobExecutor partials belong to one " + + "logical writer. HubCorrelationMiddleware belongs to its later phase; a sixth writer is how a " + "request runs under a tenant nothing resolved"); } diff --git a/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs index 0414690d..4c404bc9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs @@ -13,6 +13,8 @@ public sealed class TrustedOperationSourceConventionTests private const string Seed = "LearnStack.Tools.Seeder.SeedOperationSource"; private const string Delivery = "LearnStack.Infrastructure.Messaging.DeliveryOperationSource"; private const string Job = "LearnStack.Application.Jobs.BackgroundJobOperationSource"; + private const string Operator = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorOperationSource"; + private const string OperatorExecutor = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActExecutor"; private const string Admission = "LearnStack.Application.Jobs.BackgroundJobExecutionAdmission"; private const string JobOwner = "LearnStack.SharedKernel.Jobs.JobApplicationSourceOwner"; @@ -20,7 +22,8 @@ public sealed class TrustedOperationSourceConventionTests public void Finite_operation_descriptors_have_exact_minters_private_construction_and_revocable_evidence() { using var census = Census.Read(); - Offenders(census).Should().BeEmpty("Fix: preserve the exact owned seed/delivery/job source set and its closed lifetime (ADR-0076)"); + Offenders(census).Should().BeEmpty( + "Fix: preserve the exact owned seed/delivery/job/operator source set and its closed lifetime (ADR-0076, ADR-0102)"); var descriptor = census.Type(Descriptor); Dirty(census, () => { @@ -53,9 +56,11 @@ public void Finite_operation_descriptors_have_exact_minters_private_construction (Delivery, "IsEvidenceCurrent", "LearnStack.SharedKernel.Persistence.IUnitOfWork", "GetTenantContextAnnouncement"), (Admission, "IsOperationEvidenceCurrent", JobOwner, "get_IsCurrentBinding"), (Admission, "IsOperationEvidenceCurrent", Admission, "IsLive"), + (Operator, "IsEvidenceCurrent", "LearnStack.SharedKernel.Tenancy.ITenantContextAccessor", "get_Current"), + (Operator, "Capture", "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActCatalog", "TryGet"), }) Dirty(census, () => RemoveCall(census.Body(type, method), target, name)); foreach (var (typeName, methodName) in new[] - { (Delivery, "Enter"), ("LearnStack.SharedKernel.Permissions.ITrustedOperationSource", "Capture") }) + { (Delivery, "Enter"), (Operator, "Enter"), ("LearnStack.SharedKernel.Permissions.ITrustedOperationSource", "Capture") }) foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) Dirty(census, () => { var module = census.Type(Seed).Module; @@ -74,17 +79,18 @@ private static List Offenders(Census census) var descriptor = census.Type(Descriptor); var constructors = descriptor.Methods.Where(method => method.IsConstructor).ToArray(); if (!descriptor.IsSealed || !descriptor.IsPublic || constructors.Length != 1 || !constructors[0].IsPrivate - || descriptor.Fields.Count != 5 || descriptor.Fields.Any(field => !field.IsPrivate || !field.IsInitOnly || field.IsStatic) + || descriptor.Fields.Count != 6 || descriptor.Fields.Any(field => !field.IsPrivate || !field.IsInitOnly || field.IsStatic) || descriptor.Properties.Any(property => property.SetMethod is not null) || !Same(descriptor.Fields.Select(field => field.Name), ["_source", "_context", "_evidence", - "k__BackingField", "k__BackingField"])) + "k__BackingField", "k__BackingField", "k__BackingField"])) errors.Add("The immutable descriptor has only private closed construction and exact evidence fields"); - if (!Same(census.Types.Where(type => type.BaseType?.FullName == Minter).Select(type => type.FullName), [Seed, Delivery, Job])) - errors.Add("Only the three enumerated owners derive the finite descriptor source"); + if (!Same(census.Types.Where(type => type.BaseType?.FullName == Minter).Select(type => type.FullName), [Seed, Delivery, Job, Operator])) + errors.Add("Only the four enumerated owners derive the finite descriptor source"); foreach (var instruction in census.Methods.SelectMany(method => method.Body.Instructions)) if (instruction.Operand is MethodReference target && (target.DeclaringType.FullName == Descriptor && target.Name == ".ctor" || target.DeclaringType.FullName == Minter && target.Name == "ForOperation" || target.DeclaringType.FullName == Delivery && target.Name == "Enter" + || target.DeclaringType.FullName == Operator && target.Name == "Enter" || target.DeclaringType.FullName == Admission && target.Name == "CaptureOperationEvidence" || target.DeclaringType.FullName == "LearnStack.SharedKernel.Permissions.ITrustedOperationSource" && target.Name == "Capture") && instruction.OpCode.Code is not (Code.Call or Code.Callvirt or Code.Newobj)) @@ -93,7 +99,9 @@ private static List Offenders(Census census) Exact(Seed, ".ctor", ["LearnStack.Tools.Seeder.SeedComposition::Build"]); Exact(Delivery, ".ctor", []); Exact(Job, ".ctor", []); - Exact(Minter, "ForOperation", [Seed + "::Capture", Delivery + "::Capture", Job + "::Capture"]); + Exact(Operator, ".ctor", []); + Exact(Minter, "ForOperation", [Seed + "::Capture", Delivery + "::Capture", Job + "::Capture", Operator + "::Capture"]); + Exact(Operator, "Enter", [OperatorExecutor + "::ExecuteAsync"]); Exact(Delivery, "Enter", ["LearnStack.Infrastructure.Messaging.DeliveryExecutor::ExecuteOwnedAsync"]); Exact(Admission, "CaptureOperationEvidence", [Job + "::Capture"]); Exact(Admission, "IsOperationEvidenceCurrent", [Admission + "::CaptureOperationEvidence", Job + "::IsEvidenceCurrent"]); @@ -106,6 +114,8 @@ private static List Offenders(Census census) Require(Delivery, "IsEvidenceCurrent", "LearnStack.SharedKernel.Persistence.IUnitOfWork", "GetTenantContextAnnouncement"); Require(Admission, "IsOperationEvidenceCurrent", JobOwner, "get_IsCurrentBinding"); Require(Admission, "IsOperationEvidenceCurrent", Admission, "IsLive"); + Require(Operator, "IsEvidenceCurrent", "LearnStack.SharedKernel.Tenancy.ITenantContextAccessor", "get_Current"); + Require(Operator, "Capture", "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActCatalog", "TryGet"); if (Calls(census.Body(Admission, "CaptureOperationEvidence")).Any(target => target.DeclaringType.FullName == Admission && target.Name is "TryEnterRequest" or "PermitsRequest")) errors.Add("Capturing job evidence never repeats root or nested request admission"); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs index 0c460447..8974b83e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs @@ -54,6 +54,7 @@ private sealed class EntrySealProbe(MembershipWriteStore actual, IInvitationWrit public Task FindAsync(MembershipId id, CancellationToken cancellationToken = default) => actual.FindAsync(id, cancellationToken); public Task LockAsync(MembershipId id, CancellationToken cancellationToken = default) => actual.LockAsync(id, cancellationToken); public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => actual.HasMembershipHistoryAsync(cancellationToken); + public Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default) => actual.HasActiveTenantAdministratorAsync(cancellationToken); public Task AddAsync(Membership aggregate, CancellationToken cancellationToken = default) => actual.AddAsync(aggregate, cancellationToken); public Task UpdateAsync(Membership aggregate, CancellationToken cancellationToken = default) => actual.UpdateAsync(aggregate, cancellationToken); public async Task ValidateGraphAsync(CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index 871ee49d..e7d13f4f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -407,8 +407,8 @@ private static CanonicalFunction[] CompiledFunctions() : attributes.Contains("STABLE", StringComparison.Ordinal) ? "s" : "v", attributes.Contains("STRICT", StringComparison.Ordinal)); }).OrderBy(function => function.Name, StringComparer.Ordinal).ToArray(); - functions.Should().HaveCount(28, "the closed set includes three provider definers, one target transition guard and the federation connection guard"); - functions.Count(function => function.Definer).Should().Be(15); + functions.Should().HaveCount(29, "the closed set includes three provider definers, one target transition guard, the federation connection guard and the operator resolver"); + functions.Count(function => function.Definer).Should().Be(16); functions.Single(function => function.Name == "fn_tenancy_own_field_consent_scope").Signature .Should().Be("public.fn_tenancy_own_field_consent_scope(uuid,uuid,uuid,text,uuid,uuid,integer)", nameof(MembershipFieldConsentStorageTests.Definer_scope_is_subject_and_host_capped_with_a_closed_bounded_interface)); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs index ac5f8691..102fd8b2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -66,7 +66,7 @@ public async Task Applied_census_has_sixty_six_tables_and_exactly_fifteen_confin """, null); names.Should().Equal("fn_identity_admin_admission_state", "fn_identity_audit_creation_guard", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", "fn_identity_invitation_entry", "fn_identity_membership_admission_guard", - "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", "fn_identity_self_membership_scopes", "fn_identity_user_capacity_guard", "fn_identity_user_creation_audit_guard", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope"); (await ScalarAsync(owner, null, """ @@ -76,7 +76,7 @@ SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace AND r.rolname='learnstack_migration' AND NOT r.rolbypassrls AND 'search_path=pg_catalog'=ANY(p.proconfig) AND NOT EXISTS (SELECT 1 FROM aclexplode(p.proacl) acl WHERE acl.grantee=0) - """)).Should().Be(15); + """)).Should().Be(16); (await ScalarAsync(owner, null, """ SELECT count(*) FROM pg_class WHERE oid IN ('public.users'::regclass,'public.identity_authority'::regclass) AND relrowsecurity AND relforcerowsecurity diff --git a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs index 89aac9d3..a2aaf53b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs @@ -16,15 +16,15 @@ public sealed class InvitationSmtpStorageTests(InvitationSmtpStorageFixture fixt { "fn_identity_admin_admission_state", "fn_identity_audit_creation_guard", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", "fn_identity_invitation_entry", "fn_identity_membership_admission_guard", - "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", "fn_identity_self_membership_scopes", "fn_identity_user_capacity_guard", "fn_identity_user_creation_audit_guard", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", }; private static readonly string[] AppExecutableDefinerFunctions = new[] { "fn_identity_admin_admission_state", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", - "fn_identity_invitation_entry", "fn_identity_self_membership_scopes", "fn_invitation_smtp_claim_or_read", - "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", + "fn_identity_invitation_entry", "fn_identity_operator_resolve_user", "fn_identity_self_membership_scopes", + "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", }; [Fact] diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index a63cd991..f11a4e3f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -103,8 +103,8 @@ public async Task Reversible_chain_prefixes_reverse_to_empty_and_current_heads_r (await CountAsync(connection, AuditFunctionQuery)).Should().Be(2L); (await CountAsync(connection, EducationFunctionQuery)).Should().Be(3L); (await CountAsync(connection, InboxFunctionQuery)).Should().Be(1L); - (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(23L, - "current Identity also installs three provider definers, one target transition guard and the federation connection guard"); + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(24L, + "current Identity also installs three provider definers, one target transition guard, the federation connection guard and the operator subject resolver"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs new file mode 100644 index 00000000..d83abb2a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs @@ -0,0 +1,170 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The contract of fn_identity_operator_resolve_user against real PostgreSQL as the application role +/// (ADR-0102 § 5, Database Standards § Operator subject resolution). +/// +/// +/// The definer is the one place an operator act reads users, which a tenant announcement blanks for the +/// application role, so each refusal it promises is asserted here rather than left to the handler above it. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class OperatorSubjectResolverTests(PublicReadFixture parent) +{ + private const string Resolve = "SELECT public.fn_identity_operator_resolve_user(@authority, @key)"; + + [Fact] + public async Task An_Active_User_Is_Found_And_An_Unknown_Subject_Is_Not() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.ResolveAsync(proof.Subject)).Should().Be(proof.Person.Value); + (await proof.ResolveAsync("nobody-has-signed-in")).Should().BeNull(); + } + + [Fact] + public async Task A_User_Who_Is_No_Longer_Active_Is_Not_Found() + { + await using var proof = await Proof.CreateAsync(parent); + await proof.CloseUserAsync(); + + (await proof.ResolveAsync(proof.Subject)).Should().BeNull("the Active filter is part of the contract, not a courtesy"); + } + + [Fact] + public async Task The_Definer_Refuses_Every_Caller_And_Argument_It_Does_Not_Admit() + { + await using var proof = await Proof.CreateAsync(parent); + var key = proof.Key(proof.Subject); + + (await proof.RefusalAsync(authority: Guid.NewGuid(), key: key)).Should().Be("23514", "another authority"); + (await proof.RefusalAsync(key: key[..31])).Should().Be("23514", "a key that is not 32 bytes"); + (await proof.RefusalAsync(key: [])).Should().Be("23514", "an empty key"); + (await proof.RefusalAsync(key: key, announceTenant: false)).Should().Be("23514", "no tenant announcement"); + (await proof.RefusalAsync(key: key, readOnly: true)).Should().Be("23514", "a read-only transaction"); + (await proof.RefusalAsync(key: key, asOwner: true)).Should().Be("23514", "a session that is not the application role"); + (await proof.RefusalAsync(key: key)).Should().BeNull("the control: the same call, admitted"); + } + + private sealed class Proof : IAsyncDisposable + { + private readonly TenantAuthenticationIssuer _issuer; + private readonly IdentityPublicReadFixture _database; + + private Proof(TenantAuthenticationIssuer issuer, IdentityPublicReadFixture database, UserId person, string subject) + { + _issuer = issuer; + _database = database; + Person = person; + Subject = subject; + } + + internal UserId Person { get; } + + internal string Subject { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var issuer = await TenantAuthenticationIssuer.StartAsync(); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "resolver-person-" + person.Value.ToString("N"); + try + { + var database = await IdentityPublicReadFixture.CreateAsync( + parent, issuer.Issuer, new Dictionary { [person] = subject }); + return new Proof(issuer, database, person, subject); + } + catch + { + await issuer.DisposeAsync(); + throw; + } + } + + internal byte[] Key(string subject) => + IdentitySubjectKey.Compute(_database.Registration.AuthorityId, subject).ToByteArray(); + + /// One call as the application role under a tenant announcement, the way an act makes it. + internal async Task ResolveAsync(string subject) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, Guid.CreateVersion7()); + await using var command = Command(app, transaction, _database.Registration.AuthorityId.Value, Key(subject)); + return await command.ExecuteScalarAsync() is Guid found ? found : null; + } + + /// The SQLSTATE the definer raises for the call, or null when it answers. + internal async Task RefusalAsync( + Guid? authority = null, byte[]? key = null, bool announceTenant = true, bool readOnly = false, bool asOwner = false) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync( + asOwner ? _database.MigrationConnectionString : _database.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + if (readOnly) + { + await IdentityMembershipFixture.ExecuteAsync(connection, transaction, "SET TRANSACTION READ ONLY"); + } + + if (announceTenant) + { + await IdentityMembershipFixture.ScopeAsync(connection, transaction, Guid.CreateVersion7()); + } + + try + { + await using var command = Command( + connection, transaction, authority ?? _database.Registration.AuthorityId.Value, key ?? Key(Subject)); + await command.ExecuteScalarAsync(); + return null; + } + catch (PostgresException failure) + { + return failure.SqlState; + } + } + + /// + /// The fixture's one corruption: the user closed, with the immutability trigger and the insert check stepped + /// around exactly as the administration-eligibility cases do, and restored before the definer is called. + /// + internal async Task CloseUserAsync() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.MigrationConnectionString); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{Person.Value:D}'::uuid AND status='Closing' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='Closing' WHERE id='{Person.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + private static NpgsqlCommand Command(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid authority, byte[] key) + { + var command = new NpgsqlCommand(Resolve, connection, transaction); + command.Parameters.AddWithValue("authority", authority); + command.Parameters.AddWithValue("key", key); + return command; + } + + public async ValueTask DisposeAsync() + { + await _database.DisposeAsync(); + await _issuer.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs new file mode 100644 index 00000000..ced27268 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs @@ -0,0 +1,560 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Hosting; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The five operator onboarding acts through the actual Program, the operator bearer scheme and the +/// ordinary pipeline, against PostgreSQL as the application role (ADR-0102). +/// +/// +/// +/// Every state assertion reads as learnstack_app under the tenant's own announcement, so what is +/// observed is what row security shows that tenant. The only owner-credential reads are of +/// platform_host_to_tenant, which has no tenant to announce, and the fixture's one deliberate +/// corruption (an administrator revoked outside the last-admin guard so the recovery has something to +/// recover). +/// +/// +/// An act is a PUT on operator-supplied identifiers, so each case that proves an act also +/// sends it again: a reply lost on the wire must cost nothing and write nothing twice. +/// +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class PlatformOperatorOnboardingTests(PublicReadFixture parent) +{ + private const string Full = "operator-full"; + private const string TenantOnly = "operator-tenant-only"; + private const string BootstrapOnly = "operator-bootstrap-only"; + + [Fact] + public async Task An_Operator_Onboards_A_Tenant_Step_By_Step_And_Every_Act_Is_Audited_And_Repeatable() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var role = Ids.Next(); + var membership = Ids.Next(); + var slug = "onboard-" + Ids.Short(); + var host = slug + ".example.test"; + + // Provision, and send the same act again. + var provision = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization)); + await AssertOkAsync(provision); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + + // The first administrator needs the role and the person first; each refusal writes nothing. + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + (await proof.CountAsync(tenant, "roles")).Should().Be(1); + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, "nobody-has-signed-in")), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + (await proof.CountAsync(tenant, "membership_role_assignments")).Should().Be(1); + + // The host mapping, then again. + var mapped = await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}"""); + await AssertOkAsync(mapped); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}""")); + (await proof.HostMappingsAsync(host)).Should().Equal(tenant); + + // Who the business columns name, and what the audit rows say. + (await proof.ScalarAsync(tenant, "SELECT created_by FROM public.memberships")).Should().Be(UserId.SystemActor.Value); + (await proof.ScalarAsync(tenant, "SELECT user_id FROM public.memberships")).Should().Be(proof.Person.Value); + var audit = await proof.AuditAsync(tenant); + audit.Where(row => row.Outcome == "success").Select(row => row.Operation).Distinct().Should().BeEquivalentTo( + ["tenancy.tenant.create", "tenancy.organization.create", "identity.role.initialize", + "identity.membership.create_first_admin", "tenancy.hostmapping.write"]); + audit.Should().OnlyContain(row => row.ActorUserId == null, "an operator act names no tenant user; the operator is in metadata"); + audit.Where(row => row.Outcome == "failed").Select(row => row.Operation).Should().Equal( + ["identity.membership.create_first_admin", "identity.membership.create_first_admin"], + "the two refused first-administrator attempts are recorded as the failures they were, and nothing else failed"); + audit.Should().OnlyContain(row => row.Metadata.Contains(proof.Operator.Issuer, StringComparison.Ordinal), + "every row carries the admitted operator's issuer"); + audit.Should().OnlyContain(row => !row.Metadata.Contains(proof.PersonSubject, StringComparison.Ordinal) + && !row.Metadata.Contains(Full, StringComparison.Ordinal), "neither the person's subject nor the operator's raw subject is stored"); + audit.Should().OnlyContain(row => !row.Metadata.Contains("INC-77", StringComparison.Ordinal), "the ticket stays out of rows a tenant can read"); + audit.Select(row => row.Reason).Distinct().Should().BeEquivalentTo( + ["tenant_provision", "role_initialize", "first_admin_create", "host_map"]); + } + + [Fact] + public async Task A_Grant_Is_Evaluated_Per_Act_And_A_Refused_Act_Writes_Nothing() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "grants-" + Ids.Short(); + + // Holding the tenant grant is not holding the bootstrap grant, and the reverse. + (await proof.PutAsync(BootstrapOnly, $"/tenants/{tenant}", ProvisionBody(slug, organization))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + await AssertOkAsync(await proof.PutAsync(TenantOnly, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + + var role = Ids.Next(); + (await proof.PutAsync(TenantOnly, $"/tenants/{tenant}/roles/{role}", RoleBody())).StatusCode.Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync(TenantOnly, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync(TenantOnly, RecoveryPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync("somebody-without-a-grant", $"/tenants/{Ids.Next()}", ProvisionBody("x-" + Ids.Short(), Ids.Next()))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + + (await proof.CountAsync(tenant, "roles")).Should().Be(0, "a refused act reaches no handler"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + } + + [Fact] + public async Task An_Act_On_A_Tenant_That_Does_Not_Exist_Is_Not_Found_And_A_Taken_Name_Is_Refused() + { + await using var proof = await Proof.CreateAsync(parent); + var missing = Ids.Next(); + + (await proof.PutAsync(Full, $"/tenants/{missing}/host-mappings/missing.example.test", "{}")).StatusCode + .Should().Be(HttpStatusCode.NotFound); + (await proof.PutAsync(Full, $"/tenants/{missing}/roles/{Ids.Next()}", RoleBody())).StatusCode + .Should().Be(HttpStatusCode.NotFound); + (await proof.PutAsync(Full, FirstAdminPath(missing, Ids.Next()), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.NotFound); + + var first = Ids.Next(); + var slug = "taken-" + Ids.Short(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody(slug, Ids.Next()))); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{Ids.Next()}", ProvisionBody(slug, Ids.Next())), + HttpStatusCode.Conflict, "lockey_slug_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody("another-" + Ids.Short(), Ids.Next())), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + } + + [Fact] + public async Task Identifiers_That_Are_Not_UuidV7_Are_Refused_Before_Any_Write() + { + await using var proof = await Proof.CreateAsync(parent); + var v4 = Guid.NewGuid(); + var tenant = Ids.Next(); + + (await proof.PutAsync(Full, $"/tenants/{v4}", ProvisionBody("v4-" + Ids.Short(), Ids.Next()))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the tenant id is the act's identity and must be a UUIDv7"); + (await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("v4-" + Ids.Short(), v4))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "nor may the default organization's"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{v4}", RoleBody())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, FirstAdminPath(tenant, v4), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(v4, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, RecoveryPath(tenant, v4), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.CountAsync(Ids.Next(), "tenants")).Should().Be(0); + } + + [Fact] + public async Task A_Person_Whose_Binding_Is_No_Longer_Active_Cannot_Be_Named_An_Administrator() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var role = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("closing-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await proof.CloseUserAsync(proof.Person); + + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + } + + [Fact] + public async Task The_First_Administrator_Is_Refused_Once_A_Tenant_Has_Had_Any_Member() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, _) = await proof.OnboardAsync(Full); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, second)), + HttpStatusCode.Conflict, "lockey_tenant_has_memberships"); + // Nor may a Role template be created once a Membership exists. + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", RoleBody()), + HttpStatusCode.Conflict, "lockey_tenant_has_memberships"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + } + + [Fact] + public async Task A_Recovery_Is_Refused_While_An_Administrator_Is_Active_And_Succeeds_Once_None_Is() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, firstMembership) = await proof.OnboardAsync(Full); + var (secondUser, second) = await proof.AnotherPersonAsync(); + var replacement = Ids.Next(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second)), + HttpStatusCode.Conflict, "lockey_administrator_exists"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + + // The database never lets the last administrator be revoked, so the state a recovery exists for is + // reached only by an owner-level repair that steps outside the guard; the fixture does exactly that. + await proof.SuspendOutsideTheGuardAsync(tenant, firstMembership); + + await AssertOkAsync(await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second))); + await AssertOkAsync(await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second))); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(1); + (await proof.AuditAsync(tenant)).Should().Contain(row => + row.Operation == "identity.membership.recover_admin" && row.Reason == "admin_recover" && row.Outcome == "success"); + + // The act is repeatable but not additive: with an administrator active again a third person is refused. + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(role, (await proof.AnotherPersonAsync()).Subject)), + HttpStatusCode.Conflict, "lockey_administrator_exists"); + + // The last-administrator invariant is the database's and the recovery leaves it as it found it: the + // replacement, now the only administrator, cannot be revoked by the application role. + var revoke = () => proof.RevokeAsApplicationRoleAsync(tenant, replacement, secondUser); + (await revoke.Should().ThrowAsync()).Which.SqlState.Should().Be("P0303"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(1); + } + + [Fact] + public async Task A_Recovery_Names_An_Initialized_Administrator_Role_Of_The_Tenant_And_A_Person_Who_Has_Signed_In() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, _, firstMembership) = await proof.OnboardAsync(Full); + await proof.SuspendOutsideTheGuardAsync(tenant, firstMembership); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(Ids.Next(), second)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(Ids.Next(), "nobody-has-signed-in")), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(0); + } + + [Fact] + public async Task A_Recovery_Is_Refused_For_A_Role_That_Is_Not_An_Administrator_Role_Of_The_Tenant() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var adminRole = Ids.Next(); + var learnerRole = Ids.Next(); + var membership = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("roles-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{adminRole}", RoleBody())); + await AssertOkAsync(await proof.PutAsync( + Full, $"/tenants/{tenant}/roles/{learnerRole}", """{"builtInKey":"Learner","capabilityScope":"Tenant"}""")); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(adminRole, proof.PersonSubject))); + await proof.SuspendOutsideTheGuardAsync(tenant, membership); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(learnerRole, second)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(0); + } + + private static string ProvisionBody(string slug, Guid organization) => JsonSerializer.Serialize(new + { + slug, + displayName = "Onboarded " + slug, + defaultOrganization = new { id = organization, slug = "main", displayName = "Main" }, + ticket = "INC-77", + }); + + private static string RoleBody() => """{"builtInKey":"TenantAdmin","capabilityScope":"Tenant","ticket":"INC-77"}"""; + + private static string AdminBody(Guid role, string subject) => JsonSerializer.Serialize(new { roleId = role, providerSubject = subject, ticket = "INC-77" }); + + private static string FirstAdminPath(Guid tenant, Guid membership) => $"/tenants/{tenant}/first-administrator/{membership}"; + + private static string RecoveryPath(Guid tenant, Guid membership) => $"/tenants/{tenant}/administrator-recovery/{membership}"; + + private static async Task AssertOkAsync(HttpResponseMessage response) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, text); + using var document = JsonDocument.Parse(text); + document.RootElement.GetProperty("correlationId").GetString().Should().NotBeNullOrWhiteSpace(); + } + + private static async Task AssertRuleAsync(HttpResponseMessage response, HttpStatusCode status, string reason) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(status, text); + text.Should().Contain(reason); + } + + private static class Ids + { + internal static Guid Next() => Guid.CreateVersion7(); + + internal static string Short() => Guid.NewGuid().ToString("N")[..10]; + } + + private sealed record AuditRow(string Operation, string Outcome, Guid? ActorUserId, string? Reason, string Metadata); + + private sealed class Proof : IAsyncDisposable + { + private readonly HttpClient _client; + private readonly Dictionary _tokens = []; + + private Proof(TenantAuthenticationIssuer tenantIssuer, TenantAuthenticationIssuer @operator, + IdentityPublicReadFixture database, UserId person, string personSubject, HttpClient client) + { + TenantIssuer = tenantIssuer; + Operator = @operator; + Database = database; + Person = person; + PersonSubject = personSubject; + _client = client; + } + + internal TenantAuthenticationIssuer TenantIssuer { get; } + + internal TenantAuthenticationIssuer Operator { get; } + + internal IdentityPublicReadFixture Database { get; } + + internal UserId Person { get; } + + internal string PersonSubject { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var tenantIssuer = await TenantAuthenticationIssuer.StartAsync(); + var @operator = await TenantAuthenticationIssuer.StartAsync(); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "onboarding-person-" + person.Value.ToString("N"); + IdentityPublicReadFixture? database = null; + HttpClient? client = null; + try + { + database = await IdentityPublicReadFixture.CreateAsync( + parent, tenantIssuer.Issuer, new Dictionary { [person] = subject }); + client = database.ClientFor("localhost", configureHost: ConfigureOperator(@operator)); + return new Proof(tenantIssuer, @operator, database, person, subject, client); + } + catch + { + client?.Dispose(); + if (database is not null) await database.DisposeAsync(); + await @operator.DisposeAsync(); + await tenantIssuer.DisposeAsync(); + throw; + } + } + + private static Action ConfigureOperator(TenantAuthenticationIssuer @operator) => builder => + { + builder.UseSetting("PlatformOperator:Issuer", @operator.Issuer); + builder.UseSetting("PlatformOperator:AcceptedAcr:0", "mfa"); + builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); + var grants = new (string Subject, string[] Keys)[] + { + (Full, [PlatformPermissions.TenantWrite.Key, PlatformPermissions.TenantBootstrapWrite.Key]), + (TenantOnly, [PlatformPermissions.TenantWrite.Key]), + (BootstrapOnly, [PlatformPermissions.TenantBootstrapWrite.Key]), + }; + for (var index = 0; index < grants.Length; index++) + { + builder.UseSetting($"PlatformOperator:Grants:{index}:Subject", grants[index].Subject); + for (var key = 0; key < grants[index].Keys.Length; key++) + { + builder.UseSetting($"PlatformOperator:Grants:{index}:Permissions:{key}", grants[index].Keys[key]); + } + } + }; + + internal async Task PutAsync(string operatorSubject, string path, string json) + { + if (!_tokens.TryGetValue(operatorSubject, out var token)) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + token = Operator.Token(JsonSerializer.Serialize(new Dictionary + { + ["iss"] = Operator.Issuer, + ["sub"] = operatorSubject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + })); + _tokens[operatorSubject] = token; + } + + using var request = new HttpRequestMessage(HttpMethod.Put, "/api/platform/v1" + path) + { + Headers = { Authorization = new AuthenticationHeaderValue("Bearer", token) }, + Content = new StringContent(json, Encoding.UTF8, "application/json"), + }; + return await _client.SendAsync(request); + } + + /// A person who has signed in, so the first-sign-in bootstrap has bound them. + internal async Task<(UserId Person, string Subject)> AnotherPersonAsync() + { + var person = UserId.From(Guid.CreateVersion7()); + var subject = "onboarding-person-" + person.Value.ToString("N"); + await Database.AdoptAsync(person, subject); + return (person, subject); + } + + /// + /// A user closed, with the immutability trigger and the insert check stepped around exactly as the + /// administration-eligibility cases do, and restored before the next act runs. + /// + internal async Task CloseUserAsync(UserId user) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{user.Value:D}'::uuid AND status='Closing' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='Closing' WHERE id='{user.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + /// The whole onboarding through the real routes; returns the tenant, its role and its first membership. + internal async Task<(Guid Tenant, Guid Role, Guid Membership)> OnboardAsync(string operatorSubject) + { + var tenant = Ids.Next(); + var role = Ids.Next(); + var membership = Ids.Next(); + await AssertOkAsync(await PutAsync(operatorSubject, $"/tenants/{tenant}", ProvisionBody("full-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await PutAsync(operatorSubject, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await AssertOkAsync(await PutAsync(operatorSubject, FirstAdminPath(tenant, membership), AdminBody(role, PersonSubject))); + return (tenant, role, membership); + } + + internal Task CountAsync(Guid tenant, string table) => + ScalarAsync(tenant, $"SELECT count(*) FROM public.{table}"); + + internal async Task ScalarAsync(Guid tenant, string sql) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand(sql, app, transaction); + return (T)(await command.ExecuteScalarAsync())!; + } + + internal async Task> AuditAsync(Guid tenant) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand( + "SELECT operation,outcome,actor_user_id,reason,metadata::text FROM public.audit_log ORDER BY timestamp", app, transaction); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new( + reader.GetString(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + reader.IsDBNull(3) ? null : reader.GetString(3), reader.GetString(4))); + } + + return rows; + } + + /// + /// What the resolver itself would read for the host: the application role, announcing only the host + /// it is resolving, which is the one thing row security lets it see of the host index. + /// + internal async Task> HostMappingsAsync(string host) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync( + app, transaction, "SELECT set_config('app.resolving_host', @host, true)", ("host", host)); + await using var command = new NpgsqlCommand( + "SELECT tenant_id FROM public.platform_host_to_tenant WHERE host=@host", app, transaction); + command.Parameters.AddWithValue("host", host); + await using var reader = await command.ExecuteReaderAsync(); + var tenants = new List(); + while (await reader.ReadAsync()) + { + tenants.Add(reader.GetGuid(0)); + } + + return tenants; + } + + /// + /// The fixture's one deliberate corruption: the only administrator suspended with the deferred + /// last-administrator guard stepped around, which is the state a recovery exists for. + /// + /// + /// The owner is subject to forced row security, so it announces the tenant like any other connection and + /// takes the same locks; what it skips is the commit-time guard that refuses a tenant with no administrator. + /// + internal async Task SuspendOutsideTheGuardAsync(Guid tenant, Guid membership) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(owner, transaction, tenant); + await IdentityMembershipFixture.LockAsync(owner, transaction, tenant, Person.Value, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, "ALTER TABLE public.memberships DISABLE TRIGGER tg_memberships_complete_graph"); + await IdentityMembershipFixture.ExecuteAsync( + owner, transaction, "UPDATE public.memberships SET status='Suspended' WHERE id=@membership", ("membership", membership)); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, "ALTER TABLE public.memberships ENABLE TRIGGER tg_memberships_complete_graph"); + await transaction.CommitAsync(); + } + + /// An ordinary revocation by the application role, under the locks a handler would take. + internal async Task RevokeAsApplicationRoleAsync(Guid tenant, Guid membership, UserId user) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await IdentityMembershipFixture.LockAsync(app, transaction, tenant, user.Value, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@actor WHERE id=@membership + """, ("actor", UserId.SystemActor.Value), ("membership", membership)); + await transaction.CommitAsync(); + } + + public async ValueTask DisposeAsync() + { + _client.Dispose(); + await Database.DisposeAsync(); + await Operator.DisposeAsync(); + await TenantIssuer.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs similarity index 98% rename from backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs rename to backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs index dbf8657a..d3e16509 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/KillswitchToggleOrderingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs @@ -11,7 +11,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Xunit; -namespace LearnStack.Tests.Integration.Database; +namespace LearnStack.Tests.Integration; /// /// The order of the killswitch writer's steps and the failure branches around its commit, decided @@ -19,7 +19,7 @@ namespace LearnStack.Tests.Integration.Database; /// /// /// No Docker. The real-database behaviour (row lock, both audit rows, rollback) is asserted in -/// ; what a stub can show and a database cannot is the writer's +/// ; what a stub can show and a database cannot is the writer's /// reaction to a commit whose outcome is unknown. /// public sealed class KillswitchToggleOrderingTests diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index dfe2e3e7..b82c7bef 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -432,7 +432,11 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum var operatorDocument = await _client.GetStringAsync("/openapi/platform-v1.json"); var tenantDocument = await _client.GetStringAsync("/openapi/v1.json"); - operatorDocument.Should().Contain("/api/platform/v1/killswitches/{key}"); + foreach (var route in OperatorRoutes) + { + operatorDocument.Should().Contain(route, "the contract is the only client the operator surface has"); + } + tenantDocument.Should().NotContain("/api/platform", "the tenant contract is pinned and untouched (ADR-0101 § 4)"); // What a client author needs: a title, no Host-derived servers, the bearer scheme and its token @@ -454,8 +458,33 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum .Should().BeTrue(); put.GetProperty("responses").GetProperty("503").GetProperty("headers").TryGetProperty("Retry-After", out _) .Should().BeTrue(); + put.GetProperty("responses").TryGetProperty("409", out _).Should().BeFalse("a switch toggle never answers a refused state"); + + // Every onboarding act is a PUT with its own body, the same status set, and a 409 for the state it refuses. + foreach (var route in OperatorRoutes.Where(route => !route.Contains("killswitches", StringComparison.Ordinal))) + { + var act = root.GetProperty("paths").GetProperty(route).GetProperty("put"); + act.GetProperty("security").GetArrayLength().Should().Be(1, route); + act.GetProperty("requestBody").GetProperty("content").GetProperty("application/json") + .GetProperty("schema").ValueKind.Should().NotBe(JsonValueKind.Undefined, route); + act.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "404", "409", "415", "500", "503"], route); + } + + root.GetProperty("paths").EnumerateObject().Select(path => path.Name).Should().BeEquivalentTo(OperatorRoutes, + "a route that is not in the closed list is an operator act nobody reviewed"); } + private static readonly string[] OperatorRoutes = + [ + "/api/platform/v1/killswitches/{key}", + "/api/platform/v1/tenants/{tenantId}", + "/api/platform/v1/tenants/{tenantId}/host-mappings/{host}", + "/api/platform/v1/tenants/{tenantId}/roles/{roleId}", + "/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}", + "/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}", + ]; + [Fact] public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() { @@ -489,7 +518,7 @@ public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_S } [Fact] - public void The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_Its_Prefix() + public void The_Operator_Surface_Is_Exactly_The_Six_Authorized_Put_Endpoints_Under_Its_Prefix() { // The tenant surface census excludes this surface by exact type (it has its own scheme), so // its population is closed here instead: every routed endpoint under /api/platform (whatever @@ -503,13 +532,19 @@ public void The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_It ?.Kind == InfrastructureOperationKind.PlatformOperator) .ToList(); - var only = endpoints.Should().ContainSingle().Subject; - only.RoutePattern.RawText.Should().Be("/api/platform/v1/killswitches/{key}"); - only.Metadata.GetMetadata()!.HttpMethods.Should().Equal("PUT"); - only.Metadata.GetOrderedMetadata() - .Select(data => data.Policy).Should().Contain(PlatformOperatorAuthentication.PolicyName, - "an operator endpoint without the authenticated-operator policy would admit an anonymous caller"); - only.Metadata.GetMetadata().Should().BeNull(); + endpoints.Select(endpoint => endpoint.RoutePattern.RawText).Should().BeEquivalentTo( + OperatorRoutes.Select(route => route.Replace("{tenantId}", "{tenantId:guid}").Replace("{roleId}", "{roleId:guid}") + .Replace("{membershipId}", "{membershipId:guid}")), + "the operator population is closed: a new route is a reviewed act with its own policy, grant and audit slug"); + foreach (var endpoint in endpoints) + { + var route = endpoint.RoutePattern.RawText; + endpoint.Metadata.GetMetadata()!.HttpMethods.Should().Equal(["PUT"], route); + endpoint.Metadata.GetOrderedMetadata() + .Select(data => data.Policy).Should().Contain(PlatformOperatorAuthentication.PolicyName, + "an operator endpoint without the authenticated-operator policy would admit an anonymous caller: " + route); + endpoint.Metadata.GetMetadata().Should().BeNull(route); + } } private string Header(string alg, string typ) => JsonSerializer.Serialize(new { alg, typ, kid = _operator.CurrentKey.Kid }); diff --git a/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs b/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs index bd2a6f87..69da411e 100644 --- a/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs @@ -3,6 +3,7 @@ using LearnStack.Application.Authorization; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Localization; using LearnStack.Application.Pipeline; @@ -46,6 +47,34 @@ public async Task Canonical_slot_five_refuses_an_unclassified_request_before_its scope.ServiceProvider.GetRequiredService().HasActiveTransaction.Should().BeFalse(); } + [Fact] + public async Task The_seed_source_does_not_admit_an_operator_act_before_its_handler() + { + // ADR-0102 § 1: neither source is sufficient for the other's request. The seed composition mints no + // operator descriptor, so an operator command sent through it is refused by the policy it names + // before any handler, transaction or database connection. + await using var data = Source(); + await using var provider = SeedComposition.Build(data, + new SeedTenantContext(TenantId.From(Guid.CreateVersion7()), null), NullLoggerFactory.Instance); + await using var scope = provider.CreateAsyncScope(); + var behavior = scope.ServiceProvider + .GetServices>>() + .OfType>>().Single(); + var entered = false; + var command = new OperatorProvisionTenantCommand( + TenantId.From(Guid.CreateVersion7()), "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + var result = await behavior.Handle(command, () => + { + entered = true; + return Task.FromResult(Result.Fail(new Error(new LocalizedMessage("lockey_forbidden")))); + }, CancellationToken.None); + + result.Error!.Code.Should().Be("forbidden"); + entered.Should().BeFalse("a seed descriptor, or none, is not an operator act"); + scope.ServiceProvider.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + } + [Fact] public async Task An_attributable_finite_seed_refusal_cannot_claim_durability_without_a_shared_evidence_factory() { diff --git a/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs b/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs new file mode 100644 index 00000000..cf4ce33f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs @@ -0,0 +1,86 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Tools.Seeder; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The seeder is a development capability (ADR-0102 § 10): started anywhere but a Development +/// deployment it refuses before it reads a credential or opens a connection. +/// +/// +/// No Docker and no database: the process is given no connection string at all, so a run that did anything +/// but refuse would exit with the missing-credential code instead. +/// +public sealed class SeederDevelopmentOnlyTests +{ + [Theory] + [InlineData("Production")] + [InlineData("Dedicated")] + [InlineData("SelfHosted")] + [InlineData("development")] + [InlineData("")] + [InlineData(null)] + public async Task The_Seeder_Refuses_Outside_A_Development_Deployment_Before_Reading_A_Credential(string? mode) + { + var (exit, errors) = await RunAsync(mode); + + exit.Should().Be(2); + errors.Should().Contain("only when Deployment__Mode is Development").And.Contain("operator surface"); + } + + [Fact] + public async Task In_A_Development_Deployment_The_Refusal_Is_Not_The_Answer() + { + // With the mode right and no credential the seeder reaches its own missing-credential exit, which is + // how this case shows the refusal is the mode's and not a blanket one. + var (exit, errors) = await RunAsync("Development"); + + exit.Should().Be(2); + errors.Should().NotContain("only when Deployment__Mode is Development"); + errors.Should().Contain("ConnectionStrings__Default"); + } + + private static async Task<(int Exit, string Errors)> RunAsync(string? mode) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = AppContext.BaseDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.deps.json")); + start.ArgumentList.Add(typeof(SeedRunner).Assembly.Location); + start.Environment.Remove("ConnectionStrings__Default"); + start.Environment.Remove("Deployment__Mode"); + if (mode is not null) + { + start.Environment["Deployment__Mode"] = mode; + } + + using var process = new Process { StartInfo = start }; + process.Start().Should().BeTrue(); + var output = process.StandardOutput.ReadToEndAsync(); + var errors = process.StandardError.ReadToEndAsync(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + try + { + await process.WaitForExitAsync(deadline.Token); + } + finally + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + } + + await Task.WhenAll(output, errors); + return (process.ExitCode, await errors); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs index ac37d1db..a3747579 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs @@ -322,16 +322,9 @@ internal async Task WriteReconciliationInputAsync(Stream destination, string sce await JsonSerializer.SerializeAsync(destination, input, JsonSerializerOptions.Web, cancellationToken); } - internal static string RealmPath(string realm) => Path.Combine(RepositoryRoot(), "infra", "keycloak", "realms", realm + ".json"); + internal static string RealmPath(string realm) => RealmFiles.RealmPath(realm); - internal static string RepositoryRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !(File.Exists(Path.Combine(directory.FullName, "CLAUDE.md")) - && Directory.Exists(Path.Combine(directory.FullName, "infra", "keycloak", "realms")))) - directory = directory.Parent; - return directory?.FullName ?? throw new InvalidOperationException("Keycloak fixture repository root is missing."); - } + internal static string RepositoryRoot() => RealmFiles.RepositoryRoot(); public async Task DisposeAsync() { diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs index b3463107..8cab58ed 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs @@ -14,7 +14,7 @@ namespace LearnStack.Tests.Integration.TenancyIdentity; public sealed class PlatformOperatorRealmFileTests { private static JsonObject Realm() => - JsonNode.Parse(File.ReadAllText(KeycloakFixture.RealmPath("learnstack-hub")))!.AsObject(); + JsonNode.Parse(File.ReadAllText(RealmFiles.RealmPath("learnstack-hub")))!.AsObject(); [Fact] public void Password_Reset_Is_Off_So_No_Second_Path_To_A_Password_Skips_The_Second_Factor() => diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs new file mode 100644 index 00000000..4826e490 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs @@ -0,0 +1,22 @@ +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// Where the shipped realm exports live, for the cases that read the files and start no Keycloak. +/// +/// +/// Kept apart from the Keycloak fixture on purpose: a case that only parses a file is not a Docker case, +/// and naming the fixture would route it to the job that has a Docker socket. +/// +internal static class RealmFiles +{ + internal static string RealmPath(string realm) => Path.Combine(RepositoryRoot(), "infra", "keycloak", "realms", realm + ".json"); + + internal static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !(File.Exists(Path.Combine(directory.FullName, "CLAUDE.md")) + && Directory.Exists(Path.Combine(directory.FullName, "infra", "keycloak", "realms")))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("The repository root is missing."); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs index 6f7bdc55..920971a8 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs @@ -36,7 +36,7 @@ public void Real_sources_cover_every_actual_request_once_without_implicit_grants && type.GetInterfaces().Any(contract => contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IRequest<>))) .OrderBy(type => type.FullName, StringComparer.Ordinal).ToArray(); Assert.Equal(actual, catalog.All.Select(policy => policy.RequestType)); - Assert.Equal(131, actual.Length); + Assert.Equal(136, actual.Length); Assert.Equal(5, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.PublicRead)); Assert.Single(catalog.All, policy => policy.Kind == OperationPolicyKind.AccountRead); Assert.Equal(61, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.Protected)); @@ -64,7 +64,7 @@ public void Real_sources_cover_every_actual_request_once_without_implicit_grants Assert.Equal(new[] { typeof(WithdrawOwnMembershipFieldConsentCommand), typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), typeof(ListOwnFieldConsentScopesQuery), typeof(ListOwnMembershipFieldConsentsQuery) } .OrderBy(type => type.FullName, StringComparer.Ordinal), catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnConsentEntry).Select(policy => policy.RequestType)); - Assert.Equal(46, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.FiniteTrusted)); + Assert.Equal(51, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.FiniteTrusted)); var admission = Assert.Single(catalog.All, policy => policy.Kind == OperationPolicyKind.NativeSessionAdmission); Assert.Equal(typeof(AdmitNativeSessionScopeCommand), admission.RequestType); Assert.Null(admission.RequiredPermission); @@ -106,6 +106,48 @@ public void Conflicting_or_unregistered_metadata_never_freezes_as_authority(stri Assert.Throws(() => new OperationPolicyCatalog([source])); } + [Fact] + public void Operator_acts_accept_only_the_operator_source_and_seed_acts_never_accept_it() + { + // ADR-0102 § 1: neither source is sufficient for the other's request. The operator source is the + // single allowed source of each operator command, and no other policy in the catalogue lists it. + var catalog = ProductionCatalog(); + Type[] operatorActs = + [ + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.OperatorProvisionTenantCommand), + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.OperatorMapHostCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorInitializeRoleCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorCreateFirstAdminCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorRecoverAdminCommand), + ]; + + foreach (var act in operatorActs) + { + Assert.True(catalog.TryGet(act, out var policy), act.Name); + Assert.Equal(OperationPolicyKind.FiniteTrusted, policy.Kind); + Assert.Equal(AuthorizationSourceKind.PlatformOperator, Assert.Single(policy.AllowedSources)); + } + + var withOperatorSource = catalog.All + .Where(policy => policy.AllowedSources.Contains(AuthorizationSourceKind.PlatformOperator)) + .Select(policy => policy.RequestType) + .ToArray(); + Assert.Equal(operatorActs.OrderBy(type => type.FullName, StringComparer.Ordinal), withOperatorSource); + + Type[] seedCounterparts = + [ + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.ProvisionTenantCommand), + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.MapHostToTenantCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.Seeding.InitializeSeedRoleCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.Seeding.CreateFirstSeedAdminMembershipCommand), + ]; + foreach (var seed in seedCounterparts) + { + Assert.True(catalog.TryGet(seed, out var policy), seed.Name); + Assert.DoesNotContain(AuthorizationSourceKind.PlatformOperator, policy.AllowedSources); + } + } + [Fact] public void Inactive_definitions_remain_registered_without_acquiring_grants() { diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs new file mode 100644 index 00000000..db2a2f7c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs @@ -0,0 +1,335 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Application.Audit; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Tenancy.Application.Authorization; +using LearnStack.Modules.Tenancy.Application.Contracts.Seeding; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Application.Authorization; + +/// +/// The handler-side check of an operator act (ADR-0102 § 1, § 7): it admits the live act of the +/// right source in the right context and transaction, and refuses everything else before a lock is +/// taken or a row is written. +/// +/// +/// The guard is driven through the real authorization coordinator, so the invocation it reads is the +/// one the pipeline would have built. Only the source is a double: it mints the operator descriptor +/// the executor's source mints, and, for the cross-source case, a seed descriptor. +/// +public sealed class OperatorActGuardTests +{ + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly DateTimeOffset Now = new(2026, 11, 19, 12, 0, 0, TimeSpan.Zero); + + private static OperatorProvisionTenantCommand Request() => new( + Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + private static IdentityMutationLockPlan Plan() => new([], Tenant, IdentityTenantLockMode.Exclusive); + + [Fact] + public async Task The_Live_Act_In_Its_Own_Context_Is_Admitted_And_Holds_Its_Locks() + { + using var rig = new Rig(); + var request = Request(); + + var result = await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsSuccess.Should().BeTrue(); + rig.Guard.RequireCurrent(admission.Value!).IsSuccess.Should().BeTrue(); + admission.Value!.TenantId.Should().Be(Tenant); + return Result.Ok(None.Value); + }); + + result.IsSuccess.Should().BeTrue(); + await rig.Locks.Received(1).AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Call_Outside_Any_Invocation_Is_Refused_Before_A_Lock() + { + using var rig = new Rig(); + + var result = await rig.Guard.AdmitAsync(Request(), Plan(), default); + + result.IsFailure.Should().BeTrue(); + result.Error!.Code.Should().Be("forbidden"); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Request_That_Is_Not_The_Invocations_Own_Object_Is_Refused() + { + using var rig = new Rig(); + + await rig.ExpectRefusalAsync(Request(), () => Request()); + } + + [Fact] + public async Task A_Seed_Source_Is_Not_Sufficient_For_An_Operator_Guard() + { + using var rig = new Rig(); + var seed = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + rig.SourceKind = AuthorizationSourceKind.Seed; + + var result = await rig.RunAsync(seed, async () => + { + var admission = await rig.Guard.AdmitAsync(seed, Plan(), default); + admission.IsFailure.Should().BeTrue("the guard names the operator source alone"); + admission.Error!.Code.Should().Be("forbidden"); + return Result.Ok(None.Value); + }); + + result.IsSuccess.Should().BeTrue(); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Revoked_Source_Admits_Nothing() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + rig.Source.Dispose(); + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsFailure.Should().BeTrue(); + return Result.Ok(None.Value); + }); + + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("user")] + [InlineData("organization")] + [InlineData("host")] + [InlineData("unresolved")] + [InlineData("other_tenant")] + public async Task A_Context_That_Is_Not_The_Tenants_Ambient_One_Is_Refused(string change) + { + // Applied before the invocation starts, so the invocation's own drift check has nothing to catch and + // the guard's restatement of the context is the only thing that can refuse. + using var rig = new Rig(); + var request = Request(); + Apply(rig, change); + + await rig.ExpectRefusalAsync(request, () => request); + } + + private static void Apply(Rig rig, string change) + { + switch (change) + { + case "user": rig.Context.UserId.Returns(UserId.SystemActor); break; + case "organization": rig.Context.OrganizationId.Returns(OrganizationId.From(Guid.CreateVersion7())); break; + case "host": + rig.Context.HostScope.Returns(TenantContextFactory.Create( + new TenantResolutionAttempt { HostTenantId = Tenant }).Value!.HostScope); + break; + case "unresolved": rig.Context.IsResolved.Returns(false); break; + default: rig.Context.TenantId.Returns(TenantId.From(Guid.CreateVersion7())); break; + } + } + + [Theory] + [InlineData("no_transaction")] + [InlineData("read_only")] + [InlineData("rollback_only")] + [InlineData("announced_elsewhere")] + [InlineData("not_announced")] + [InlineData("global_identity")] + public async Task A_Transaction_That_Is_Not_The_Ordinary_Announced_Owner_Is_Refused(string change) + { + using var rig = new Rig(); + var request = Request(); + + await rig.ExpectRefusalAsync(request, () => + { + switch (change) + { + case "no_transaction": rig.Unit.HasActiveTransaction.Returns(false); break; + case "read_only": rig.Unit.Mode.Returns(TransactionMode.ReadOnly); break; + case "rollback_only": rig.Unit.IsRollbackOnly.Returns(true); break; + case "announced_elsewhere": + rig.Unit.GetTenantContextAnnouncement(Arg.Any()) + .Returns(new TenantContextAnnouncement(1, TenantId.From(Guid.CreateVersion7()), null)); + break; + case "not_announced": rig.Unit.GetTenantContextAnnouncement(Arg.Any()).Returns((TenantContextAnnouncement?)null); break; + default: rig.GlobalUnit.IsGlobalIdentityTransaction.Returns(true); break; + } + + return request; + }); + } + + [Fact] + public async Task A_Lock_That_Cannot_Be_Taken_Is_Unavailable_And_Rolls_The_Act_Back() + { + using var rig = new Rig(); + var request = Request(); + rig.Locks.AcquireAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new IdentityMutationLockException())); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsFailure.Should().BeTrue(); + admission.Error!.Code.Should().Be("dependency_unavailable"); + return Result.Ok(None.Value); + }); + + rig.Unit.Received(1).MarkRollbackOnly(); + } + + [Fact] + public async Task A_Lock_That_Was_Lost_Before_A_Write_Refuses_The_Write_And_Rolls_The_Act_Back() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsSuccess.Should().BeTrue(); + rig.Locks.When(value => value.RequireCurrent(Arg.Any())) + .Do(_ => throw new IdentityMutationLockException()); + + var current = rig.Guard.RequireCurrent(admission.Value!); + + current.IsFailure.Should().BeTrue(); + current.Error!.Code.Should().Be("dependency_unavailable"); + return Result.Ok(None.Value); + }); + + rig.Unit.Received(1).MarkRollbackOnly(); + } + + [Fact] + public async Task A_Plan_For_Another_Tenant_Is_Not_Held_For_This_Act() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync( + request, new IdentityMutationLockPlan([], TenantId.From(Guid.CreateVersion7()), IdentityTenantLockMode.Exclusive), default); + admission.IsFailure.Should().BeTrue("the act may lock only the tenant its context carries"); + return Result.Ok(None.Value); + }); + + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + private sealed class Rig : IDisposable + { + private readonly OperationAuthorizationCoordinator _coordinator; + private IdentityMutationLockPlan? _held; + + public Rig() + { + Context.IsResolved.Returns(true); + Context.TenantId.Returns(Tenant); + Context.Origin.Returns(TenantContextOrigin.Ambient); + var transaction = Substitute.For(); + Unit.HasActiveTransaction.Returns(true); + Unit.Mode.Returns(TransactionMode.ReadWrite); + Unit.Transaction.Returns(transaction); + Unit.GetTenantContextAnnouncement(Arg.Any()).Returns(new TenantContextAnnouncement(1, Tenant, null)); + Locks.AcquireAsync(Arg.Any(), Arg.Any()).Returns(call => + { + _held = call.Arg(); + return Task.CompletedTask; + }); + Locks.When(value => value.RequireCurrent(Arg.Any())).Do(call => + { + if (!ReferenceEquals(_held, call.Arg())) throw new IdentityMutationLockException(); + }); + + Source = new OperatorSource(this); + var clock = Substitute.For(); + clock.UtcNow.Returns(Now); + OperationAuthorizationCoordinator? current = null; + var evidence = new AuthorizationEvidenceCoordinator( + Substitute.For(), new AuditStateCapture(), Unit, clock, new SystemGuidFactory(), + () => current!, [], NullLogger.Instance); + _coordinator = current = new OperationAuthorizationCoordinator( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()]), + Substitute.For(), Context, [], [Source], evidence); + Guard = new OperatorActGuard(_coordinator, Context, Unit, Locks); + } + + public ITenantContext Context { get; } = Substitute.For(); + + public IGlobalIdentityUnitOfWork GlobalUnit { get; } = Substitute.For(); + + public IUnitOfWork Unit => GlobalUnit; + + public IIdentityMutationLocks Locks { get; } = Substitute.For(); + + public OperatorActGuard Guard { get; } + + public OperatorSource Source { get; } + + public AuthorizationSourceKind SourceKind { get; set; } = AuthorizationSourceKind.PlatformOperator; + + public Task> RunAsync(TRequest request, Func>> body) where TRequest : notnull => + _coordinator.ExecuteRequestAsync>(request, body); + + /// Runs the guard after altered the world, and expects a refusal and no lock. + public async Task ExpectRefusalAsync(TRequest request, Func change) where TRequest : notnull + { + var refused = false; + await RunAsync(request, async () => + { + var asked = change(); + var admission = await Guard.AdmitAsync(asked, Plan(), default); + refused = admission.IsFailure && admission.Error!.Code == "forbidden"; + return Result.Ok(None.Value); + }); + + refused.Should().BeTrue(); + await Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + public void Dispose() => _coordinator.Dispose(); + } + + private sealed class OperatorSource(Rig rig) : TrustedOperationDescriptor.MintingSource, ITrustedOperationSource + { + public TrustedOperationDescriptor? Capture(Type requestType, ITenantContext context) + { + if (!CanIssue) + { + return null; + } + + return rig.SourceKind == AuthorizationSourceKind.PlatformOperator + ? ForOperation( + AuthorizationSourceKind.PlatformOperator, requestType, context, null, + PlatformOperatorAttribution.From(TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now))) + : ForOperation(AuthorizationSourceKind.Seed, requestType, context); + } + + protected override bool IsEvidenceCurrent(object? evidence) => true; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index e1924019..5b22d3b5 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -292,7 +292,10 @@ public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() entry.OperationType.Should().Be(OperationType.SecurityEvent); entry.ModuleName.Should().Be("platform", "the scope belongs to no module's request path"); - foreach (var operation in PlatformOperations.All) + // Only the operations that enter the platform scope write their result row off-path; the + // onboarding acts run through the pipeline, whose request-keyed catalogue the audit-coverage + // rules join to the matrices. + foreach (var operation in PlatformOperations.All.Where(operation => operation.NeedsPlatformRole)) { catalogue.TryGetOffPath(operation.AuditSlug, out var declared) .Should().BeTrue($"'{operation.AuditSlug}' must be declared so its result row can be recorded"); @@ -317,7 +320,7 @@ public void The_Registry_Is_Closed_And_Every_Operation_Names_A_Registered_Platfo public void The_Grant_Validator_Refuses_Unregistered_Keys_And_The_Demo_Operator_Outside_Development() { var options = new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }; - options.Grants.Add(new PlatformOperatorGrant { Subject = "operator-1", Permissions = { "platform.tenant.write" } }); + options.Grants.Add(new PlatformOperatorGrant { Subject = "operator-1", Permissions = { "platform.never.write" } }); new PlatformOperatorGrantOptionsValidator(DeploymentMode.Development).Validate(null, options).Failed.Should().BeTrue( "a key no operation has registered is not a grant"); diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs new file mode 100644 index 00000000..e9e5ecb3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs @@ -0,0 +1,269 @@ +using FluentAssertions; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Tenancy.Application.Authorization; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.MultiTenancy; + +/// +/// What the operator act executor and its source decide before a handler runs (ADR-0102 § 1): which +/// requests and admissions it accepts, what context and provenance the act runs under, and that +/// both are gone when the act is. +/// +/// +/// No database and no pipeline: the sender is a double that observes the ambient context and asks the +/// scoped source for a descriptor while the act is in flight, which is the one moment the pair is +/// allowed to answer. +/// +public sealed class PlatformOperatorActExecutorTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 19, 12, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + + private static OperatorProvisionTenantCommand Provision(TenantId? tenant = null) => new( + tenant ?? Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + [Fact] + public async Task An_Admitted_Act_Runs_On_A_Resolved_Ambient_Context_Of_The_Tenant_It_Names_And_Nothing_Else() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + + var result = await rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + result.IsSuccess.Should().BeTrue(); + var seen = rig.Observed.Should().ContainSingle().Subject; + seen.Context.IsResolved.Should().BeTrue(); + seen.Context.TenantId.Should().Be(Tenant); + seen.Context.Origin.Should().Be(TenantContextOrigin.Ambient); + seen.Context.UserId.Should().BeNull("an operator act names no user; the business actor is the registry actor"); + seen.Context.OrganizationId.Should().BeNull(); + seen.Context.HostScope.Should().BeNull(); + seen.Descriptor.Should().NotBeNull(); + seen.Descriptor!.SourceKind.Should().Be(AuthorizationSourceKind.PlatformOperator); + seen.Descriptor.RequestType.Should().Be(typeof(OperatorProvisionTenantCommand)); + seen.Descriptor.Operator!.ReasonSlug.Should().Be("tenant_provision"); + seen.Descriptor.Operator.Issuer.Should().Be(TestPlatformAdmissions.Issuer); + seen.MatchedWhileLive.Should().BeTrue("the descriptor answers for its request in its context while the act is in flight"); + } + + [Fact] + public async Task The_Context_And_The_Provenance_Are_Gone_When_The_Act_Is() + { + await using var rig = new Rig(); + var before = Substitute.For(); + rig.Accessor.Current = before; + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + rig.Accessor.Current.Should().BeSameAs(before, "the executor restores what it found, it does not clear it"); + var seen = rig.Observed.Single(); + seen.Descriptor!.IsActive.Should().BeFalse("a descriptor kept past its act proves nothing"); + seen.Descriptor.Matches(typeof(OperatorProvisionTenantCommand), seen.Context).Should().BeFalse(); + seen.Source.Capture(typeof(OperatorProvisionTenantCommand), seen.Context).Should().BeNull( + "the frame is closed, so the same source in the same context answers nothing after the act"); + } + + [Fact] + public async Task A_Failing_Act_Still_Restores_The_Context_And_Closes_The_Provenance() + { + await using var rig = new Rig { Failure = new InvalidOperationException("handler failed") }; + + var act = () => rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + await act.Should().ThrowAsync().WithMessage("handler failed"); + rig.Accessor.Current.Should().BeNull(); + rig.Observed.Single().Descriptor!.IsActive.Should().BeFalse(); + } + + [Fact] + public async Task The_Source_Answers_Only_For_The_Operation_The_Admission_Is_For_And_Only_In_Its_Own_Context() + { + await using var rig = new Rig(); + rig.Probe = (provider, context) => + [ + provider.Capture(typeof(OperatorProvisionTenantCommand), context), + provider.Capture(typeof(OperatorMapHostCommand), context), + provider.Capture(typeof(ProvisionTenantCommand), context), + provider.Capture(typeof(OperatorProvisionTenantCommand), Substitute.For()), + provider.Capture(typeof(MapHostToTenantCommand), context), + ]; + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + var answers = rig.Observed.Single().Probed; + answers[0].Should().NotBeNull("the admitted operation's own request in the context the executor installed"); + answers[1].Should().BeNull("a host mapping is another operation: one admission, one act"); + answers[2].Should().BeNull("the seed command is not an operator act, whatever the context"); + answers[3].Should().BeNull("a context the executor did not install is not the act's"); + answers[4].Should().BeNull("a request whose policy does not name the operator source is not captured, even when the catalog lists it"); + } + + [Fact] + public async Task A_Request_Outside_The_Catalog_Is_Refused_Before_The_Admission_Is_Spent() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + var seed = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, seed); + + await act.Should().ThrowAsync(); + rig.Observed.Should().BeEmpty("the sender was never reached"); + admission.TryConsume().Should().BeTrue("a refusal before the act leaves the admission unspent"); + } + + [Theory] + [InlineData("host_map")] + [InlineData("killswitch_toggle")] + public async Task An_Admission_For_Another_Operation_Does_Not_Admit_The_Act(string operation) + { + await using var rig = new Rig(); + var other = operation == "host_map" ? PlatformOperations.HostMap : PlatformOperations.KillswitchToggle; + var admission = TestPlatformAdmissions.Admission(other, issuedAt: Now); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + await act.Should().ThrowAsync(); + rig.Observed.Should().BeEmpty(); + admission.TryConsume().Should().BeTrue(); + } + + [Fact] + public async Task The_Platform_Sentinel_And_An_Unassigned_Tenant_Are_Not_Tenants_An_Act_May_Name() + { + await using var rig = new Rig(); + + // An id nobody assigned. Vogen refuses `default` and `new` at compile time; an array element the + // runtime zeroed is the state a deserialized DTO's unset field reaches in production. + var slot = new TenantId[1]; + var unassigned = slot[0]; + foreach (var tenant in new[] { TenantId.PlatformSentinel, unassigned }) + { + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + var act = () => rig.Executor.ExecuteAsync(admission, tenant, Provision(tenant)); + await act.Should().ThrowAsync(); + admission.TryConsume().Should().BeTrue(); + } + + rig.Observed.Should().BeEmpty(); + } + + [Fact] + public async Task A_Stale_Admission_Is_Refused_And_Is_Not_Spent_By_The_Refusal() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission( + PlatformOperations.TenantProvision, issuedAt: Now - PlatformAdmission.MaximumAge - TimeSpan.FromSeconds(1)); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + (await act.Should().ThrowAsync()).WithMessage("*stale*"); + rig.Observed.Should().BeEmpty(); + admission.TryConsume().Should().BeTrue("the age check comes before the spend, so a stale admission is simply stale"); + } + + [Fact] + public async Task One_Admission_Admits_One_Act() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + await rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + var again = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + (await again.Should().ThrowAsync()).WithMessage("*already used*"); + rig.Observed.Should().ContainSingle("the second act never reached the pipeline"); + } + + [Fact] + public void The_Act_Catalog_Refuses_An_Operation_That_Needs_The_Platform_Role_Or_No_Acts_At_All() + { + var bypass = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.KillswitchToggle))]); + var empty = () => new PlatformOperatorActCatalog([]); + + bypass.Should().Throw("the platform role is the scope facade's, never a pipeline act's"); + empty.Should().Throw(); + } + + private sealed record Observation( + ITenantContext Context, + ITrustedOperationSource Source, + TrustedOperationDescriptor? Descriptor, + bool MatchedWhileLive, + IReadOnlyList Probed); + + private sealed class Rig : IAsyncDisposable + { + private readonly ServiceProvider _provider; + + public Rig() + { + var catalog = new PlatformOperatorActCatalog( + [ + new(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.TenantProvision)), + new(typeof(OperatorMapHostCommand), new(PlatformOperations.HostMap)), + // A request whose policy admits the seed source and not the operator's: bound in the catalog + // here so the source's own check of the policy's sources is what has to refuse it. + new(typeof(MapHostToTenantCommand), new(PlatformOperations.TenantProvision)), + ]); + var clock = Substitute.For(); + clock.UtcNow.Returns(Now); + var services = new ServiceCollection(); + services.AddSingleton(Accessor); + services.AddSingleton( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()])); + services.AddSingleton(clock); + services.AddPlatformOperatorActs(catalog); + services.AddScoped(provider => + { + var sender = Substitute.For(); + sender.Send(Arg.Any>>(), Arg.Any()).Returns(_ => + { + var context = Accessor.Current!; + var source = provider.GetServices().Single(); + var descriptor = source.Capture(typeof(OperatorProvisionTenantCommand), context); + Observed.Add(new Observation( + context, source, descriptor, + descriptor?.Matches(typeof(OperatorProvisionTenantCommand), context) ?? false, + Probe?.Invoke(source, context) ?? [])); + return Failure is null + ? Task.FromResult(Result.Ok(new ProvisionedTenantDto(Tenant, "acme", OrganizationId.From(Guid.CreateVersion7()), "main"))) + : Task.FromException>(Failure); + }); + return sender; + }); + _provider = services.BuildServiceProvider(); + Executor = _provider.GetRequiredService(); + } + + public StaticTenantContextAccessor Accessor { get; } = new(null); + + public PlatformOperatorActExecutor Executor { get; } + + public List Observed { get; } = []; + + public Exception? Failure { get; set; } + + public Func>? Probe { get; set; } + + public ValueTask DisposeAsync() => _provider.DisposeAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs index 3838d479..ad871c4e 100644 --- a/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs @@ -24,6 +24,7 @@ using LearnStack.SharedKernel.Time; using MediatR; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Xunit; @@ -392,6 +393,7 @@ public Fixture(int locales = 0, bool second = true, bool host = true, bool resol services.AddSingleton(NoReservedHosts.Instance); services.AddSingleton(NullHostResolutionInvalidator.Instance); services.AddSingleton(Guard); + services.AddSingleton(new OperatorActGuard(execution, context, Unit, Locks)); _provider = services.BuildServiceProvider(); } public ISeedCustomizationPrerequisiteReader Customization { get; } = Substitute.For(); @@ -493,6 +495,10 @@ internal static void Register(ServiceCollection services, ITenantContext context customization.IsCompleteAsync(Arg.Any(), Arg.Any()).Returns(true); services.AddSingleton(customization); services.AddSingleton(); + services.AddSingleton(); + var existence = Substitute.For(); + existence.ExistsAsync(Arg.Any()).Returns(true); + services.TryAddSingleton(existence); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TenancySeedInvocationBehavior<,>)); } diff --git a/docs/decisions/0033-audit-durability-model.md b/docs/decisions/0033-audit-durability-model.md index 717686c2..d95a8181 100644 --- a/docs/decisions/0033-audit-durability-model.md +++ b/docs/decisions/0033-audit-durability-model.md @@ -873,3 +873,20 @@ writes its MUST rows in its own transaction under the real target tenant. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +## Amendment 14 — An operator act's authorization refusal writes no durable row (2026-11-19) + +Amendment 12 makes an authorization refusal a MUST `identity.authorization.deny` event. +For the `PlatformOperator` source of [ADR-0102](0102-production-tenant-onboarding.md) +the authorization evidence coordinator writes none, in either of its denial paths. +Operator refusals follow the decision [ADR-0101](0101-platform-operator-authority.md) § +11 records for denied entry: a counter and a log line by closed cause at the gate, and +the act's own refusal response, with no durable row. Inside an admitted act an +authorization refusal can only mean the request, source or context was not what the +executor built, and the act fails closed with the response. The pipeline's other rows +are unchanged: a business refusal of an admitted act writes the ordinary `failed` MUST +row in the target tenant with `metadata.operator`, and a success writes its MUST rows in +the act's own transaction. Every other source keeps Amendment 12 as written. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0036-tenant-resolution-trusted-inputs.md b/docs/decisions/0036-tenant-resolution-trusted-inputs.md index 7e4dc489..f4361580 100644 --- a/docs/decisions/0036-tenant-resolution-trusted-inputs.md +++ b/docs/decisions/0036-tenant-resolution-trusted-inputs.md @@ -1423,5 +1423,29 @@ work by one confined setter. The rule that no route resolves a tenant from a request-supplied override stands for every route that resolves context from a host or a claim. +> **Erratum (2026-11-19, Amendment 22 below).** "One confined setter" is wrong: no +> setter was added. The operator act executor installs a resolved ambient context for +> the target and the ordinary transaction behavior announces it. + The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 22 — The operator target is an executor-installed context (2026-11-19) + +Amendment 21 said the target tenant of an admitted operator act is announced by one +confined setter. As built by [ADR-0102](0102-production-tenant-onboarding.md) there is +no setter: `PlatformOperatorActExecutor` consumes the single-use admission, opens a +fresh scope and installs an immutable resolved context with `Ambient` origin, no user, +no organization and no host scope, for the tenant the operator named in the path of a +`/api/platform/v1/tenants/{tenantId}` route. It is the fifth writer of +`ITenantContextAccessor.Current`, alongside the four of Amendment 2, and +`SetTenant_Callers_Are_The_Enumerated_Four` names its file. The target comes from that +route's path and from nothing an ordinary route supplies; the rule that no route +resolves a tenant from a request-supplied override stands for every route that resolves +context from a host or a claim, and the operator surface resolves none. A request type +outside the executor's closed catalog, an admission for another operation, the platform +sentinel and an unassigned tenant are refused before the admission is spent. + +The Decision, Status, Date and prior amendments of this record are unchanged, apart from +the inline erratum beside Amendment 21. Acceptance of the linked records is not proof +that anything they decide is implemented. diff --git a/docs/decisions/0040-ambient-unit-of-work.md b/docs/decisions/0040-ambient-unit-of-work.md index 42400b75..966b3415 100644 --- a/docs/decisions/0040-ambient-unit-of-work.md +++ b/docs/decisions/0040-ambient-unit-of-work.md @@ -1012,5 +1012,35 @@ four context writers do not change. The single-act resolver that maps a provider to a `UserId` is a ninth definer function; its signature, owner, body and ACL land in [Standard 05](../standards/05-database.md) with the packet that ships it. +> **Erratum (2026-11-19, Amendment 25 below).** All three counts above were wrong when +> this amendment was written: there is no new setter, the context writers are five, and +> the resolver is the sixteenth definer. + The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 25 — Operator acts: a fifth context writer, no new setter (2026-11-19) + +Amendment 24 recorded accepted [ADR-0102](0102-production-tenant-onboarding.md) as +adding an eleventh logical tenant setter, leaving the four context writers unchanged and +counting the subject resolver as the ninth definer. The packet that implements it shows +all three counts wrong. + +- **No setter.** The operator act executor installs an immutable, resolved, ambient + context for the admitted target tenant, with no user, organization or host scope, and + the ordinary transaction behavior announces it as it announces a seed, delivery or job + context. The logical tenant setters stay at fourteen (Amendments 22 and 23). The + platform role is not used and the unit of work gains no method. +- **A fifth context writer.** The executor is the fifth writer of + `ITenantContextAccessor.Current`, named by file in + `SetTenant_Callers_Are_The_Enumerated_Four`, which keeps its name because three + Accepted records and the catalogue cite it. The claim that the four writers do not + change was unachievable: the query filters and the transaction behavior read the + accessor. +- **The sixteenth definer.** `fn_identity_operator_resolve_user(uuid, bytea)` follows + the fifteen the schema carried before it; [Standard 05](../standards/05-database.md) + carries its signature, owner, body and ACL. + +The Decision, Status, Date and prior amendments of this record are unchanged, apart from +the inline erratum beside Amendment 24. Acceptance of the linked records is not proof +that anything they decide is implemented. diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md index 7d54ae34..4860c8dc 100644 --- a/docs/decisions/0102-production-tenant-onboarding.md +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -67,6 +67,16 @@ is not proof that anything is implemented. [ADR-0040](0040-ambient-unit-of-work.md) and [ADR-0036](0036-tenant-resolution-trusted-inputs.md) receive dated disclosures, and the four context writers do not change. The platform role is not used. + + > **Erratum (2026-11-19, Amendment 1 below).** The mechanism above was not built and + > could not have been. No new tenant setter exists: the operator act executor + installs > an immutable resolved ambient context for the admitted target, and the + ordinary > transaction behavior announces it, so the setter census does not move. The + executor > is a fifth writer of the tenant context accessor, because the query + filters and the > transaction behavior read that accessor and an act that is not + installed in it is > invisible to row security. "The four context writers do not + change" and "the > eleventh logical tenant setter" were therefore false when this + record was accepted. 2. **The commands.** `OperatorProvisionTenant` creates a Tenant and its default Organization. `OperatorMapHost` maps a host through the existing host-mapping store and its reserved-host and platform-host rules. `OperatorInitializeRole` creates one @@ -184,6 +194,14 @@ naming. are the source check, the in-transaction predicates, the resolver's Active filter and the setter's operation binding. + > **Erratum (2026-11-19, Amendment 1 below).** "After the last one is revoked" names a + > state the database refuses: the deferred last-administrator guard rejects any commit + > that leaves a tenant without an available administrator, so no ordinary write + reaches > it. The proof reaches the state by an owner-level repair that steps around + that > guard, and shows the invariant intact after the recovery. "The setter's + operation > binding" reads as the executor's binding of the admitted operation to its + request > type. + ## Carriers Dated disclosures in [ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the target @@ -195,6 +213,67 @@ path), [ADR-0074](0074-membership-admission-under-ordered-locks.md) (the recover predicate under its locks), Standards 05, 18 and 19, the Identity and Tenancy module specifications, and the Phase 03 Status. +## Amendments + +### Amendment 1 — As built: an executor-installed context, no new setter (2026-11-19) + +Step 2 of the packet shipped the five acts and showed four statements of this record +wrong or stale. Each is corrected inline above and recorded here. + +1. **No new setter; a fifth context writer.** § 1 promised one new confined tenant + setter and unchanged context writers. The operator act executor + (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs`) + consumes the single-use admission, opens a fresh scope, installs an immutable + resolved `Ambient` context for the admitted tenant (no user, no organization, no host + scope) and sends the command through the ordinary pipeline, which announces that + context as it does for seed, delivery and job acts. The logical setter census stays + at fourteen ([ADR-0040](0040-ambient-unit-of-work.md) Amendments 22 and 23), the + platform role is not used, and the executor is the fifth writer of the context + accessor ([ADR-0036](0036-tenant-resolution-trusted-inputs.md) Amendment 2). The one + source that may mint the operator descriptor is the fourth minting source, scoped to + the executor's frame and bound to the operation of the admission. +2. **Provisioning on a resolved context.** The new tenant's id is the act's target, so + the executor installs a resolved context for an id that has no `tenants` row yet, and + the ordinary insert policy admits it. The operator provisioning command therefore + needs no provisioning announcement, and the seed command keeps its own. +3. **The resolver is the sixteenth definer.** `fn_identity_operator_resolve_user(uuid, + bytea)` takes the stored authority id and the derived subject key. The application + derives the key with the one `IdentitySubjectKey` implementation under the + deployment's qualified authority, and the function refuses any other authority, any + session but the application role, any key that is not 32 bytes and any transaction + that is not an ordinary read-write tenant one, then answers an Active user's id or + null. [Database Standards](../standards/05-database.md) carries the contract. +4. **Recovery is a break-glass for repaired states.** The last-administrator guard is + deferred to commit and rejects any write that leaves a tenant without an available + administrator, which means a Membership with an Active tenant-wide administrator Role + whose User is Active. Revoking or suspending the last administrator is therefore not + reachable through any ordinary path, and Users have no admitted update or removal + owner today. § 8's predicate is a Membership predicate, as accepted, and is + implemented as written: the act refuses while an Active tenant-wide administrator + Membership exists. A tenant whose only administrator Membership is nominally Active + but unusable is not a recoverable tenant under it, and a predicate that also reads + the User's eligibility would need a second confined definer. The maintainer decides + whether that is wanted. + +Two behaviors the record left open are fixed. The business actor of every written row is +`UserId.SystemActor` and the audit actor is NULL, as § 3 and +[ADR-0101](0101-platform-operator-authority.md) § 9 say. A refused operator act writes +the ordinary `failed` MUST row in the target tenant, carrying the operator in +`metadata.operator`, and an authorization refusal of an operator request writes no +durable denial row ([ADR-0033](0033-audit-durability-model.md) Amendment 14). + +Carriers changed with this amendment: ADR-0033 Amendment 14, ADR-0036 Amendment 22 and +ADR-0040 Amendment 25, each with an inline erratum beside the false text; Database +Standards, Security Standards, Audit Coverage, Permission Standards and the +Architecture-Tests Catalogue; the Identity and Tenancy module specifications; the +glossary and the onboarding runbook. +[ADR-0072](0072-application-owned-identity-bootstrap.md), +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](0074-membership-admission-under-ordered-locks.md) are read and unchanged: no +sentence of theirs is stale. The Decision, Status, Date and every other section are +unchanged. Acceptance of the linked records is not proof that anything they decide is +implemented. + ## References - [ADR-0101](0101-platform-operator-authority.md), diff --git a/docs/glossary.md b/docs/glossary.md index 8c215253..0b2fc189 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -496,6 +496,7 @@ and recurrence definitions remain empty. | **Grace Period** | The 30-day window during which an instance keeps operating after the last successful phone-home. Bounded by `grace_until` in the **durable** `platform_entitlement_cache` row — never by a cache TTL. Collapsing the two makes the advertised 30 days into 15 minutes; see [26-hybrid-license-model.md § 5](architecture/26-hybrid-license-model.md). | | **Platform Entitlement Cache** | The `platform_entitlement_cache` table in LearnStack core — the **durable** read-only mirror of the Hub-side Entitlement Aggregate, carrying `valid_until` and `grace_until`. Despite the name it is a projection store, not a cache: the volatile layers are L1 and L2 in front of it. Third in the normative read path `L1 → L2 → platform_entitlement_cache → Hub` ([ADR-0034](decisions/0034-hub-contract-surface-invariant.md)). Eager-invalidated on the entitlement-updated event. The only sanctioned reader **and** writer is an `IEntitlementProvider` implementation; no module — Tenancy included — may query it (`Modules_Do_Not_Read_Entitlement_Cache_Directly`), and `IFeatureFlags` reaches the projection through the provider rather than through this table ([ADR-0045 § 2](decisions/0045-entitlement-and-feature-flag-socket.md)). | | **Operator Portal** | `operator-portal` — the separate Next.js app for Hub operators. Authenticates against the `learnstack-hub` Keycloak realm. | +| **Operator act** | One of the platform operator's production onboarding operations of [ADR-0102](decisions/0102-production-tenant-onboarding.md): provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator. The gate admits one operation per act, and the executor runs it on the application role through the ordinary pipeline under the target tenant's resolved ambient context. Its only authorization source is `PlatformOperator`: not a Seed act, not a Membership act. Idempotent on operator-supplied identifiers. | ## Decision Records diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 3a991796..5445c74a 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -28,9 +28,11 @@ the request exists, and off-path events register by slug when their writer lands | Resource | Operation | Class | Why | |---|---|---|---| | User/global immutable subject | `identity.user.create` `(off-path)` | **MUST** (`security-event`) | ADR-0072's confined creation/adoption owner and central non-success reconciliation; success shares the User transaction. Exact global witness, source and retention contract stays there. | -| Role including grants | `identity.role.initialize` | **MUST** (`security-event`) | `InitializeSeedRole`; one Role transaction, with contained grants. | +| Role including grants | `identity.role.initialize` | **MUST** (`security-event`) | `InitializeSeedRole` and the operator's `OperatorInitializeRoleCommand` share this slug; one Role transaction, with contained grants. | | Membership including Profile/Assignments | `identity.membership.create_first_seed_admin` | **MUST** (`security-event`) | `CreateFirstSeedAdminMembership`; one Membership transaction. | | Membership including Profile/Assignments | `identity.membership.create_seed` | **MUST** (`security-event`) | `CreateSeedMembership`; one Membership transaction. | +| Membership including Profile/Assignments | `identity.membership.create_first_admin` | **MUST** (`security-event`) | `OperatorCreateFirstAdminCommand`, the operator's production first administrator ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)); one Membership transaction on the operator source, `metadata.operator` and the reason slug on the row, refused once the tenant has had any member. | +| Membership including Profile/Assignments | `identity.membership.recover_admin` | **MUST** (`security-event`) | `OperatorRecoverAdminCommand`, the operator's replacement administrator for a tenant with none active; one Membership transaction on the operator source, refused while any administrator is active. | | MembershipProfile, captured under Membership | `identity.membership_profile.set_seed_profile` | **MUST** (`update`) | `SetSeedMembershipProfile`; same Membership transaction. The slug matches the gated sub-resource while the row's subject remains its owning aggregate. | | Authorization decision | `identity.authorization.deny` `(off-path)` | **MUST** (`security-event`) | Central HTTP/application/resource denial owner; one decided invocation event, separate from ordinary plural resource intents. No tenant override or host suppression budget. | | Membership directory | `identity.membership.list` | **MUST** (`read-sensitive`) | Internal `ListMembershipsQuery` under existing Tenant `identity.membership.admin`; ordinary ReadWrite owner commits its row before disclosure. No HTTP activation follows from its catalogue entry. | diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md index 93caa458..2263a475 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -26,6 +26,9 @@ permission admission. An attribute, realm role or SystemActor value grants no ro | `CreateSeedMembership` | Tenant or Organization `identity.membership.admin` | Exact declared learner tuple/target scope; no arbitrary actor/tenant/org/Role | | `SetSeedMembershipProfile` | Tenant or Organization `identity.membership_profile.write` | Declared Membership and bounded contextual fields, through the Membership root | | `InitializeSeedRole` | Tenant `identity.role.admin` | Exact tenant/template/v1 manifest, including Organization-capability templates; one Role root | +| `OperatorInitializeRoleCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | One finite template of the target tenant, before any Membership exists; idempotent on the operator's Role id ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) | +| `OperatorCreateFirstAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | The first tenant-wide administrator of a tenant with no Membership history; the person is named by provider subject and must be an Active, bootstrapped User | +| `OperatorRecoverAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | A replacement administrator while no Active tenant-wide administrator Membership exists; the last-administrator guard is the database's and is unchanged | Scope selection derives from immutable target Membership/validated declaration, never a claimed scope string. Finite metadata alternatives count the exact five diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 579ba5d8..026baee0 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -68,6 +68,13 @@ under [ADR-0033](../../decisions/0033-audit-durability-model.md). The branding w shares that guarantee; a failed MUST audit rolls its setting write back too. +**Operator acts share the slugs.** The operator's production provisioning and host +mapping ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) register the +same slugs as the seed commands, in the same classes, written on the act's own +transaction under the target tenant with `actor_user_id` NULL, the closed reason slugs +`tenant_provision` and `host_map`, and `metadata.operator`. Provisioning writes the two +rows below, and a refused act writes the ordinary `failed` row. + **One command, two rows.** An intent is parked per audited `(resource, operation)` and not per request ([ADR-0044 § 3](../../decisions/0044-audit-write-path.md)), so `ProvisionTenantCommand` declares `tenancy.tenant.create` **and** diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index ffb1834d..91e0e941 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -111,9 +111,16 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi the widening it needs is an ADR's to make, not a migration's. The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) -is separate and never assignable to a Role. Tenancy owns one key in it today, -`platform.killswitch.write`, which authorizes the operator surface to toggle -`platform_killswitches`; operators hold it by configuration +is separate and never assignable to a Role. Tenancy owns two keys in it today. +`platform.killswitch.write` authorizes the operator surface to toggle +`platform_killswitches`. `platform.tenant.write` authorizes the operator's production +tenant provisioning and host mapping +([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)): +`OperatorProvisionTenantCommand` and `OperatorMapHostCommand` are `FiniteTrusted` +operations whose one source is `PlatformOperator`, run on the application role under the +target tenant's ordinary announcement, and share their audit slugs +(`tenancy.tenant.create`, `tenancy.organization.create`, `tenancy.hostmapping.write`) +with the seed commands they parallel. Operators hold the keys by configuration ([Standard 19](../../standards/19-permissions.md)). ## Bounded human administration contract diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index 6150ffbe..bf5ae187 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -10,3 +10,4 @@ begins this directory with the platform operator runbooks; |---|---| | [Platform operator access](operator-access.md) | An operator needs a token, a grant, or an answer to a 401, 403 or 503 | | [Killswitch](killswitch.md) | A capability must be switched off for every tenant during an incident | +| [Tenant onboarding](tenant-onboarding.md) | A production tenant must be provisioned, mapped to a host and given its first administrator, or an administrator must be recovered | diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index ba99e926..3e1ebb75 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -22,7 +22,7 @@ The surface does not exist until an issuer is configured; with none, every | `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | | `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, as a time span such as `00:15:00`; at most one hour, default 15 minutes | | `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | -| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the acts run under. Required for any act: without it the first act fails with an error that names this key | +| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act runs under. Required for that act: without it the first act fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | List settings are indexed in environment variables, and the double underscore is the separator: diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 8658ef28..15452069 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -5643,18 +5643,23 @@ rewriting the selected terminal status. ## Invitation entry and consumption -**Derives from:** [ADR-0093](../decisions/0093-verified-invitation-acceptance-and-handoff.md). -Implemented P03-4 contract; the -[phase Status](../roadmap/phase-03-identity-admin.md) owns qualification and follow-ups. This section extends the earlier global/contextual contracts; -the earlier eight-function/ten-setter counts describe their historical slices. -The delivered ADR-0093 baseline is eleven confined definers, eleven logical tenant -setters and four physical context writers. The [P03-5 extension](#custom-field-and-consent-storage) -implements twelve definers/twelve logical setters. The -[provider-event extension](#provider-event-intake-storage) brings the census to -fifteen definers/thirteen logical setters, preserving those four physical -writers; qualification remains source-bound in the phase Status. SMTP adds no tenant setter. -The [federation host-alias read](#federation-host-alias-read) is the fourteenth logical -setter; it adds no definer and no physical context writer. +**Derives from:** +[ADR-0093](../decisions/0093-verified-invitation-acceptance-and-handoff.md). Implemented +P03-4 contract; the [phase Status](../roadmap/phase-03-identity-admin.md) owns +qualification and follow-ups. This section extends the earlier global/contextual +contracts; the earlier eight-function/ten-setter counts describe their historical +slices. The delivered ADR-0093 baseline is eleven confined definers, eleven logical +tenant setters and four physical context writers. The +[P03-5 extension](#custom-field-and-consent-storage) implements twelve definers/twelve +logical setters. The [provider-event extension](#provider-event-intake-storage) brings +the census to fifteen definers/thirteen logical setters, preserving those four physical +writers; qualification remains source-bound in the phase Status. SMTP adds no tenant +setter. The [federation host-alias read](#federation-host-alias-read) is the fourteenth +logical setter; it adds no definer and no physical context writer. The +[operator subject resolution](#operator-subject-resolution) is the sixteenth definer; it +adds no logical tenant setter. The operator act executor that installs an operator act's +resolved context is the fifth writer of the context accessor +([ADR-0040 Amendment 25](../decisions/0040-ambient-unit-of-work.md)). ### Invitation root and constrained transitions @@ -6241,3 +6246,38 @@ pins its statements, implementation and caller; `Out_Of_Band_Setters_Open_Read_Only_Transactions` lists it among the own-connection readers. +## Operator onboarding storage + +**Derives from:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and its +Amendment 1. An operator onboarding act runs on the application role under the ordinary +tenant announcement, so it adds no table, no policy and no grant. It adds one confined +definer. + +### Operator subject resolution + +`users` is under forced row security keyed by identity settings that every tenant +announcement blanks, so a tenant transaction cannot read it. The act that names a first +administrator by provider subject needs the `UserId` of an Active user, so one definer +answers exactly that: + +- **Function.** + `public.fn_identity_operator_resolve_user(selected_authority uuid, selected_subject_key bytea) RETURNS uuid`, + `LANGUAGE plpgsql STABLE SECURITY DEFINER`, owned by `learnstack_migration` (whose + policy branch sees `users`), fixed `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, + `EXECUTE` to `learnstack_app` only. +- **Refusals.** Any session user but `learnstack_app`, an empty tenant announcement, a + read-only or non-`READ COMMITTED` transaction, a null argument, a key that is not 32 + bytes, and any authority id other than the one stored in `identity_authority`. Each + raises `23514` and reveals nothing. +- **Answer.** The `id` of the one `users` row with that authority and key whose `status` + is `Active` and whose `deleted_at` is null, otherwise null. It reads no other relation + and writes nothing. +- **Caller.** `OperatorSubjectResolver`, which derives the key with the one + `IdentitySubjectKey` implementation under the deployment's qualified authority, so a + request supplies the provider subject and nothing else. The exact SQL, ACL, owner and + caller are pinned by the definer census (sixteen definers). + +A Membership written under that answer still passes the ordinary admission guard, which +re-reads the User's eligibility under the user fence, so the resolver is a lookup and +not an authority. + diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index ac6e127c..1fee1403 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -164,8 +164,14 @@ LearnStack runs **two Keycloak realms** per (`/api/platform/v1/*`, [ADR-0101](../decisions/0101-platform-operator-authority.md)). Tenant-facing apps and the tenant API **never** accept `learnstack-hub` tokens; the internal API (`/api/internal/*`) **only** accepts `learnstack-hub` tokens plus the - mTLS client certificate; and the platform operator prefix accepts operator tokens - of its pinned issuer only, for its own audience. + mTLS client certificate; and the platform operator prefix accepts operator tokens of + its pinned issuer only, for its own audience. The operator's onboarding acts + ([ADR-0102](../decisions/0102-production-tenant-onboarding.md)) run on the application + role, under row security, through the ordinary pipeline; the one `BYPASSRLS` use of + the operator surface remains the killswitch writer. The executor that installs an + act's tenant context accepts only an admission the gate minted for that act within the + last 30 seconds and spends it once, and the seeder refuses to run outside a + Development deployment. General rules: diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 96f41947..abb0854c 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -318,19 +318,24 @@ Rules: member name on the wire and in the column, which is why the example above reads `Create` and `Must` where the tables read `create` and **MUST**. - `outcome` is one of `success`, `denied`, `failed`, `indeterminate` - ([ADR-0044 § 5](../decisions/0044-audit-write-path.md); ADR-0016's `is_success boolean` - is superseded, because a boolean cannot carry `denied`). `denied` is used when an - authorisation check rejects the operation — these MUST be audited so we can detect - probing. A Platform operator admission refusal is tenantless and outside that - population: it leaves a counter and a Warning log - ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11). `indeterminate` is the commit whose server-side outcome is unknown: the - standalone re-write carries the **same** `id` as the in-transaction attempt, and the - pair is what a reviewer reads as one commit in doubt. `PostgresAuditStore` supplies - `occurredAt` from `IClock` — the intent's declaration time in the transaction, a fresh - reading for a standalone re-write — which is what keeps that pair legal under the - composite primary key `(id, timestamp)`. This describes ordinary resource - reconciliation; [trusted denial occurrences](#trusted-authorization-evidence) - instead retain one fixed key, timestamp and draft. + ([ADR-0044 § 5](../decisions/0044-audit-write-path.md); ADR-0016's + `is_success boolean` is superseded, because a boolean cannot carry `denied`). `denied` + is used when an authorisation check rejects the operation — these MUST be audited so + we can detect probing. A Platform operator admission refusal is tenantless and outside + that population: it leaves a counter and a Warning log + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11), and so does an + authorization refusal of an operator act inside the pipeline + ([ADR-0033 Amendment 14](../decisions/0033-audit-durability-model.md)). A business + refusal of an admitted operator act writes the ordinary `failed` row in the target + tenant, with `actor_user_id` NULL, the closed reason slug and `metadata.operator`. + `indeterminate` is the commit whose server-side outcome is unknown: the standalone + re-write carries the **same** `id` as the in-transaction attempt, and the pair is what + a reviewer reads as one commit in doubt. `PostgresAuditStore` supplies `occurredAt` + from `IClock` — the intent's declaration time in the transaction, a fresh reading for + a standalone re-write — which is what keeps that pair legal under the composite + primary key `(id, timestamp)`. This describes ordinary resource reconciliation; + [trusted denial occurrences](#trusted-authorization-evidence) instead retain one fixed + key, timestamp and draft. - `reason` is required when the operator is a platform admin acting on a tenant they are not a member of. It is the closed reason slug of the registered operator operation (`PlatformOperation.ReasonSlug`) — never caller-supplied text — and it is surfaced in diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 4905053b..6ffd1431 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write` (registered); `platform.tenant.write`, `platform.tenant_bootstrap.write` and the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue join with the step that ships the operation using them, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write` and `platform.tenant_bootstrap.write` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | @@ -104,6 +104,15 @@ not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authori | Key | Operation | Packet | |---|---|---| | `platform.killswitch.write` | `tenancy.killswitch.toggle` | P03-9 Step 1 | +| `platform.tenant.write` | `tenancy.tenant.create` (tenant provisioning), `tenancy.hostmapping.write` (host mapping) | P03-9 Step 2 | +| `platform.tenant_bootstrap.write` | `identity.role.initialize`, `identity.membership.create_first_admin`, `identity.membership.recover_admin` | P03-9 Step 2 | + +The five onboarding acts of +[ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the +`PlatformOperator` authorization source, which is not a Membership candidate: their +policies are `FiniteTrusted` with that single source, the business actor of every row +they write is `UserId.SystemActor`, and the operator is recorded in audit only. The +grant is evaluated by the gate on every act, never cached across acts. Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 0310bb69..31062f4c 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**379 test methods run in +**381 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**284 rules in this catalogue are Implemented, and 166 of them are in that assembly.** +**285 rules in this catalogue are Implemented, and 167 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -2792,10 +2792,13 @@ promotes an unrun proof. [source ledger](05-database.md#authorization-and-evidence-source-ledger). - **Type:** source/caller/role census plus real app-role PostgreSQL/PgBouncer progress and lifetime controls. **Kind:** behavioural and structural. -- **Test owners:** `IdentityAuthorizationReaderTests`, - `AuthorizationReadSourceTests`, `AuthorizationPoolProgressTests`, - `IdentityAuthorizationConventionTests`, `TrustedOperationSourceConventionTests`, - `OperationPolicyOwnershipTests`, `IdentityAuditConventionTests`. +- **Test owners:** `IdentityAuthorizationReaderTests`, `AuthorizationReadSourceTests`, + `AuthorizationPoolProgressTests`, `IdentityAuthorizationConventionTests`, + `TrustedOperationSourceConventionTests`, `OperationPolicyOwnershipTests`, + `IdentityAuditConventionTests`. `TrustedOperationSourceConventionTests` pins four + minting sources, the seed, delivery, job and operator-act owners + ([ADR-0102](../decisions/0102-production-tenant-onboarding.md)), and the operator + source's one caller and its closed evidence lifetime. - **Status:** **Implemented** — `IdentityAuditConventionTests`; source/caller controls complement the real PostgreSQL/PgBouncer owners above. - **Coverage:** the confined reader/source, actual PostgreSQL/ @@ -5702,29 +5705,34 @@ structural test proves — and what it does not. #### `SetTenant_Callers_Are_The_Enumerated_Four` - **Asserts:** `ITenantContextAccessor.Current` is **written** only by the HTTP, - internal Hub, job and integration-event boundaries. ADR-0047 names JobExecutor - as the sole job-path writer, replacing the unshipped Hangfire JobActivator. - `EnterPlatformAdminScope` opens a separate connection and writes no tenant - context. Reads are unconstrained; no new writer is admitted before it ships. + internal Hub, job, integration-event and operator-act boundaries. ADR-0047 names + JobExecutor as the sole job-path writer, replacing the unshipped Hangfire + JobActivator; `PlatformOperatorActExecutor` is the operator-act writer + ([ADR-0040 Amendment 25](../decisions/0040-ambient-unit-of-work.md)). + `EnterPlatformAdminScope` opens a separate connection and writes no tenant context. + Reads are unconstrained; no new writer is admitted before it ships. - **Source:** ADR-0036 § Rules, second bullet, as corrected by its erratum and [Amendments 2 and 12](../decisions/0036-tenant-resolution-trusted-inputs.md). - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`TenantContextConstructionTests`, Packet 7 step 5). - **Phase:** 02a (Packet 7). - **Note:** the name predates the correction and is kept. `ITenantContextAccessor` - declares one member, `ITenantContext? Current { get; set; }`, and the `SetTenant` - this row used to name has never existed; ADR-0036 Amendment 2 fixes the ADR and - keeps the test's spelling, because § Canonical names makes a rename its own - liability and the name describes the caller set, which is what ADR-0036 decides. + declares one member, `ITenantContext? Current { get; set; }`, and the `SetTenant` this + row used to name has never existed; ADR-0036 Amendment 2 fixes the ADR and keeps the + test's spelling, because § Canonical names makes a rename its own liability and the + name describes the caller set, which is what ADR-0036 decides. The set is five logical + writers since the operator executor landed (ADR-0036 Amendment 22), and the name is + kept for the same reason. - **Note:** a source scan rather than NetArchTest: NetArchTest resolves *type* references and cannot see a write to a property, which is the whole assertion — the same reason `Effective_Host_Computed_In_One_Place` is a scan. The needle (`.Current =`) is receiver-agnostic, so an unrelated `Activity.Current =` would trip it; that is a false positive to exempt by path, never a reason to filter by folder. -- **Note:** **three of the four logical boundaries exist** — TenantResolverMiddleware, +- **Note:** **four of the five logical boundaries exist** — TenantResolverMiddleware, the integration-event acceptance/execution scope in InProcessEventBus and - DeliveryExecutor, and JobExecutor's framework/business partials. The two JobExecutor - files are one logical writer. HubCorrelationMiddleware belongs to Phase 02c. + DeliveryExecutor, JobExecutor's framework/business partials and the operator act + executor. The JobExecutor partials are one logical writer. HubCorrelationMiddleware + belongs to Phase 02c. The whole-source census also refuses every writer outside the exact file set. The first version of the test scanned only files whose path contained `Tenancy`, which deleted the `InProcessEventBus` writer from its own expectation *and* let a From a2a66757138518b28667d14d4e3c88482e2ad91b Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 18:11:19 +0300 Subject: [PATCH 08/28] docs(runbooks): add the tenant onboarding runbook The five operator acts, their order, the person-first rule, recovery and its reach, the refusal table and how to read the audit rows. The ADR errata and amendments, standards and module matrices landed with the code. ADR: 0102 Co-Authored-By: Claude Sonnet 5.5 --- docs/runbooks/tenant-onboarding.md | 145 +++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/runbooks/tenant-onboarding.md diff --git a/docs/runbooks/tenant-onboarding.md b/docs/runbooks/tenant-onboarding.md new file mode 100644 index 00000000..c8421a20 --- /dev/null +++ b/docs/runbooks/tenant-onboarding.md @@ -0,0 +1,145 @@ +# Tenant onboarding + +Creating a production tenant that resolves to a host and has one administrator who can +sign in, and recovering one that has none. Decided in +[ADR-0102](../decisions/0102-production-tenant-onboarding.md); the storage contract of +the one definer it adds is in +[Database Standards](../standards/05-database.md#operator-subject-resolution). The +development seed is not this procedure: the seeder refuses to run outside a Development +deployment. + +## What it needs + +An operator with a current token (see [operator access](operator-access.md)) holding +`platform.tenant.write` for the first two acts and `platform.tenant_bootstrap.write` for +the other three. The grant is read from configuration on every act. No platform database +credential is involved: every act below runs on the application role, under the +tenant's own row security, through the same pipeline a request uses. + +You also need, before you start: + +- A tenant id, an organization id, a role id per template and a membership id, each a + **UUIDv7** that you generate. The ids are the acts' identity: sending an act again + with the same ids is a retry and never a second write. +- A slug for the tenant and for its default organization, and the host the tenant will + answer on. +- The first administrator's provider subject (`sub`) at the tenant issuer, read from the + identity provider's own console. An email address is never accepted. + +## The order + +Each act commits in its own transaction. Stop between any two and resume at the first +act that has not been answered `200`. + +1. **Provision the tenant and its default organization.** + `PUT /api/platform/v1/tenants/{tenantId}` + + ```json + { + "slug": "acme", + "displayName": "Acme Academy", + "defaultOrganization": { "id": "", "slug": "main", "displayName": "Main" }, + "ticket": "CHG-123" + } + ``` + +2. **Map the host.** `PUT /api/platform/v1/tenants/{tenantId}/host-mappings/{host}` with + `{ "isActive": true, "isPubliclyLive": true, "ticket": "CHG-123" }`. `organizationId` + is optional and pins the host to one branch. **You assert that the tenant owns the + host.** LearnStack checks no DNS and issues no certificate: a Self-Hosted operator is + responsible for both. A SaaS custom domain is the Hub's to approve and is not + reachable from here. + +3. **The person signs in once at that host.** The tenant has no members yet, and the + zero-membership entry binds the person to the identity authority the first time they + sign in. The next acts refuse a subject that has not done this + (`lockey_bootstrap_required`). + +4. **Initialize the Role templates** the tenant will need, one act each: + `PUT /api/platform/v1/tenants/{tenantId}/roles/{roleId}` with + `{ "builtInKey": "TenantAdmin", "capabilityScope": "Tenant", "ticket": "CHG-123" }`. + The foundation admits eight templates: at scope `Tenant` the `builtInKey` is + `TenantAdmin`, `Instructor`, `Learner`, `Guardian` or `Editor`; at scope + `Organization` it is `OrgAdmin`, `OrgInstructor` or `Learner`. `TenantAdmin` at + `Tenant` is the one step 5 needs. **Initialize every template the tenant will use + now:** a Role template cannot be created once the tenant has had a Membership. + +5. **Create the first administrator.** + `PUT /api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}` with + `{ "roleId": "", "providerSubject": "", "ticket": "CHG-123" }`. + It refuses any tenant that has ever had a Membership, so it cannot add an + administrator to a tenant that has members. + +The `ticket` in each body is optional, and is the operator's own reference. Every answer +is `200 { "result": ..., "correlationId": "..." }`. Keep the correlation id. + +## Recovering a tenant with no administrator + +`PUT /api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}` with the +same body as step 5. It creates a replacement administrator and is the only act that +adds one to a tenant with Membership history. + +**It refuses while any Active tenant-wide administrator Membership exists** +(`lockey_administrator_exists`). The database also refuses to leave a tenant without an +available administrator, so revoking or suspending the last one through the product is +not possible. Recovery therefore applies to a tenant whose administration was lost +outside that guard, for example after an owner-level repair. It does **not** apply to a +tenant whose administrator is Active but cannot sign in: escalate that to the platform +owner, because it is a decision about identity, not a runbook step. The act names an +initialized `TenantAdmin` Role of the tenant and an Active, bootstrapped person, and +leaves the last-administrator guard as it found it. + +## When an act answers something else + +| Status | Reason (in the problem's `errors`) | What it means and what to do | +|---|---|---| +| 400 | `validation_failed` | The body is malformed, a value is out of its grammar, an id is not a UUIDv7, or the ticket is not 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -` | +| 401 | | The token does not meet the profile; there is one answer for every cause, and the cause is in the operator's signals | +| 403 | | The token is good and the operator holds no grant for this act | +| 404 | | The tenant does not exist, or the act can no longer see it. Provision first | +| 409 | `lockey_slug_taken`, `lockey_identifier_taken` | Another tenant has the slug, or an id is already used by a different record. Use another value; an exact repeat of your own act is a `200` | +| 409 | `lockey_bootstrap_required` | The named person has not signed in at the tenant's host (or is not Active). Ask them to sign in, then repeat | +| 409 | `lockey_role_not_initialized` | The role id names no initialized `TenantAdmin` template of this tenant. Run step 4 first | +| 409 | `lockey_tenant_has_memberships` | The tenant has had a Membership, so a first administrator or a new template is refused. Use recovery only if no administrator is active | +| 409 | `lockey_administrator_exists` | Recovery refused: an Active administrator exists | +| 409 | `lockey_role_template_unknown`, `lockey_identity_foundation_refused` | The template or the resulting graph is not one the identity foundation admits | +| 503 | | The audit row could not be written or a dependency could not answer, so nothing changed. Retry after a short delay | + +A refused act writes a `failed` audit row in the tenant, so the attempt is on the +record. + +## Repeating an act + +Every act is idempotent on the ids you chose, so any failure that leaves you unsure, a +timeout or a connection reset or a `500` after a commit, is answered by sending the same +request again. The retry finds what was written and answers `200`; it never writes a +second row. A retry whose ids match but whose other values differ is refused as +`lockey_identifier_taken` or `lockey_slug_taken` rather than changing the record. + +## Reading the record + +Each act writes its MUST audit rows in its own transaction, in the target tenant, with +`actor_user_id` NULL, a closed reason slug (`tenant_provision`, `host_map`, +`role_initialize`, `first_admin_create`, `admin_recover`) and `metadata.operator` +carrying the issuer, the operator's subject digest, the accepted `acr` and the executor. +The ticket is not on these rows, because the tenant can read them. As the application +role, announcing the tenant inside a transaction, by the correlation id the answer +returned: + +```sql +BEGIN; +SELECT set_config('app.tenant_id', '', true); +SELECT timestamp, operation, outcome, reason, metadata->'operator' AS operator +FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; +COMMIT; +``` + +The operator's digest is computed as in [Killswitch](killswitch.md#reading-the-record). + +## What this does not do + +It does not verify DNS, issue TLS, send an invitation, set a plan or an entitlement, +create a Hub record, or deprovision a tenant. A tenant that needs an entitlement before +it serves is waiting on the Hub's push or the operator-configured default, which is the +Hub's runbook. Nothing here moves a tenant between identity issuers; that is a separate +act ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). From 101578c11c8bbe3f0c03e6f27dcf6dad4e75db08 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 18:56:20 +0300 Subject: [PATCH 09/28] fix(platform): close P03-9 step 2 review round 1 findings Three read-only reviews (authority and security, correctness and concurrency, tests/censuses/docs) found no blocker. Fixed: provisioning replay compares the full request and answers from the stored records; administrator and role acts find their own result before judging the Role's present state; the host-mapping retry drops the cached resolution again and both flags are required; a blank subject, an over-long subject, the platform sentinel and non-UUIDv7 ids are 400; the subject resolver is called only after a live-act check and its migration is forward-only; storage refusals answer in the sibling Identity vocabulary; the HTTP/2 body rule; the act outcome counter and event 7109 that ADR-0102 section 11 promised. Tests add a reply lost after the commit, an act interrupted between its writes, host and role-scope refusals, route validation, resolver refusals and the act counter. ADR errata are rewritten in the ADR-0041 form and ADR-0102 Amendment 1 records what was built; the runbook, Standards 05 and 18 and the catalogue are corrected. ADR: 0102 Module: Tenancy, Identity Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorEndpoints.Onboarding.cs | 28 +- .../Platform/PlatformOperatorEndpoints.cs | 6 +- .../Audit/AuthorizationEvidenceCoordinator.cs | 3 +- .../PlatformOperatorActExecutor.cs | 58 ++- .../PlatformOperatorMetrics.cs | 37 ++ .../Permissions/OperatorActGuard.cs | 23 + .../OperatorActs/OperatorIdentityHandlers.cs | 60 ++- ...119140000_add_operator_subject_resolver.cs | 5 +- .../Persistence/OperatorSubjectResolverDdl.cs | 4 - .../Tenant/MapHostToTenantCommandHandler.cs | 17 +- .../Tenant/ProvisionTenantCommandHandler.cs | 25 +- ...itConventionTests.AuthorizationEvidence.cs | 1 + .../PlatformAdminScopeConventionTests.cs | 17 + .../TenantContextConstructionTests.cs | 2 +- .../Database/MigrationRollbackTests.cs | 6 +- .../Database/OperatorSubjectResolverTests.cs | 11 +- .../PlatformOperatorOnboardingTests.cs | 392 +++++++++++++++++- .../Authorization/OperatorActGuardTests.cs | 92 +++- .../PlatformOperatorActExecutorTests.cs | 117 +++++- docs/decisions/0033-audit-durability-model.md | 15 +- .../0036-tenant-resolution-trusted-inputs.md | 11 +- docs/decisions/0040-ambient-unit-of-work.md | 11 +- .../0102-production-tenant-onboarding.md | 118 ++++-- docs/runbooks/tenant-onboarding.md | 56 ++- docs/standards/05-database.md | 18 +- docs/standards/18-audit-coverage.md | 5 +- .../21-architecture-tests-catalogue.md | 19 +- 27 files changed, 1000 insertions(+), 157 deletions(-) diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs index cde90e96..1343e966 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs @@ -103,9 +103,12 @@ private static Task MapHostAsync( RunAsync( http, tenantId, PlatformOperations.HostMap, gate, executor, loggers, body => body.Ticket, - body => new OperatorMapHostCommand( - host, body.OrganizationId is { } organization ? OrganizationId.From(organization) : null, - body.IsActive ?? true, body.IsPubliclyLive ?? true), + // Both flags are the operator's to state: there is no act that unmaps a host, so a mapping must + // never arrive serving anonymous traffic because a field was left out. + body => body.IsActive is { } active && body.IsPubliclyLive is { } live + ? new OperatorMapHostCommand( + host, body.OrganizationId is { } organization ? OrganizationId.From(organization) : null, active, live) + : null, cancellationToken); private static Task InitializeRoleAsync( @@ -128,8 +131,8 @@ private static Task CreateFirstAdminAsync( RunAsync( http, tenantId, PlatformOperations.FirstAdminCreate, gate, executor, loggers, body => body.Ticket, - body => body.ProviderSubject is { } subject && IsRoot(membershipId) && IsRoot(body.RoleId) - ? new OperatorCreateFirstAdminCommand(membershipId, body.RoleId, subject) : null, + body => IsSubject(body.ProviderSubject) && IsRoot(membershipId) && IsRoot(body.RoleId) + ? new OperatorCreateFirstAdminCommand(membershipId, body.RoleId, body.ProviderSubject!) : null, cancellationToken); private static Task RecoverAdminAsync( @@ -138,8 +141,8 @@ private static Task RecoverAdminAsync( RunAsync( http, tenantId, PlatformOperations.AdminRecover, gate, executor, loggers, body => body.Ticket, - body => body.ProviderSubject is { } subject && IsRoot(membershipId) && IsRoot(body.RoleId) - ? new OperatorRecoverAdminCommand(membershipId, body.RoleId, subject) : null, + body => IsSubject(body.ProviderSubject) && IsRoot(membershipId) && IsRoot(body.RoleId) + ? new OperatorRecoverAdminCommand(membershipId, body.RoleId, body.ProviderSubject!) : null, cancellationToken); /// @@ -200,7 +203,16 @@ private static async Task RunAsync( } } - private static bool IsRoot(Guid id) => id != Guid.Empty && id.Version == 7; + /// + /// An identifier the operator generates: a UUIDv7, never the nil value and never the platform sentinel, which + /// is the tenant the platform's own rows belong to and which no operator act may name. + /// + private static bool IsRoot(Guid id) => id != Guid.Empty && id.Version == 7 && id != TenantId.PlatformSentinel.Value; + + private const int MaximumSubjectLength = 255; + + private static bool IsSubject(string? subject) => + !string.IsNullOrWhiteSpace(subject) && subject.Length <= MaximumSubjectLength; private static IResult RefusalProblem(HttpContext http, PlatformRefusal refusal) => refusal switch { diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index a5d9c946..8e0a15df 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -82,7 +82,11 @@ private enum BodyState { Read, Missing, NotJson, Malformed } HttpRequest request, CancellationToken cancellationToken) where TBody : class { - if (request.ContentLength is 0 || (request.ContentLength is null && !request.Headers.ContainsKey("Transfer-Encoding"))) + // HTTP/1.x with neither a length nor a transfer encoding has no body. HTTP/2 and HTTP/3 carry bodies + // without either header, so for them only a declared zero length is an absent body. + var undeclared = request.ContentLength is null && !request.Headers.ContainsKey("Transfer-Encoding") + && (HttpProtocol.IsHttp10(request.Protocol) || HttpProtocol.IsHttp11(request.Protocol)); + if (request.ContentLength is 0 || undeclared) { return (null, BodyState.Missing); } diff --git a/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs b/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs index aa5e5f6b..5c9ebbfb 100644 --- a/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs +++ b/backend/src/LearnStack.Application/Audit/AuthorizationEvidenceCoordinator.cs @@ -167,7 +167,8 @@ public async Task RecordConfirmedAssertionAsync(ConfirmedClaimAssertion assertio private void RecordDenial(OperationInvocation invocation, ProtectedOperationDecision? decision, AuthorizationRefusalReason reason, string errorKey = "lockey_forbidden", AuthorizationAuditContext? observedContext = null) { - // An operator's refused act leaves a counter and a log line and no durable row (ADR-0101 § 11). + // An operator's refused act writes no durable row: the executor counts it as refused and logs event 7109 + // (ADR-0033 Amendment 14). if (invocation.TrustedSource is { SourceKind: AuthorizationSourceKind.PlatformOperator }) return; if (_entries.ContainsKey(invocation) || !HasAttribution(invocation)) return; try diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs index 3711ea36..e8d9c780 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs @@ -6,6 +6,7 @@ using LearnStack.SharedKernel.Time; using MediatR; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace LearnStack.Infrastructure.PlatformOperator; @@ -15,14 +16,13 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// /// /// -/// The confined tenant setter. This is the one place a tenant chosen by an operator reaches the -/// pipeline. It consumes the admission, opens a fresh scope, installs an immutable -/// in the accessor for the length of the act (or leaves the -/// context unresolved when the act creates its tenant, which then announces itself through -/// IProvisionsTenant as the seed's provisioning does), enters the one-frame operator source, -/// sends the request and restores the accessor. The target is never read from a header, a host or an -/// ambient value, and a request outside the closed catalog, or one the admission's operation does not -/// cover, is refused before any scope exists. +/// The one place an operator's tenant reaches the pipeline. It consumes the admission, opens a +/// fresh scope, installs an immutable resolved in the accessor for +/// the length of the act, including for the tenant the act is about to create, enters the one-frame +/// operator source, sends the request, counts how the act ended and restores the accessor. The ordinary +/// transaction behavior announces the installed context, so this adds no tenant setter. The target is +/// never read from a header, a host or an ambient value, and a request outside the closed catalog, or one +/// the admission's operation does not cover, is refused before any scope exists. /// /// /// It is a context writer, and says so. Installing a context in the accessor is what makes the @@ -31,11 +31,12 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// runtime. The platform role is not used, and nothing here opens a connection. /// /// -public sealed class PlatformOperatorActExecutor( +public sealed partial class PlatformOperatorActExecutor( IServiceScopeFactory scopeFactory, ITenantContextAccessor accessor, PlatformOperatorActCatalog acts, - IClock clock) + IClock clock, + ILogger logger) { /// Runs for under . /// The admission or the request is not admissible. @@ -77,11 +78,46 @@ public async Task ExecuteAsync( var source = services.GetServices().OfType().Single(); using var frame = source.Enter(admission, context); - return await services.GetRequiredService().Send(request, cancellationToken); + TResponse response; + try + { + response = await services.GetRequiredService().Send(request, cancellationToken); + } + catch + { + PlatformOperatorMetrics.Act(admission.Operation, PlatformOperatorActOutcome.Failed); + throw; + } + + if (response.IsSuccess) + { + PlatformOperatorMetrics.Act( + admission.Operation, + services.GetRequiredService().Replayed + ? PlatformOperatorActOutcome.Replayed : PlatformOperatorActOutcome.Applied); + } + else + { + PlatformOperatorMetrics.Act(admission.Operation, PlatformOperatorActOutcome.Refused); + if (response.Error?.Code == "forbidden") + { + // An admitted act the pipeline itself refused means the request, source or context was not what + // this executor built: a defect, not an operator's mistake, and it writes no audit row. + LogPipelineRefused(logger, admission.Operation.AuditSlug); + } + } + + return response; } finally { accessor.Current = previous; } } + + [LoggerMessage( + EventId = 7109, + Level = LogLevel.Warning, + Message = "An admitted operator act {Operation} was refused by the request pipeline as forbidden; the request, source or context was not what the executor built.")] + private static partial void LogPipelineRefused(ILogger logger, string operation); } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index 6b8bb3c0..7a250d62 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -23,6 +23,9 @@ public static class PlatformOperatorMetrics /// MUST result rows committed, by operation. public const string ResultCounterName = "learnstack_platform_operator_results_total"; + /// Onboarding acts by operation and outcome (applied, replayed, refused, failed). + public const string ActCounterName = "learnstack_platform_operator_acts_total"; + /// Acts refused with 503 because a MUST row could not be written, by operation. public const string AuditFailureCounterName = "learnstack_platform_operator_audit_failures_total"; @@ -40,6 +43,9 @@ public static class PlatformOperatorMetrics private static readonly Counter Results = Meter.CreateCounter(ResultCounterName, description: "MUST result rows committed by operation."); + private static readonly Counter Acts = + Meter.CreateCounter(ActCounterName, description: "Operator onboarding acts by operation and outcome."); + private static readonly Counter AuditFailures = Meter.CreateCounter(AuditFailureCounterName, description: "Operator acts refused because the MUST row was not durable."); @@ -80,7 +86,38 @@ public static void Unauthenticated(string cause) => public static void Result(PlatformOperation operation) => Results.Add(1, new KeyValuePair("operation", operation.AuditSlug)); + /// + /// Counts one onboarding act by how it ended: applied wrote its state, replayed found the state an + /// earlier run of the same act wrote and so is a setup resumed at that step, refused returned a failure + /// result, and failed threw. + /// + public static void Act(PlatformOperation operation, PlatformOperatorActOutcome outcome) => + Acts.Add(1, new KeyValuePair("operation", operation.AuditSlug), + new KeyValuePair("outcome", outcome switch + { + PlatformOperatorActOutcome.Applied => "applied", + PlatformOperatorActOutcome.Replayed => "replayed", + PlatformOperatorActOutcome.Refused => "refused", + _ => "failed", + })); + /// Counts an act that was refused because its MUST row could not be written. public static void AuditFailed(PlatformOperation operation) => AuditFailures.Add(1, new KeyValuePair("operation", operation.AuditSlug)); } + +/// How an onboarding act ended, the closed label set of the act counter. +public enum PlatformOperatorActOutcome +{ + /// The act wrote its state. + Applied = 1, + + /// The act found the state an earlier run wrote and wrote nothing. + Replayed = 2, + + /// The act returned a failure result. + Refused = 3, + + /// The act threw. + Failed = 4, +} diff --git a/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs index c88ff545..931ab77f 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs @@ -59,6 +59,29 @@ public sealed class OperatorActGuard( IUnitOfWork unit, IIdentityMutationLocks locks) { + private int _replayed; + + /// + /// Whether the act found its own earlier result and wrote nothing, so the executor can count a retry + /// apart from a first run (ADR-0102 § 11). + /// + public bool Replayed => Volatile.Read(ref _replayed) != 0; + + /// Records that the act is answering from state a previous run of the same act wrote. + public void MarkReplayed() => Volatile.Write(ref _replayed, 1); + + /// + /// Whether is the live operator act in its own context and transaction, with no lock + /// taken and nothing read, for a handler that must not touch a confined read before it knows it is one. + /// + public Result RequireLiveAct(object request) + { + ArgumentNullException.ThrowIfNull(request); + return context.IsResolved && HasInvocation(execution.CurrentInvocation, request) && HasOwner(context.TenantId) + ? Result.Ok(None.Value) + : RefusedNone(); + } + /// Checks the act and acquires the plan; a refusal is a Problem Details-ready failure. public async Task> AdmitAsync( object request, IdentityMutationLockPlan plan, CancellationToken cancellationToken) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs index b1cb11e7..8ff7e453 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs @@ -22,6 +22,18 @@ internal static class OperatorIdentityFailures internal static Result Unavailable() => Result.Fail(new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + /// + /// What a refused storage write answers, in the vocabulary the sibling Identity handlers already use: a + /// lost race or a lock that timed out is retryable, a missing plan is unavailable, and the rest is the + /// foundation refusing the graph. + /// + internal static Result Storage(IdentityFoundationStorageException failure) => failure.Failure switch + { + IdentityFoundationStorageFailure.Conflict => Result.Fail(new Error(new LocalizedMessage("lockey_concurrency_conflict"))), + IdentityFoundationStorageFailure.Plan => Unavailable(), + _ => Rule("$", "lockey_identity_foundation_refused"), + }; + /// /// A 409 with the reason on the field it concerns. The top-level code stays /// business_rule_violation because the status map is closed and a module-specific code would @@ -68,11 +80,14 @@ public async Task> Handle(OperatorInitializeRoleCommand request, Ca // The same template named again is the same act, so a reply lost on the wire costs nothing. if (await store.FindAsync(id, cancellationToken) is { } existing) { - return existing.TenantId == context.TenantId && existing.BuiltInKey == request.BuiltInKey - && existing.PermissionScope == request.CapabilityScope && existing.CreatedBy == UserId.SystemActor - && existing.MatchesInitialTemplate() - ? Result.Ok(request.RoleId) - : OperatorIdentityFailures.Rule("RoleId", "lockey_identifier_taken"); + // The act is identified by the Role's id, tenant, key, scope and creator. Its grants are not part of + // that: once an administrator exists the template may be edited, and a retry of the original act + // must still find its Role. + if (existing.TenantId != context.TenantId || existing.BuiltInKey != request.BuiltInKey + || existing.PermissionScope != request.CapabilityScope || existing.CreatedBy != UserId.SystemActor) + return OperatorIdentityFailures.Rule("RoleId", "lockey_identifier_taken"); + guard.MarkReplayed(); + return Result.Ok(request.RoleId); } if (await store.HasMembershipHistoryAsync(cancellationToken)) @@ -87,9 +102,9 @@ public async Task> Handle(OperatorInitializeRoleCommand request, Ca await store.ValidateGraphAsync(cancellationToken); return Result.Ok(request.RoleId); } - catch (IdentityFoundationStorageException) + catch (IdentityFoundationStorageException failure) { - return OperatorIdentityFailures.Rule("$", "lockey_identity_foundation_refused"); + return OperatorIdentityFailures.Storage(failure); } catch (IdentityMutationLockException) { @@ -125,6 +140,11 @@ internal static async Task> CreateAsync( if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) return OperatorIdentityFailures.NotFound(); + // The confined resolver is reachable only from inside a live operator act, so the check is made before + // it is called and not left to the lock plan that needs its answer. + if (guard.RequireLiveAct(request) is { IsFailure: true } notLive) + return Result.Fail(notLive.Error); + // The person first: naming a person who has not signed in refuses before any lock or write. if (await subjects.ResolveActiveUserAsync(providerSubject, cancellationToken) is not { } userId || !SeedFoundationGate.ValidUser(userId)) @@ -139,20 +159,24 @@ internal static async Task> CreateAsync( if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) return OperatorIdentityFailures.NotFound(); var id = MembershipId.From(membershipId); - var role = await roles.ReadAsync(RoleId.From(roleId), cancellationToken); - if (!IsAdministratorRole(role, context.TenantId, firstAdmin)) - return OperatorIdentityFailures.Rule("RoleId", "lockey_role_not_initialized"); - // The same act named again finds its Membership, so a reply lost on the wire costs nothing. + // The same act named again finds its Membership, so a reply lost on the wire costs nothing. This is + // asked before the Role's present state is judged: the new administrator may have edited the + // template since, and a retry of the original act must not be refused for that. if (await store.FindAsync(id, cancellationToken) is { } existing) { - return existing.TenantId == context.TenantId && existing.UserId == userId - && existing.OrganizationId is null && existing.Status == MembershipStatus.Active - && existing.RoleAssignments.Any(assignment => assignment.RoleId.Value == roleId) - ? Result.Ok(membershipId) - : OperatorIdentityFailures.Rule("MembershipId", "lockey_identifier_taken"); + if (existing.TenantId != context.TenantId || existing.UserId != userId + || existing.OrganizationId is not null || existing.Status != MembershipStatus.Active + || !existing.RoleAssignments.Any(assignment => assignment.RoleId.Value == roleId)) + return OperatorIdentityFailures.Rule("MembershipId", "lockey_identifier_taken"); + guard.MarkReplayed(); + return Result.Ok(membershipId); } + var role = await roles.ReadAsync(RoleId.From(roleId), cancellationToken); + if (!IsAdministratorRole(role, context.TenantId, firstAdmin)) + return OperatorIdentityFailures.Rule("RoleId", "lockey_role_not_initialized"); + // The act's own predicate, under the locks. The first administrator refuses any Membership // history, so it is not a way to add an administrator to a tenant that has had members; the // recovery refuses while an active tenant-wide administrator exists. @@ -172,9 +196,9 @@ internal static async Task> CreateAsync( await store.ValidateGraphAsync(cancellationToken); return Result.Ok(membershipId); } - catch (IdentityFoundationStorageException) + catch (IdentityFoundationStorageException failure) { - return OperatorIdentityFailures.Rule("$", "lockey_identity_foundation_refused"); + return OperatorIdentityFailures.Storage(failure); } catch (IdentityMutationLockException) { diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs index 18826988..5b5ca5c1 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs @@ -10,5 +10,8 @@ public sealed class add_operator_subject_resolver : Migration { protected override void Up(MigrationBuilder migrationBuilder) => OperatorSubjectResolverDdl.Add(migrationBuilder); - protected override void Down(MigrationBuilder migrationBuilder) => OperatorSubjectResolverDdl.Remove(migrationBuilder); + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0102): like every recent Identity head, the resolver is retired by a reviewed forward + // migration, so a reversal cannot silently remove the confined lookup an operator act depends on. + throw new NotSupportedException("Operator subject resolution requires a reviewed forward migration."); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs index 57d8cc0d..d24e3a92 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs @@ -36,8 +36,4 @@ SELECT u.id INTO found FROM public.users u REVOKE ALL ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) FROM PUBLIC; GRANT EXECUTE ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) TO learnstack_app; """); - - internal static void Remove(MigrationBuilder migration) => migration.Sql(""" - DROP FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea); - """); } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs index 445e565b..72c52bfc 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs @@ -150,11 +150,18 @@ [new LocalizedMessage("lockey_host_reserved")], if (idempotent && await hosts.FindForUpdateAsync(mapping.Host, cancellationToken) is { } existing) { - return existing.OrganizationId == mapping.OrganizationId && existing.IsActive == mapping.IsActive - && existing.IsPubliclyLive == mapping.IsPubliclyLive - ? Result.Ok(new HostMappingDto( - existing.Host, existing.TenantId, existing.OrganizationId, existing.IsActive, existing.IsPubliclyLive)) - : Result.FailFor>(HostTaken()); + if (existing.OrganizationId != mapping.OrganizationId || existing.IsActive != mapping.IsActive + || existing.IsPubliclyLive != mapping.IsPubliclyLive) + { + return Result.FailFor>(HostTaken()); + } + + // The retry is also the repair for the one thing the first run could not guarantee: a miss + // cached between its invalidation and its commit. Dropping the entry again is idempotent. + await resolutionCache.InvalidateAsync(mapping.Host, cancellationToken); + operatorGuard.MarkReplayed(); + return Result.Ok(new HostMappingDto( + existing.Host, existing.TenantId, existing.OrganizationId, existing.IsActive, existing.IsPubliclyLive)); } try diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs index 49597297..27285699 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs @@ -120,16 +120,27 @@ public async Task> Handle( request, new IdentityMutationLockPlan([], request.TenantId, IdentityTenantLockMode.Exclusive), cancellationToken); if (admission.IsFailure) return Result.Fail(admission.Error); - // The act is idempotent on the pair (id, slug), so a reply lost on the wire costs nothing: the - // tenant is already there and the same pair finds it. A known slug under another id is the - // database's own answer, below, because row security hides another tenant's row from this read. + // An exact repeat of the act is the answer, and anything else under the same id is a different + // request: a reply lost on the wire costs nothing, and a retry that changes a value is refused + // rather than silently answered with a record it did not describe. The comparison reads the stored + // Organization, so the answer is what was written and never an echo of the request. A known slug + // under another id is the database's own answer, below, because row security hides another + // tenant's row from this read. var existing = await tenants.FindAsync(request.TenantId, cancellationToken); if (existing is not null) { - return existing.Slug == request.Slug && existing.DefaultOrganizationId == request.DefaultOrganizationId - ? Result.Ok(new ProvisionedTenantDto( - request.TenantId, existing.Slug, request.DefaultOrganizationId, request.DefaultOrganizationSlug)) - : Result.FailFor>(TakenFor(nameof(OperatorProvisionTenantCommand.TenantId))); + var organization = existing.DefaultOrganizationId == request.DefaultOrganizationId + ? await organizations.FindForUpdateAsync(request.DefaultOrganizationId, cancellationToken) + : null; + if (organization is null || existing.Slug != request.Slug || existing.DisplayName != request.DisplayName + || organization.Slug != request.DefaultOrganizationSlug + || organization.DisplayName != request.DefaultOrganizationDisplayName) + { + return Result.FailFor>(TakenFor(nameof(OperatorProvisionTenantCommand.TenantId))); + } + + operatorGuard.MarkReplayed(); + return Result.Ok(new ProvisionedTenantDto(request.TenantId, existing.Slug, organization.Id, organization.Slug)); } try diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 8adedabb..0cf7c202 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -102,6 +102,7 @@ private static readonly (string Owner, string Method, int Count)[] CurrentInvoca (SeedTenancyGuard, "RequireCurrent", 1), (OperatorActGuard, "AdmitAsync", 1), (OperatorActGuard, "RequireCurrent", 1), + (OperatorActGuard, "RequireLiveAct", 1), (SeedTenancyGuard, "AllowsIdentityContinuationAsync", 1), (SeedTenancyGuard, "AllowsContentContinuationAsync", 1), (SeedTenancyGuard, "g__Current|14_0", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index cc1b070a..00dced9d 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -223,6 +223,23 @@ public void Only_The_Operator_Services_Hold_The_Platform_Scope() "each new operator service is added here deliberately, with its denied proof"); } + [Fact] + public void Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act() + { + // ADR-0102: the executor is the one place an operator's tenant reaches the pipeline, and an admission is + // the only thing that lets it run. The files that name it in code are the executor, the registration beside + // the source it enters and the onboarding routes, and nothing else: a second caller is a second route to an + // act, and is added here deliberately with its own denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorActExecutor", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs", + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs", + ], + "each new caller of an operator act is added here deliberately, with its denied proof"); + } + private const string KillswitchWriterFile = "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs index 02cdde90..9d090183 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs @@ -174,7 +174,7 @@ public void SetTenant_Callers_Are_The_Enumerated_Four() // handler scope (integration events). HTTP and the acceptance/execution // halves of the integration-event scope and the job executor exist today; // the rule is written over the whole set so the next writer is a deliberate edit here rather - // than a silent addition there. The operator act executor (ADR-0102, ADR-0036 Amendment 3) + // than a silent addition there. The operator act executor (ADR-0102, ADR-0036 Amendment 22) // is that deliberate edit: a fifth logical writer, which installs the resolved context // of the tenant an admitted operator act names. The method keeps the name three Accepted // ADRs and the catalogue cite. diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index f11a4e3f..1a36cf5e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -211,6 +211,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() recoveryAnchor.Should().Throw().WithMessage("Provider recovery continuity requires a forward repair."); Action collision = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.classify_retained_provider_collision().DownOperations; collision.Should().Throw().WithMessage("Provider receipt collision classification requires a forward repair."); + Action federation = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_federation_connections().DownOperations; + federation.Should().Throw().WithMessage("Federation connection storage requires a reviewed forward migration."); Action releaseV4 = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.role_registry_release_v4().DownOperations; releaseV4.Should().Throw().WithMessage("Role release adoption requires a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] @@ -219,8 +221,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), (platform, "20261105020229_lock_invitation_envelope_parent", PlatformReversibleHead, "20261110013140_add_custom_field_protected_receipts", "Retained custom field receipts require a reviewed forward migration."), - (identity, "20261113114919_role_registry_release_v4", IdentityReversibleHead, - "20261113120259_add_federation_connections", "Federation connection storage requires a reviewed forward migration."), + (identity, "20261113120259_add_federation_connections", IdentityReversibleHead, + "20261119140000_add_operator_subject_resolver", "Operator subject resolution requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, "20261109230218_membership_custom_field_definitions", "Retained custom field definitions require a reviewed forward migration."), }) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs index d83abb2a..79111a24 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs @@ -50,6 +50,9 @@ public async Task The_Definer_Refuses_Every_Caller_And_Argument_It_Does_Not_Admi (await proof.RefusalAsync(key: key, announceTenant: false)).Should().Be("23514", "no tenant announcement"); (await proof.RefusalAsync(key: key, readOnly: true)).Should().Be("23514", "a read-only transaction"); (await proof.RefusalAsync(key: key, asOwner: true)).Should().Be("23514", "a session that is not the application role"); + (await proof.RefusalAsync(key: key, repeatableRead: true)).Should().Be("23514", "a transaction that is not READ COMMITTED"); + (await proof.RefusalAsync(key: key, nullAuthority: true)).Should().Be("23514", "a null authority"); + (await proof.RefusalAsync(nullKey: true)).Should().Be("23514", "a null key"); (await proof.RefusalAsync(key: key)).Should().BeNull("the control: the same call, admitted"); } @@ -103,11 +106,13 @@ internal byte[] Key(string subject) => /// The SQLSTATE the definer raises for the call, or null when it answers. internal async Task RefusalAsync( - Guid? authority = null, byte[]? key = null, bool announceTenant = true, bool readOnly = false, bool asOwner = false) + Guid? authority = null, byte[]? key = null, bool announceTenant = true, bool readOnly = false, bool asOwner = false, + bool repeatableRead = false, bool nullAuthority = false, bool nullKey = false) { await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync( asOwner ? _database.MigrationConnectionString : _database.AppConnectionString); - await using var transaction = await connection.BeginTransactionAsync(); + await using var transaction = await connection.BeginTransactionAsync( + repeatableRead ? System.Data.IsolationLevel.RepeatableRead : System.Data.IsolationLevel.ReadCommitted); if (readOnly) { await IdentityMembershipFixture.ExecuteAsync(connection, transaction, "SET TRANSACTION READ ONLY"); @@ -122,6 +127,8 @@ internal byte[] Key(string subject) => { await using var command = Command( connection, transaction, authority ?? _database.Registration.AuthorityId.Value, key ?? Key(Subject)); + if (nullAuthority) command.Parameters["authority"].Value = DBNull.Value; + if (nullKey) command.Parameters["key"].Value = DBNull.Value; await command.ExecuteScalarAsync(); return null; } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs index ced27268..aeeaa6de 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs @@ -1,9 +1,16 @@ +using System.Diagnostics.Metrics; using System.Net; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using FluentAssertions; +using LearnStack.Modules.Tenancy.Application.Abstractions; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.Extensions.DependencyInjection; using LearnStack.SharedKernel.Platform; using Microsoft.AspNetCore.Hosting; using Npgsql; @@ -40,6 +47,7 @@ public sealed class PlatformOperatorOnboardingTests(PublicReadFixture parent) public async Task An_Operator_Onboards_A_Tenant_Step_By_Step_And_Every_Act_Is_Audited_And_Repeatable() { await using var proof = await Proof.CreateAsync(parent); + using var outcomes = new ActOutcomes(); var tenant = Ids.Next(); var organization = Ids.Next(); var role = Ids.Next(); @@ -50,10 +58,31 @@ public async Task An_Operator_Onboards_A_Tenant_Step_By_Step_And_Every_Act_Is_Au // Provision, and send the same act again. var provision = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization)); await AssertOkAsync(provision); + using (var answered = JsonDocument.Parse(await provision.Content.ReadAsStringAsync())) + { + var correlation = answered.RootElement.GetProperty("correlationId").GetString(); + (await proof.CorrelationIdsAsync(tenant, "tenancy.tenant.create")).Should().Contain(correlation, + "the runbook finds an act's rows by the correlation id its answer returned"); + } + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); (await proof.CountAsync(tenant, "tenants")).Should().Be(1); (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + // An exact repeat answers from what was stored; a repeat that changes any value is a different request. + using (var repeat = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))) + { + using var body = JsonDocument.Parse(await repeat.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("result").GetProperty("defaultOrganizationSlug").GetString().Should().Be("main"); + } + + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization, displayName: "Renamed")), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization, organizationSlug: "elsewhere")), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + // The first administrator needs the role and the person first; each refusal writes nothing. await AssertRuleAsync( await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject)), @@ -74,9 +103,20 @@ await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, " // The host mapping, then again. var mapped = await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}"""); await AssertOkAsync(mapped); + proof.Invalidations.Should().Equal([host], "the first run drops any cached answer for the host"); await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}""")); + proof.Invalidations.Should().Equal([host, host], "the retry drops it again, which is the repair for a miss cached before the commit"); (await proof.HostMappingsAsync(host)).Should().Equal(tenant); + // How each act ended, as the monitoring owner sees it: four first runs, five repeats that found their own + // earlier result (the provisioning twice and each of the others once) and four refusals. + outcomes.Counts.Should().Equal(new Dictionary + { + ["applied"] = 4, + ["replayed"] = 5, + ["refused"] = 4, + }); + // Who the business columns name, and what the audit rows say. (await proof.ScalarAsync(tenant, "SELECT created_by FROM public.memberships")).Should().Be(UserId.SystemActor.Value); (await proof.ScalarAsync(tenant, "SELECT user_id FROM public.memberships")).Should().Be(proof.Person.Value); @@ -85,9 +125,11 @@ await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, " ["tenancy.tenant.create", "tenancy.organization.create", "identity.role.initialize", "identity.membership.create_first_admin", "tenancy.hostmapping.write"]); audit.Should().OnlyContain(row => row.ActorUserId == null, "an operator act names no tenant user; the operator is in metadata"); - audit.Where(row => row.Outcome == "failed").Select(row => row.Operation).Should().Equal( - ["identity.membership.create_first_admin", "identity.membership.create_first_admin"], - "the two refused first-administrator attempts are recorded as the failures they were, and nothing else failed"); + audit.Where(row => row.Outcome == "failed").Select(row => row.Operation).Should().BeEquivalentTo( + ["identity.membership.create_first_admin", "identity.membership.create_first_admin", + "tenancy.tenant.create", "tenancy.organization.create", "tenancy.tenant.create", "tenancy.organization.create"], + "the two refused first-administrator attempts and the two changed provisioning repeats are recorded as the " + + "failures they were, and nothing else failed"); audit.Should().OnlyContain(row => row.Metadata.Contains(proof.Operator.Issuer, StringComparison.Ordinal), "every row carries the admitted operator's issuer"); audit.Should().OnlyContain(row => !row.Metadata.Contains(proof.PersonSubject, StringComparison.Ordinal) @@ -95,6 +137,17 @@ await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, " audit.Should().OnlyContain(row => !row.Metadata.Contains("INC-77", StringComparison.Ordinal), "the ticket stays out of rows a tenant can read"); audit.Select(row => row.Reason).Distinct().Should().BeEquivalentTo( ["tenant_provision", "role_initialize", "first_admin_create", "host_map"]); + foreach (var row in audit) + { + using var metadata = JsonDocument.Parse(row.Metadata); + var @operator = metadata.RootElement.GetProperty("operator"); + @operator.GetProperty("issuer").GetString().Should().Be(proof.Operator.Issuer); + @operator.GetProperty("acr").GetString().Should().Be("mfa"); + @operator.GetProperty("kind").GetString().Should().Be("human"); + @operator.GetProperty("executor").GetString().Should().NotBeNullOrWhiteSpace(); + @operator.GetProperty("subjectDigest").GetString().Should().MatchRegex("^[A-Za-z0-9_-]{43}$"); + metadata.RootElement.GetProperty("authorization").GetProperty("source").GetString().Should().Be("operator"); + } } [Fact] @@ -129,7 +182,7 @@ public async Task An_Act_On_A_Tenant_That_Does_Not_Exist_Is_Not_Found_And_A_Take await using var proof = await Proof.CreateAsync(parent); var missing = Ids.Next(); - (await proof.PutAsync(Full, $"/tenants/{missing}/host-mappings/missing.example.test", "{}")).StatusCode + (await proof.PutAsync(Full, $"/tenants/{missing}/host-mappings/missing.example.test", LiveFlags)).StatusCode .Should().Be(HttpStatusCode.NotFound); (await proof.PutAsync(Full, $"/tenants/{missing}/roles/{Ids.Next()}", RoleBody())).StatusCode .Should().Be(HttpStatusCode.NotFound); @@ -165,7 +218,8 @@ public async Task Identifiers_That_Are_Not_UuidV7_Are_Refused_Before_Any_Write() .Should().Be(HttpStatusCode.BadRequest); (await proof.PutAsync(Full, RecoveryPath(tenant, v4), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode .Should().Be(HttpStatusCode.BadRequest); - (await proof.CountAsync(Ids.Next(), "tenants")).Should().Be(0); + (await proof.CountAsync(v4, "tenants")).Should().Be(0); + (await proof.CountAsync(tenant, "tenants")).Should().Be(0); } [Fact] @@ -184,6 +238,153 @@ await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, p (await proof.CountAsync(tenant, "memberships")).Should().Be(0); } + [Fact] + public async Task A_Reply_Lost_After_The_Commit_Is_Answered_By_Sending_The_Same_Request_Again() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "lost-" + Ids.Short(); + using var lossy = proof.ClientWith(services => services.Insert(0, ServiceDescriptor.Scoped< + IPipelineBehavior>, LoseTheReplyAfterTheCommit>())); + + using var lost = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization), lossy); + + lost.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the act committed and the operator was told it failed"); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1, "the commit is real whatever the operator was told"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + (await proof.AuditAsync(tenant)).Count(row => row.Operation == "tenancy.tenant.create" && row.Outcome == "success") + .Should().Be(2, "the first run wrote the create; the retry is recorded as the repeated act it is, without a second tenant"); + } + + [Fact] + public async Task An_Act_Interrupted_Between_Its_Writes_Leaves_Nothing_And_The_Retry_Completes_Once() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "cut-" + Ids.Short(); + using var failing = proof.ClientWith(services => + { + var registered = services.Last(descriptor => descriptor.ServiceType == typeof(ITenantWriteStore)); + services.Remove(registered); + services.AddScoped(provider => new FailTheLastWrite((ITenantWriteStore)( + registered.ImplementationFactory?.Invoke(provider) + ?? ActivatorUtilities.CreateInstance(provider, registered.ImplementationType!)))); + }); + + using var cut = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization), failing); + + cut.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await proof.CountAsync(tenant, "tenants")).Should().Be(0, "the tenant and organization inserts rolled back with the act"); + (await proof.CountAsync(tenant, "organizations")).Should().Be(0); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + } + + [Fact] + public async Task The_Platform_Sentinel_And_A_Malformed_Request_Are_Refused_With_The_Status_An_Operator_Can_Act_On() + { + await using var proof = await Proof.CreateAsync(parent); + var sentinel = TenantId.PlatformSentinel.Value; + var tenant = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("shape-" + Ids.Short(), Ids.Next()))); + + (await proof.PutAsync(Full, $"/tenants/{sentinel}/roles/{Ids.Next()}", RoleBody())).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the sentinel is the platform's own tenant and no act may name it"); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(Ids.Next(), " "))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "a blank subject is a malformed request"); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(Ids.Next(), new string('x', 256)))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "a subject over 255 characters is a malformed request"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", + """{"builtInKey":"TenantAdmin","capabilityScope":"Tenant","ticket":"has a space"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the ticket grammar is enforced at the gate"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", "{ not json")).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", """{"builtInKey":"Nobody","capabilityScope":"Tenant"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "an unknown template key is refused before any act"); + (await proof.SendAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", new StringContent(RoleBody(), Encoding.UTF8, "text/plain"))).StatusCode + .Should().Be(HttpStatusCode.UnsupportedMediaType); + (await proof.CountAsync(tenant, "roles")).Should().Be(0); + } + + [Fact] + public async Task A_Host_Mapping_States_Both_Flags_And_Refuses_A_Host_Another_Tenant_Holds_And_A_Foreign_Organization() + { + await using var proof = await Proof.CreateAsync(parent); + var first = Ids.Next(); + var second = Ids.Next(); + var secondOrganization = Ids.Next(); + var host = "shared-" + Ids.Short() + ".example.test"; + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody("one-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{second}", ProvisionBody("two-" + Ids.Short(), secondOrganization))); + + // No unmap act exists, so a mapping never arrives serving traffic because a field was left out. + (await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", "{}")).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", """{"isActive":true}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.HostMappingsAsync(host)).Should().BeEmpty(); + + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", LiveFlags)); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{second}/host-mappings/{host}", LiveFlags), + HttpStatusCode.Conflict, "lockey_host_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":false}"""), + HttpStatusCode.Conflict, "lockey_host_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/other-{Ids.Short()}.example.test", + JsonSerializer.Serialize(new { organizationId = secondOrganization, isActive = true, isPubliclyLive = true })), + HttpStatusCode.Conflict, "lockey_organization_not_in_tenant"); + (await proof.HostMappingsAsync(host)).Should().Equal(first); + } + + [Fact] + public async Task Organization_Scope_Templates_Are_Initialized_And_Only_A_Tenant_Administrator_Role_Of_This_Tenant_Can_Administer() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var other = Ids.Next(); + var adminRole = Ids.Next(); + var orgAdminRole = Ids.Next(); + var otherRole = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("scoped-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{other}", ProvisionBody("other-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{adminRole}", RoleBody())); + await AssertOkAsync(await proof.PutAsync( + Full, $"/tenants/{tenant}/roles/{orgAdminRole}", """{"builtInKey":"OrgAdmin","capabilityScope":"Organization"}""")); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{other}/roles/{otherRole}", RoleBody())); + (await proof.CountAsync(tenant, "roles")).Should().Be(2); + + // An Organization-scope administrator template and another tenant's administrator template are not this + // tenant's tenant-wide administrator Role. + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(orgAdminRole, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(otherRole, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(adminRole, proof.PersonSubject))); + } + + [Fact] + public async Task A_Retry_Of_The_First_Administrator_Still_Answers_After_The_Role_Template_Was_Edited() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, membership) = await proof.OnboardAsync(Full); + await proof.EditRoleOutsideTheActsAsync(tenant, role); + + // The administrator edited the template after the first run, so it is no longer the pristine one the + // act created; the retry of the original act must still find its Membership and answer. + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + } + [Fact] public async Task The_First_Administrator_Is_Refused_Once_A_Tenant_Has_Had_Any_Member() { @@ -275,13 +476,16 @@ await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(learnerRo (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(0); } - private static string ProvisionBody(string slug, Guid organization) => JsonSerializer.Serialize(new - { - slug, - displayName = "Onboarded " + slug, - defaultOrganization = new { id = organization, slug = "main", displayName = "Main" }, - ticket = "INC-77", - }); + private const string LiveFlags = """{"isActive":true,"isPubliclyLive":true}"""; + + private static string ProvisionBody(string slug, Guid organization, string? displayName = null, string organizationSlug = "main") => + JsonSerializer.Serialize(new + { + slug, + displayName = displayName ?? "Onboarded " + slug, + defaultOrganization = new { id = organization, slug = organizationSlug, displayName = "Main" }, + ticket = "INC-77", + }); private static string RoleBody() => """{"builtInKey":"TenantAdmin","capabilityScope":"Tenant","ticket":"INC-77"}"""; @@ -319,10 +523,13 @@ private sealed class Proof : IAsyncDisposable { private readonly HttpClient _client; private readonly Dictionary _tokens = []; + private readonly List _extraClients = []; private Proof(TenantAuthenticationIssuer tenantIssuer, TenantAuthenticationIssuer @operator, - IdentityPublicReadFixture database, UserId person, string personSubject, HttpClient client) + IdentityPublicReadFixture database, UserId person, string personSubject, HttpClient client, + List invalidations) { + Invalidations = invalidations; TenantIssuer = tenantIssuer; Operator = @operator; Database = database; @@ -341,6 +548,9 @@ private Proof(TenantAuthenticationIssuer tenantIssuer, TenantAuthenticationIssue internal string PersonSubject { get; } + /// The hosts whose cached resolution the acts dropped, in order. + internal List Invalidations { get; } + internal static async Task CreateAsync(PublicReadFixture parent) { var tenantIssuer = await TenantAuthenticationIssuer.StartAsync(); @@ -349,12 +559,15 @@ internal static async Task CreateAsync(PublicReadFixture parent) var subject = "onboarding-person-" + person.Value.ToString("N"); IdentityPublicReadFixture? database = null; HttpClient? client = null; + var invalidations = new List(); try { database = await IdentityPublicReadFixture.CreateAsync( parent, tenantIssuer.Issuer, new Dictionary { [person] = subject }); - client = database.ClientFor("localhost", configureHost: ConfigureOperator(@operator)); - return new Proof(tenantIssuer, @operator, database, person, subject, client); + client = database.ClientFor("localhost", + services => services.AddSingleton(new RecordingInvalidator(invalidations)), + ConfigureOperator(@operator)); + return new Proof(tenantIssuer, @operator, database, person, subject, client, invalidations); } catch { @@ -387,7 +600,22 @@ private static Action ConfigureOperator(TenantAuthenticationIss } }; - internal async Task PutAsync(string operatorSubject, string path, string json) + /// + /// A second host over the same database whose services changes, for the cases + /// that make an act fail where the production code would not. + /// + internal HttpClient ClientWith(Action configure) + { + var client = Database.ClientFor("localhost", configure, ConfigureOperator(Operator)); + _extraClients.Add(client); + return client; + } + + internal async Task PutAsync(string operatorSubject, string path, string json, HttpClient? client = null) => + await SendAsync(operatorSubject, path, new StringContent(json, Encoding.UTF8, "application/json"), client); + + internal async Task SendAsync( + string operatorSubject, string path, HttpContent content, HttpClient? client = null) { if (!_tokens.TryGetValue(operatorSubject, out var token)) { @@ -409,9 +637,29 @@ internal async Task PutAsync(string operatorSubject, string using var request = new HttpRequestMessage(HttpMethod.Put, "/api/platform/v1" + path) { Headers = { Authorization = new AuthenticationHeaderValue("Bearer", token) }, - Content = new StringContent(json, Encoding.UTF8, "application/json"), + Content = content, }; - return await _client.SendAsync(request); + return await (client ?? _client).SendAsync(request); + } + + /// The correlation ids of the audit rows of one operation in the tenant. + internal async Task> CorrelationIdsAsync(Guid tenant, string operation) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand( + "SELECT correlation_id FROM public.audit_log WHERE operation=@operation", app, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var reader = await command.ExecuteReaderAsync(); + var ids = new List(); + while (await reader.ReadAsync()) + { + ids.Add(reader.GetString(0)); + } + + return ids; } /// A person who has signed in, so the first-sign-in bootstrap has bound them. @@ -445,6 +693,23 @@ ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR await transaction.CommitAsync(); } + /// + /// A later edit of the Role by its owner, which bumps the row version the way an administrator's edit does, with + /// the same locks a handler would take. + /// + internal async Task EditRoleOutsideTheActsAsync(Guid tenant, Guid role) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await IdentityMembershipFixture.LockAsync(app, transaction, tenant, null, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, + "UPDATE public.roles SET row_version=row_version+1, updated_at=clock_timestamp(), updated_by=@actor WHERE id=@role", + ("actor", UserId.SystemActor.Value), ("role", role)); + await transaction.CommitAsync(); + } + /// The whole onboarding through the real routes; returns the tenant, its role and its first membership. internal async Task<(Guid Tenant, Guid Role, Guid Membership)> OnboardAsync(string operatorSubject) { @@ -551,10 +816,101 @@ await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ public async ValueTask DisposeAsync() { + foreach (var extra in _extraClients) + { + extra.Dispose(); + } + _client.Dispose(); await Database.DisposeAsync(); await Operator.DisposeAsync(); await TenantIssuer.DisposeAsync(); } } + + /// Counts the outcome label of every onboarding act counted while it is alive. + private sealed class ActOutcomes : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly Dictionary _counts = []; + + public ActOutcomes() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.ActCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "outcome", Value: string outcome }) + { + lock (_counts) + { + _counts[outcome] = _counts.GetValueOrDefault(outcome) + 1; + } + } + } + }); + _listener.Start(); + } + + public IReadOnlyDictionary Counts + { + get + { + lock (_counts) + { + return new Dictionary(_counts); + } + } + } + + public void Dispose() => _listener.Dispose(); + } + + private sealed class RecordingInvalidator(List hosts) : IHostResolutionInvalidator + { + public Task InvalidateAsync(string normalizedHost, CancellationToken cancellationToken = default) + { + hosts.Add(normalizedHost); + return Task.CompletedTask; + } + } + + /// A reply lost after the commit: the outermost behavior fails once the whole act, commit included, is done. + private sealed class LoseTheReplyAfterTheCommit + : IPipelineBehavior> + { + public async Task> Handle( + OperatorProvisionTenantCommand request, + RequestHandlerDelegate> next, + CancellationToken cancellationToken) + { + await next(); + throw new InvalidOperationException("The reply was lost after the commit."); + } + } + + /// The tenant store with its third write, the default-organization back-reference, failing. + private sealed class FailTheLastWrite(ITenantWriteStore inner) : ITenantWriteStore + { + public Task AddAsync(LearnStack.Modules.Tenancy.Domain.Tenant aggregate, CancellationToken cancellationToken = default) => + inner.AddAsync(aggregate, cancellationToken); + + public Task UpdateAsync(LearnStack.Modules.Tenancy.Domain.Tenant aggregate, CancellationToken cancellationToken = default) => + throw new InvalidOperationException("The act was interrupted between its writes."); + + public Task FindAsync(TenantId id, CancellationToken cancellationToken = default) => + inner.FindAsync(id, cancellationToken); + + public Task FindForUpdateAsync(TenantId id, CancellationToken cancellationToken = default) => + inner.FindForUpdateAsync(id, cancellationToken); + } } + diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs index db2a2f7c..85b693eb 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs @@ -9,7 +9,9 @@ using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Platform; @@ -223,6 +225,80 @@ await rig.RunAsync(request, async () => rig.Unit.Received(1).MarkRollbackOnly(); } + [Fact] + public async Task The_Live_Act_Check_Answers_Without_Taking_A_Lock() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, () => + { + rig.Guard.RequireLiveAct(request).IsSuccess.Should().BeTrue(); + rig.Guard.RequireLiveAct(Request()).IsFailure.Should().BeTrue("another request object is not this invocation's"); + return Task.FromResult(Result.Ok(None.Value)); + }); + + rig.Guard.RequireLiveAct(request).IsFailure.Should().BeTrue("outside an invocation there is no live act"); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("user")] + [InlineData("organization")] + [InlineData("host")] + [InlineData("unresolved")] + public async Task The_Live_Act_Check_Refuses_A_Context_That_Is_Not_The_Tenants_Ambient_One(string change) + { + using var rig = new Rig(); + var request = Request(); + Apply(rig, change); + var refused = false; + + await rig.RunAsync(request, () => + { + refused = rig.Guard.RequireLiveAct(request).IsFailure; + return Task.FromResult(Result.Ok(None.Value)); + }); + + refused.Should().BeTrue(); + } + + [Fact] + public void A_Replay_Is_Recorded_On_The_Guard_And_Starts_Unrecorded() + { + using var rig = new Rig(); + + rig.Guard.Replayed.Should().BeFalse(); + rig.Guard.MarkReplayed(); + rig.Guard.Replayed.Should().BeTrue(); + } + + [Theory] + [InlineData(AuthorizationSourceKind.PlatformOperator, false)] + [InlineData(AuthorizationSourceKind.Seed, true)] + public async Task An_Authorization_Refusal_Of_An_Operator_Act_Writes_No_Durable_Denial_Row_Unlike_Any_Other_Source( + AuthorizationSourceKind source, bool writes) + { + // ADR-0033 Amendment 14. The control is the seed source, which records the same refusal, so the empty + // answer for the operator is the coordinator's decision and not a fixture that cannot write. + using var rig = new Rig { SourceKind = source }; + OperatorProvisionTenantCommand operatorRequest = Request(); + var seedRequest = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + await using var execution = rig.Evidence.BeginExecution(); + + Task> Refuse(object request) => rig.RunAsync(request, () => + { + rig.Evidence.RecordPolicyRefusal(rig.CurrentInvocation!, null, new Error(new LocalizedMessage("lockey_forbidden"))); + return Task.FromResult(Result.Fail(new Error(new LocalizedMessage("lockey_forbidden")))); + }); + + await (source == AuthorizationSourceKind.PlatformOperator ? Refuse(operatorRequest) : Refuse(seedRequest)); + await rig.Evidence.BeforeOwnerCompletionAsync(rig.Unit, CancellationToken.None); + await rig.Evidence.BeforeSuccessAsync(CancellationToken.None); + + (rig.EvidenceWrites().Length > 0).Should().Be(writes); + } + [Fact] public async Task A_Plan_For_Another_Tenant_Is_Not_Held_For_This_Act() { @@ -269,17 +345,27 @@ public Rig() var clock = Substitute.For(); clock.UtcNow.Returns(Now); OperationAuthorizationCoordinator? current = null; - var evidence = new AuthorizationEvidenceCoordinator( - Substitute.For(), new AuditStateCapture(), Unit, clock, new SystemGuidFactory(), + Evidence = new AuthorizationEvidenceCoordinator( + Store, new AuditStateCapture(), Unit, clock, new SystemGuidFactory(), () => current!, [], NullLogger.Instance); _coordinator = current = new OperationAuthorizationCoordinator( new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()]), - Substitute.For(), Context, [], [Source], evidence); + Substitute.For(), Context, [], [Source], Evidence); Guard = new OperatorActGuard(_coordinator, Context, Unit, Locks); } public ITenantContext Context { get; } = Substitute.For(); + public IAuditStore Store { get; } = Substitute.For(); + + public AuthorizationEvidenceCoordinator Evidence { get; } + + public OperationInvocation? CurrentInvocation => _coordinator.CurrentInvocation; + + /// The authorization-evidence writes the store was asked for, by method name. + public string[] EvidenceWrites() => [.. Store.ReceivedCalls() + .Select(call => call.GetMethodInfo().Name).Where(name => name.StartsWith("WriteAuthorization", StringComparison.Ordinal))]; + public IGlobalIdentityUnitOfWork GlobalUnit { get; } = Substitute.For(); public IUnitOfWork Unit => GlobalUnit; diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs index e9e5ecb3..36bf31fe 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs @@ -1,11 +1,16 @@ +using System.Diagnostics.Metrics; using FluentAssertions; using LearnStack.Application.Authorization; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Identity.Application; using LearnStack.Modules.Tenancy.Application.Authorization; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; @@ -13,6 +18,7 @@ using LearnStack.Tests.Fixtures; using MediatR; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using NSubstitute; using Xunit; @@ -192,6 +198,43 @@ public async Task One_Admission_Admits_One_Act() rig.Observed.Should().ContainSingle("the second act never reached the pipeline"); } + [Fact] + public async Task Each_Act_Is_Counted_By_How_It_Ended() + { + using var counted = new ActCounter(); + await using var rig = new Rig(); + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Replay = true; + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Replay = false; + rig.Refusal = new Error(new LocalizedMessage("lockey_business_rule_violation")); + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Refusal = null; + rig.Failure = new InvalidOperationException("handler failed"); + var failed = () => rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + await failed.Should().ThrowAsync(); + + counted.Outcomes.Should().Equal( + ["tenancy.tenant.create:applied", "tenancy.tenant.create:replayed", "tenancy.tenant.create:refused", "tenancy.tenant.create:failed"]); + } + + [Fact] + public async Task An_Admitted_Act_The_Pipeline_Refuses_As_Forbidden_Is_Logged_As_A_Defect() + { + await using var rig = new Rig(); + rig.Refusal = new Error(new LocalizedMessage("lockey_forbidden")); + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + rig.LoggedEvents.Should().Equal([7109], "the warning an operator can alert on, since this refusal writes no audit row"); + } + [Fact] public void The_Act_Catalog_Refuses_An_Operation_That_Needs_The_Platform_Role_Or_No_Acts_At_All() { @@ -231,6 +274,11 @@ public Rig() services.AddSingleton( new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()])); services.AddSingleton(clock); + services.AddSingleton(typeof(ILogger<>), typeof(CapturingLogger<>)); + services.AddSingleton(LoggedEvents); + services.AddScoped(_ => new OperatorActGuard( + Substitute.For(), Substitute.For(), + Substitute.For(), Substitute.For())); services.AddPlatformOperatorActs(catalog); services.AddScoped(provider => { @@ -244,9 +292,19 @@ public Rig() context, source, descriptor, descriptor?.Matches(typeof(OperatorProvisionTenantCommand), context) ?? false, Probe?.Invoke(source, context) ?? [])); - return Failure is null - ? Task.FromResult(Result.Ok(new ProvisionedTenantDto(Tenant, "acme", OrganizationId.From(Guid.CreateVersion7()), "main"))) - : Task.FromException>(Failure); + if (Replay) + { + provider.GetRequiredService().MarkReplayed(); + } + + if (Failure is not null) + { + return Task.FromException>(Failure); + } + + return Task.FromResult(Refusal is { } refusal + ? Result.FailFor>(refusal) + : Result.Ok(new ProvisionedTenantDto(Tenant, "acme", OrganizationId.From(Guid.CreateVersion7()), "main"))); }); return sender; }); @@ -262,8 +320,61 @@ public Rig() public Exception? Failure { get; set; } + public bool Replay { get; set; } + + public Error? Refusal { get; set; } + + public List LoggedEvents { get; } = []; + public Func>? Probe { get; set; } public ValueTask DisposeAsync() => _provider.DisposeAsync(); } + + private sealed class CapturingLogger(List events) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + events.Add(eventId.Id); + } + + /// Records the operation:outcome of every act counted while it is alive. + private sealed class ActCounter : IDisposable + { + private readonly MeterListener _listener = new(); + + public ActCounter() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == PlatformOperatorMetrics.ActCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value as string; + if (tag.Key == "outcome") outcome = tag.Value as string; + } + + lock (Outcomes) + { + Outcomes.Add(operation + ":" + outcome); + } + }); + _listener.Start(); + } + + public List Outcomes { get; } = []; + + public void Dispose() => _listener.Dispose(); + } } diff --git a/docs/decisions/0033-audit-durability-model.md b/docs/decisions/0033-audit-durability-model.md index d95a8181..964ccfd7 100644 --- a/docs/decisions/0033-audit-durability-model.md +++ b/docs/decisions/0033-audit-durability-model.md @@ -880,13 +880,14 @@ Amendment 12 makes an authorization refusal a MUST `identity.authorization.deny` For the `PlatformOperator` source of [ADR-0102](0102-production-tenant-onboarding.md) the authorization evidence coordinator writes none, in either of its denial paths. Operator refusals follow the decision [ADR-0101](0101-platform-operator-authority.md) § -11 records for denied entry: a counter and a log line by closed cause at the gate, and -the act's own refusal response, with no durable row. Inside an admitted act an -authorization refusal can only mean the request, source or context was not what the -executor built, and the act fails closed with the response. The pipeline's other rows -are unchanged: a business refusal of an admitted act writes the ordinary `failed` MUST -row in the target tenant with `metadata.operator`, and a success writes its MUST rows in -the act's own transaction. Every other source keeps Amendment 12 as written. +11 records for denied entry: a counter and a log line by closed cause at the gate. An +authorization refusal inside an admitted act can only mean the request, source or +context was not what the executor built; the executor counts the act as `refused`, logs +event 7109 as a Warning, and the act fails closed with its response, with no durable +row. The pipeline's other rows are unchanged: a business refusal of an admitted act +writes the ordinary `failed` MUST row in the target tenant with `metadata.operator`, and +a success writes its MUST rows in the act's own transaction. Every other source keeps +Amendment 12 as written. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0036-tenant-resolution-trusted-inputs.md b/docs/decisions/0036-tenant-resolution-trusted-inputs.md index f4361580..a6692bb9 100644 --- a/docs/decisions/0036-tenant-resolution-trusted-inputs.md +++ b/docs/decisions/0036-tenant-resolution-trusted-inputs.md @@ -1409,6 +1409,14 @@ and qualification; acceptance alone installs no runtime subject. ### Amendment 21 — Platform URL space and confined operator target (2026-11-19) +> **Erratum — 2026-11-19.** The second paragraph below says the target tenant of an +> admitted operator act is announced "by one confined setter". No setter was added: the +> operator act executor installs a resolved ambient context for the target and the +> ordinary transaction behavior announces it; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` and `PlatformOperatorActExecutorTests`. +> The Decision is unchanged. Current authority: Amendment 22 below. Recorded in +> Amendment 22. + Accepted [ADR-0101](0101-platform-operator-authority.md) fixes the platform URL space this record left open: `/api/platform/v1/*`, unclassified by host like `/api/internal` and authenticated by the operator scheme. This record's sentence that operator @@ -1423,9 +1431,6 @@ work by one confined setter. The rule that no route resolves a tenant from a request-supplied override stands for every route that resolves context from a host or a claim. -> **Erratum (2026-11-19, Amendment 22 below).** "One confined setter" is wrong: no -> setter was added. The operator act executor installs a resolved ambient context for -> the target and the ordinary transaction behavior announces it. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0040-ambient-unit-of-work.md b/docs/decisions/0040-ambient-unit-of-work.md index 966b3415..25512412 100644 --- a/docs/decisions/0040-ambient-unit-of-work.md +++ b/docs/decisions/0040-ambient-unit-of-work.md @@ -1005,6 +1005,14 @@ finding. ### Amendment 24 — Eleventh logical setter: operator target (2026-11-19) +> **Erratum — 2026-11-19.** The paragraph below counts an eleventh logical tenant +> setter, four unchanged context writers and a ninth definer. All three counts were +> wrong: there is no new setter (the census stays at fourteen), the context writers are +> five, and the resolver is the sixteenth definer; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four`, `GlobalIdentitySchemaTests` and +> `PlatformOperatorActExecutorTests`. The Decision is unchanged. Current authority: +> Amendment 25 below. Recorded in Amendment 25. + Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds the eleventh logical tenant setter, confined to the `PlatformOperator` source. It reads the target of an admitted operation, announces it once per unit of work and refuses any other caller. The @@ -1012,9 +1020,6 @@ four context writers do not change. The single-act resolver that maps a provider to a `UserId` is a ninth definer function; its signature, owner, body and ACL land in [Standard 05](../standards/05-database.md) with the packet that ships it. -> **Erratum (2026-11-19, Amendment 25 below).** All three counts above were wrong when -> this amendment was written: there is no new setter, the context writers are five, and -> the resolver is the sixteenth definer. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md index 4860c8dc..d4d21a12 100644 --- a/docs/decisions/0102-production-tenant-onboarding.md +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -55,6 +55,20 @@ is not proof that anything is implemented. ## Decision +> **Erratum — 2026-11-19.** Item 1 below says the target tenant is announced by "one +> new logical tenant setter", "the eleventh", and that "the four context writers do not +> change". No new setter exists, and the claim was unachievable when it was written: +> the query filters and the transaction behavior read the context accessor, so an act +> that is not installed in it is invisible to row security. The operator act executor +> installs an immutable resolved ambient context for the admitted target, the ordinary +> transaction behavior announces it, the setter census does not move, and the executor +> is a fifth writer of the accessor; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` (`TenantContextConstructionTests`) and +> `PlatformOperatorActExecutorTests`. The Decision is unchanged: an admitted operator +> act runs on the application role under the admitted target tenant's announcement and +> the platform role is not used. Current authority: +> [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in Amendment 1. + 1. **A confined operator source and announcement.** `AuthorizationSourceKind` gains `PlatformOperator`, minted only from an [ADR-0101](0101-platform-operator-authority.md) admission for one of the operations @@ -68,15 +82,6 @@ is not proof that anything is implemented. [ADR-0036](0036-tenant-resolution-trusted-inputs.md) receive dated disclosures, and the four context writers do not change. The platform role is not used. - > **Erratum (2026-11-19, Amendment 1 below).** The mechanism above was not built and - > could not have been. No new tenant setter exists: the operator act executor - installs > an immutable resolved ambient context for the admitted target, and the - ordinary > transaction behavior announces it, so the setter census does not move. The - executor > is a fifth writer of the tenant context accessor, because the query - filters and the > transaction behavior read that accessor and an act that is not - installed in it is > invisible to row security. "The four context writers do not - change" and "the > eleventh logical tenant setter" were therefore false when this - record was accepted. 2. **The commands.** `OperatorProvisionTenant` creates a Tenant and its default Organization. `OperatorMapHost` maps a host through the existing host-mapping store and its reserved-host and platform-host rules. `OperatorInitializeRole` creates one @@ -186,6 +191,15 @@ naming. branch, Seeder mode refusal and the onboarding runbook. It touches the source enum, `OperationPolicy` and `TrustedOperationDescriptor` source guards, the authorization audit context, the evidence coordinator and the draft composer. + > **Erratum — 2026-11-19.** The proof item below reads "succeeding after the last one + > is revoked". The database refuses that state: the deferred last-administrator guard + > rejects any commit that leaves a tenant without an available administrator, so no + > ordinary write reaches it; shown by SQLSTATE `P0303` in + > `PlatformOperatorOnboardingTests`. The proof reaches the state by an owner-level + > repair that steps around that guard and shows the invariant intact after the + > recovery, and "the setter's operation binding" reads as the executor's binding of + > the admitted operation to its request type. The Decision is unchanged. Current + > authority: Amendment 1 item 4. Recorded in Amendment 1. - Proof: positive and denied acts; wrong tenant; unbootstrapped person; interruption between every pair of steps with a retry that completes once; an unknown COMMIT; a tenant with history refusing the first-admin act; recovery refusing a tenant with an @@ -194,14 +208,6 @@ naming. are the source check, the in-transaction predicates, the resolver's Active filter and the setter's operation binding. - > **Erratum (2026-11-19, Amendment 1 below).** "After the last one is revoked" names a - > state the database refuses: the deferred last-administrator guard rejects any commit - > that leaves a tenant without an available administrator, so no ordinary write - reaches > it. The proof reaches the state by an owner-level repair that steps around - that > guard, and shows the invariant intact after the recovery. "The setter's - operation > binding" reads as the executor's binding of the admitted operation to its - request > type. - ## Carriers Dated disclosures in [ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the target @@ -217,11 +223,16 @@ specifications, and the Phase 03 Status. ### Amendment 1 — As built: an executor-installed context, no new setter (2026-11-19) -Step 2 of the packet shipped the five acts and showed four statements of this record -wrong or stale. Each is corrected inline above and recorded here. +Step 2 of the packet shipped the five acts. Two statements of this record were false +when it was accepted, and each carries an inline erratum above it: the new tenant setter +and unchanged context writers of § 1, and the proof item that revokes the last +administrator. Both were shown by the shipped code and its tests +(`SetTenant_Callers_Are_The_Enumerated_Four`, `PlatformOperatorActExecutorTests`, and +SQLSTATE `P0303` in `PlatformOperatorOnboardingTests`). The items below refine what the +record left open or stated differently from what was built; they are history, not +errata. -1. **No new setter; a fifth context writer.** § 1 promised one new confined tenant - setter and unchanged context writers. The operator act executor +1. **No new setter; a fifth context writer.** The operator act executor (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs`) consumes the single-use admission, opens a fresh scope, installs an immutable resolved `Ambient` context for the admitted tenant (no user, no organization, no host @@ -231,18 +242,24 @@ wrong or stale. Each is corrected inline above and recorded here. platform role is not used, and the executor is the fifth writer of the context accessor ([ADR-0036](0036-tenant-resolution-trusted-inputs.md) Amendment 2). The one source that may mint the operator descriptor is the fourth minting source, scoped to - the executor's frame and bound to the operation of the admission. + the executor's frame and bound to the operation of the admission. The routes that may + call the executor are pinned by + `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. 2. **Provisioning on a resolved context.** The new tenant's id is the act's target, so the executor installs a resolved context for an id that has no `tenants` row yet, and the ordinary insert policy admits it. The operator provisioning command therefore needs no provisioning announcement, and the seed command keeps its own. -3. **The resolver is the sixteenth definer.** `fn_identity_operator_resolve_user(uuid, - bytea)` takes the stored authority id and the derived subject key. The application - derives the key with the one `IdentitySubjectKey` implementation under the - deployment's qualified authority, and the function refuses any other authority, any - session but the application role, any key that is not 32 bytes and any transaction - that is not an ordinary read-write tenant one, then answers an Active user's id or - null. [Database Standards](../standards/05-database.md) carries the contract. +3. **The resolver is the sixteenth definer.** + `fn_identity_operator_resolve_user(uuid, bytea)` takes the stored authority id and + the derived subject key. The application derives the key with the one + `IdentitySubjectKey` implementation under the deployment's qualified authority, and + the function refuses any other authority, any session but the application role, any + key that is not 32 bytes and any transaction that is not an ordinary read-write + tenant one, then answers an Active user's id or null. The handlers ask the guard + whether the act is live before they call it. The function is nonetheless callable by + any application-role transaction that announces a tenant, so what it protects is the + subject lookup's confinement to the application role and not a witness bound to an + act; [Database Standards](../standards/05-database.md) records the residual. 4. **Recovery is a break-glass for repaired states.** The last-administrator guard is deferred to commit and rejects any write that leaves a tenant without an available administrator, which means a Membership with an Active tenant-wide administrator Role @@ -254,13 +271,42 @@ wrong or stale. Each is corrected inline above and recorded here. but unusable is not a recoverable tenant under it, and a predicate that also reads the User's eligibility would need a second confined definer. The maintainer decides whether that is wanted. - -Two behaviors the record left open are fixed. The business actor of every written row is -`UserId.SystemActor` and the audit actor is NULL, as § 3 and -[ADR-0101](0101-platform-operator-authority.md) § 9 say. A refused operator act writes -the ordinary `failed` MUST row in the target tenant, carrying the operator in -`metadata.operator`, and an authorization refusal of an operator request writes no -durable denial row ([ADR-0033](0033-audit-durability-model.md) Amendment 14). +5. **"Membership history" is tenant-wide history.** § 7 refuses a tenant that "ever had + a Membership". The predicate is evaluated under the act's own context, which carries + no organization and no tenant-wide read witness, so row security shows it + tenant-wide Memberships only. A tenant whose only Memberships are organization-scoped + reads as having had none. Ordinary writes cannot produce that state, because the + graph guard requires a tenant-wide administrator, so it is reachable only after an + owner-level repair, as recovery's state is, and the database's own guard reads the + same way. +6. **"Bootstrapped" means a global binding.** §§ 5 and 6 say the person signs in at the + tenant's mapped host first. The resolver finds an Active user of the stored authority + with that subject, wherever they signed in, because `users` is global per authority. + The runbook says so and asks the operator to confirm the subject belongs to the + intended person. +7. **Idempotency as built.** An exact repeat of an act answers from what was stored; a + repeat that changes any value under the same identifiers is refused + (`lockey_identifier_taken`). The administrator and Role acts find their own + Membership or Role before judging the Role's present state, so a template the new + administrator edited afterwards does not make the original act's retry fail. A + repeated act commits its ordinary MUST rows with no captured change, so the trail + shows every attempt. The host-mapping retry drops the host's cached resolution again. +8. **Signals (§ 11).** `learnstack_platform_operator_acts_total{operation,outcome}` + counts each act as `applied`, `replayed`, `refused` or `failed`; a `replayed` count + by operation is a setup resumed at that step. Event 7109 (Warning) records an + admitted act the pipeline itself refused as forbidden, which writes no durable row. +9. **Request shape.** Every identifier is a UUIDv7 and the platform sentinel is refused + as a tenant (400). A host mapping must state both `isActive` and `isPubliclyLive`, + because no act unmaps a host. A blank provider subject or one over 255 characters is + a 400, and a refused storage write answers in the vocabulary the sibling Identity + handlers use (`concurrency_conflict`, `dependency_unavailable`, or + `identity_foundation_refused`). + +The business actor of every written row is `UserId.SystemActor` and the audit actor is +NULL, as § 3 and [ADR-0101](0101-platform-operator-authority.md) § 9 say. A refused +operator act writes the ordinary `failed` MUST row in the target tenant, carrying the +operator in `metadata.operator`, and an authorization refusal of an operator request +writes no durable denial row ([ADR-0033](0033-audit-durability-model.md) Amendment 14). Carriers changed with this amendment: ADR-0033 Amendment 14, ADR-0036 Amendment 22 and ADR-0040 Amendment 25, each with an inline erratum beside the false text; Database diff --git a/docs/runbooks/tenant-onboarding.md b/docs/runbooks/tenant-onboarding.md index c8421a20..e71a2c95 100644 --- a/docs/runbooks/tenant-onboarding.md +++ b/docs/runbooks/tenant-onboarding.md @@ -44,16 +44,20 @@ act that has not been answered `200`. ``` 2. **Map the host.** `PUT /api/platform/v1/tenants/{tenantId}/host-mappings/{host}` with - `{ "isActive": true, "isPubliclyLive": true, "ticket": "CHG-123" }`. `organizationId` - is optional and pins the host to one branch. **You assert that the tenant owns the - host.** LearnStack checks no DNS and issues no certificate: a Self-Hosted operator is - responsible for both. A SaaS custom domain is the Hub's to approve and is not - reachable from here. + `{ "isActive": true, "isPubliclyLive": true, "ticket": "CHG-123" }`. **Both flags are + required** (a body without them is a `400`), because no act unmaps a host and a + mapping must never go live by omission. `organizationId` is optional and pins the + host to one branch. **You assert that the tenant owns the host.** LearnStack checks + no DNS and issues no certificate: a Self-Hosted operator is responsible for both. A + SaaS custom domain is the Hub's to approve and is not reachable from here. 3. **The person signs in once at that host.** The tenant has no members yet, and the zero-membership entry binds the person to the identity authority the first time they - sign in. The next acts refuse a subject that has not done this - (`lockey_bootstrap_required`). + sign in. The next acts refuse a subject that is not an Active, bound user of that + authority (`lockey_bootstrap_required`). The check is global, not per host: a subject + that signed in anywhere is accepted, so **confirm the `sub` is the intended + person's** (their own console entry), because a mistyped `sub` of another real person + is accepted and makes that person the administrator. 4. **Initialize the Role templates** the tenant will need, one act each: `PUT /api/platform/v1/tenants/{tenantId}/roles/{roleId}` with @@ -67,7 +71,7 @@ act that has not been answered `200`. 5. **Create the first administrator.** `PUT /api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}` with `{ "roleId": "", "providerSubject": "", "ticket": "CHG-123" }`. - It refuses any tenant that has ever had a Membership, so it cannot add an + It refuses any tenant that has had a tenant-wide Membership, so it cannot add an administrator to a tenant that has members. The `ticket` in each body is optional, and is the operator's own reference. Every answer @@ -77,7 +81,7 @@ is `200 { "result": ..., "correlationId": "..." }`. Keep the correlation id. `PUT /api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}` with the same body as step 5. It creates a replacement administrator and is the only act that -adds one to a tenant with Membership history. +adds one to a tenant with tenant-wide Membership history. **It refuses while any Active tenant-wide administrator Membership exists** (`lockey_administrator_exists`). The database also refuses to leave a tenant without an @@ -93,7 +97,7 @@ leaves the last-administrator guard as it found it. | Status | Reason (in the problem's `errors`) | What it means and what to do | |---|---|---| -| 400 | `validation_failed` | The body is malformed, a value is out of its grammar, an id is not a UUIDv7, or the ticket is not 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -` | +| 400 | `validation_failed` | The body is malformed, a value is out of its grammar, an id is not a UUIDv7 (or is the platform sentinel), a host mapping omits a flag, the `providerSubject` is blank or over 255 characters, or the ticket is not 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -` | | 401 | | The token does not meet the profile; there is one answer for every cause, and the cause is in the operator's signals | | 403 | | The token is good and the operator holds no grant for this act | | 404 | | The tenant does not exist, or the act can no longer see it. Provision first | @@ -103,18 +107,31 @@ leaves the last-administrator guard as it found it. | 409 | `lockey_tenant_has_memberships` | The tenant has had a Membership, so a first administrator or a new template is refused. Use recovery only if no administrator is active | | 409 | `lockey_administrator_exists` | Recovery refused: an Active administrator exists | | 409 | `lockey_role_template_unknown`, `lockey_identity_foundation_refused` | The template or the resulting graph is not one the identity foundation admits | +| 409 | `lockey_host_taken` | The host is mapped to another tenant, or to this one with other flags; the answer never says which | +| 409 | `lockey_host_reserved` | The host is a platform host and can never resolve to a tenant | +| 409 | `lockey_organization_not_in_tenant` | The `organizationId` of a host mapping is not one of this tenant's | +| 409 | `lockey_concurrency_conflict` | Another change won, or a lock timed out; repeat the same request. If it repeats, a second template of the same key and scope already exists | | 503 | | The audit row could not be written or a dependency could not answer, so nothing changed. Retry after a short delay | -A refused act writes a `failed` audit row in the tenant, so the attempt is on the -record. +A business refusal of an admitted act (a `409`) writes a `failed` audit row in the +tenant, so the attempt is on the record. A refusal at the gate (`401`, `403`, or a `400` +for the ticket) writes none: it leaves a counter and a log line, and the operator is not +yet an admitted actor of any tenant. ## Repeating an act Every act is idempotent on the ids you chose, so any failure that leaves you unsure, a timeout or a connection reset or a `500` after a commit, is answered by sending the same -request again. The retry finds what was written and answers `200`; it never writes a -second row. A retry whose ids match but whose other values differ is refused as -`lockey_identifier_taken` or `lockey_slug_taken` rather than changing the record. +request again. The retry finds what was written and answers `200` from the stored +record; it never writes a second tenant, Role, Membership or mapping. It does record +itself: the repeated act commits its ordinary audit rows as a `success` with no entity +or before and after state, so a repeat is visible in the trail as the repeat it is. A +retry whose ids match but whose other values differ, a changed display name or +organization slug for example, is refused as `lockey_identifier_taken` or +`lockey_slug_taken` rather than changing the record. A retry of the first administrator +or of a Role act still answers after the new administrator has edited the template. The +host-mapping retry also drops the host's cached resolution again, which repairs a miss +cached between the first run's invalidation and its commit. ## Reading the record @@ -136,6 +153,15 @@ COMMIT; The operator's digest is computed as in [Killswitch](killswitch.md#reading-the-record). +## Signals + +`learnstack_platform_operator_acts_total{operation,outcome}` counts each act as +`applied`, `replayed`, `refused` or `failed`; a `replayed` count is a setup resumed at +that step. Event 7109 (Warning) means an admitted act was refused as forbidden by the +request pipeline itself, which is a defect and not an operator mistake, and which writes +no audit row. The gate's counters and events 7101 to 7108 are in +[operator access](operator-access.md). + ## What this does not do It does not verify DNS, issue TLS, send an invitation, set a plan or an entitlement, diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 15452069..8a89771a 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6250,8 +6250,8 @@ readers. **Derives from:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and its Amendment 1. An operator onboarding act runs on the application role under the ordinary -tenant announcement, so it adds no table, no policy and no grant. It adds one confined -definer. +tenant announcement, so it adds no table, no policy and no table grant. It adds one +confined definer. ### Operator subject resolution @@ -6270,8 +6270,9 @@ answers exactly that: bytes, and any authority id other than the one stored in `identity_authority`. Each raises `23514` and reveals nothing. - **Answer.** The `id` of the one `users` row with that authority and key whose `status` - is `Active` and whose `deleted_at` is null, otherwise null. It reads no other relation - and writes nothing. + is `Active` and whose `deleted_at` is null, otherwise null. It reads + `identity_authority` for its refusal check and `users` for its answer, and nothing + else, and it writes nothing. - **Caller.** `OperatorSubjectResolver`, which derives the key with the one `IdentitySubjectKey` implementation under the deployment's qualified authority, so a request supplies the provider subject and nothing else. The exact SQL, ACL, owner and @@ -6281,3 +6282,12 @@ A Membership written under that answer still passes the ordinary admission guard re-reads the User's eligibility under the user fence, so the resolver is a lookup and not an authority. +**Residual.** The function is executable by `learnstack_app` and checks the session and +the arguments, not a witness bound to an operator act, as the invitation and consent +definers do. Any application-role transaction that announces a tenant can ask it whether +a provider subject is an Active user and receive the `UserId`. The key is an unkeyed +hash that supplies neither secrecy nor admission authority +([ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md)), so the answer +discloses that a person exists, not who they are or what they may do. The handlers check +that the act is live before they call it; no SQL-level binding is added. + diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index abb0854c..22331a51 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -323,8 +323,9 @@ Rules: is used when an authorisation check rejects the operation — these MUST be audited so we can detect probing. A Platform operator admission refusal is tenantless and outside that population: it leaves a counter and a Warning log - ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11), and so does an - authorization refusal of an operator act inside the pipeline + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11), and an + authorization refusal of an operator act inside the pipeline leaves a counted + `refused` outcome and a Warning, event 7109, with no durable row ([ADR-0033 Amendment 14](../decisions/0033-audit-durability-model.md)). A business refusal of an admitted operator act writes the ordinary `failed` row in the target tenant, with `actor_user_id` NULL, the closed reason slug and `metadata.operator`. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 31062f4c..88279778 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**381 test methods run in +**382 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**285 rules in this catalogue are Implemented, and 167 of them are in that assembly.** +**286 rules in this catalogue are Implemented, and 168 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -5936,6 +5936,21 @@ structural test proves — and what it does not. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). - **Phase:** P03-9. +#### `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act` + +- **Asserts:** the files, by their path under `backend/src`, that name + `PlatformOperatorActExecutor` in code, comments stripped, are exactly the executor, + the registration beside the source it enters and the onboarding routes. A second + caller is a second route to an act; adding one is a deliberate edit here, with its + denied proof. +- **Why it matters:** the executor installs a tenant context from an admission, so what + may call it is what may run an operator act. The admission is the barrier, and this + keeps the set of places that can spend one small and visible. +- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 1. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 2). +- **Phase:** P03-9. + #### `Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer` - **Asserts:** the write verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` From 4eb54f2c52fc1c87903973284a00270228c21db1 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Thu, 19 Nov 2026 21:54:20 +0300 Subject: [PATCH 10/28] fix(platform): close P03-9 step 2 review round 2 findings Three independent reviews with different lenses (composition and regression, SQL and row security, operability and contract) found no blocker. Fixed: a 503 answered as a result carries Retry-After; template and scope names are matched exactly instead of parsed; the five request records and the operator document state their required fields, ticket grammar, 413 and 429, and drop the untrue 409 reason; the resolver read and an unqualified authority answer in the Identity vocabulary; the resolver and its port are pinned to their callers; the killswitch route shares the refusal and audit-503 helpers; unused members and a stale summary are removed. Documents: the Identity and Tenancy module specifications no longer say production first-admin does not exist; the onboarding runbook gains a section on what cannot be recovered, a UUIDv7 hint, the errors shape and the ticket rule; the operator-access and killswitch runbooks are scoped to their own acts; ADR-0102 carries errata under every heading that repeated the setter claim and Amendment 1 items for shared cores, the unrecorded ticket and request shape; the seed skill and README state the Development-only rule. ADR: 0102 Module: Tenancy, Identity Co-Authored-By: Claude Sonnet 5.5 --- .claude/skills/seed-tenant/SKILL.md | 10 +- README.md | 4 +- .../PlatformOperatorDocumentTransformer.cs | 10 +- .../PlatformOperatorEndpoints.Onboarding.cs | 115 ++++++++++++++---- .../Platform/PlatformOperatorEndpoints.cs | 15 +-- .../PlatformOperator/OperatorTenantContext.cs | 2 +- .../PlatformOperatorActCatalog.cs | 3 - .../OperatorActs/OperatorIdentityCommands.cs | 7 ++ .../OperatorActs/OperatorIdentityHandlers.cs | 2 +- .../Persistence/ContextualIdentityStores.cs | 2 +- .../Persistence/OperatorSubjectResolver.cs | 11 +- .../Persistence/OperatorSubjectResolverDdl.cs | 8 +- .../IdentityFoundationConventionTests.cs | 24 ++++ .../Database/GlobalIdentitySchemaTests.cs | 2 +- .../PlatformOperatorOnboardingTests.cs | 52 ++++++-- .../PlatformOperatorHttpTests.cs | 26 ++++ .../0102-production-tenant-onboarding.md | 60 ++++++++- docs/glossary.md | 2 +- docs/modules/identity/README.md | 42 ++++--- docs/modules/tenancy/README.md | 9 ++ docs/runbooks/killswitch.md | 6 +- docs/runbooks/operator-access.md | 22 ++-- docs/runbooks/tenant-onboarding.md | 38 ++++-- docs/standards/05-database.md | 11 +- .../21-architecture-tests-catalogue.md | 21 +++- 25 files changed, 391 insertions(+), 113 deletions(-) diff --git a/.claude/skills/seed-tenant/SKILL.md b/.claude/skills/seed-tenant/SKILL.md index 344c8268..2d622909 100644 --- a/.claude/skills/seed-tenant/SKILL.md +++ b/.claude/skills/seed-tenant/SKILL.md @@ -99,9 +99,13 @@ credential-free projection children receive process prerequisites without those runtime values. Proxy and trust prerequisites remain available; migration, platform, dispatcher and provider-admin credentials do not enter a Seeder child. -The direct tool reads its process environment; it does not load `.env`. Supply -`ConnectionStrings__Default`, `Identity__AuthorityId` and -`Authentication__Tenant__Issuer` from the selected private configuration. The +The direct tool reads its process environment; it does not load `.env`. It runs only +with `Deployment__Mode=Development` and exits 2 before reading any credential +otherwise: production tenants are onboarded through the operator surface +([runbook](../../../docs/runbooks/tenant-onboarding.md), ADR-0102 § 10). Supply +`Deployment__Mode=Development`, `ConnectionStrings__Default`, +`Identity__AuthorityId` and `Authentication__Tenant__Issuer` from the selected private +configuration. The authority must already be installed: `make seed` passes the stable pair through `make migrate`, whose deployment installer runs before content seeding. The Seeder never installs, rewrites or infers that anchor. A schema-only migration diff --git a/README.md b/README.md index 25c8192e..c3bb3aaa 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,9 @@ Continue with the manual HTTPS prerequisites below, then run `make demo`. It creates missing private configuration and restores dependencies without changing Git hooks. `make seed` converges application data and the development identity realm and its application-owned identity foundation without starting the API or -web. The argument-free direct .NET Seeder remains data-only. +web. The argument-free direct .NET Seeder remains data-only and runs only with +`Deployment__Mode=Development`; production tenants are onboarded through the operator +surface ([runbook](docs/runbooks/tenant-onboarding.md)). The seed provisions `demo-english` and `demo-yoga`, their organizations and host mappings, enabled locales, distinct branding, built-in and tenant-authored definitions, diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 4b85d9a6..583bf0f6 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -141,13 +141,15 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation private static readonly (string Status, string Description)[] Statuses = [ - ("400", "validation_failed: the body is malformed, the required state is missing, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -."), + ("400", "validation_failed: the body is malformed, a required field is missing, an identifier is not a UUIDv7, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate or by a route check carries no per-field errors."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), - ("404", "not_found: the key is not a declared killswitch, or the tenant the route names does not exist."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (identifier taken, a person already bound, an administrator already exists, the tenant has history). The same request is safe to repeat once the state is as the reason says."), + ("404", "not_found: the killswitch key is not declared, or the tenant the route names does not exist."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), + ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), + ("429", "rate_limited: the caller exceeded the per-peer request budget."), ("500", "internal_error: an unexpected failure. An act whose final commit's outcome is unknown may have landed; repeat the same request (every act is idempotent on its identifiers) or read the state before changing it."), - ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or a dependency could not answer, so nothing changed. Retry after the delay."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or an ordered lock could not be taken, so nothing changed. Retry after the delay."), ]; } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs index 1343e966..8168ea6a 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs @@ -1,3 +1,4 @@ +using System.ComponentModel.DataAnnotations; using LearnStack.Api.Authentication; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; @@ -14,20 +15,59 @@ namespace LearnStack.Api.Platform; /// The default organization of a tenant being provisioned. -internal sealed record DefaultOrganizationBody(Guid Id, string? Slug, string? DisplayName); +/// The organization's identifier, a UUIDv7 the operator generates. +/// The organization's slug. +/// The organization's display name. +internal sealed record DefaultOrganizationBody( + [property: Required] Guid Id, + [property: Required] string? Slug, + [property: Required] string? DisplayName); /// The body of a tenant provisioning. internal sealed record TenantProvisionRequest( - string? Slug, string? DisplayName, DefaultOrganizationBody? DefaultOrganization, string? Ticket); + [property: Required] string? Slug, + [property: Required] string? DisplayName, + [property: Required] DefaultOrganizationBody? DefaultOrganization, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); -/// The body of a host mapping. -internal sealed record HostMapRequest(Guid? OrganizationId, bool? IsActive, bool? IsPubliclyLive, string? Ticket); +/// The body of a host mapping; both flags are required because no act unmaps a host. +internal sealed record HostMapRequest( + Guid? OrganizationId, + [property: Required] bool? IsActive, + [property: Required] bool? IsPubliclyLive, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); /// The body of a role template initialization. -internal sealed record RoleInitializeRequest(string? BuiltInKey, string? CapabilityScope, string? Ticket); +/// One of TenantAdmin, Instructor, Learner, Guardian, Editor, OrgAdmin, OrgInstructor. +/// Tenant or Organization. +/// An optional reference of the operator's own; it is validated and not recorded. +internal sealed record RoleInitializeRequest( + [property: Required] string? BuiltInKey, + [property: Required] string? CapabilityScope, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); /// The body of a first-administrator or recovery act. -internal sealed record AdministratorRequest(Guid RoleId, string? ProviderSubject, string? Ticket); +/// The initialized tenant-wide administrator Role, a UUIDv7. +/// The person's sub at the identity authority's issuer, at most 255 characters. +/// An optional reference of the operator's own; it is validated and not recorded. +internal sealed record AdministratorRequest( + [property: Required] Guid RoleId, + [property: Required][property: StringLength(OperatorSubjectLimits.MaximumProviderSubjectLength, MinimumLength = 1)] string? ProviderSubject, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); + +/// The ticket grammar of ADR-0101 § 5, stated once for the request records. +internal static class TicketPattern +{ + internal const string Value = @"^[A-Za-z0-9._:/#-]{1,64}$"; +} /// What an operator act answers: its result and the correlation id the operator records. internal sealed record OperatorActResponse(T Result, string CorrelationId); @@ -48,7 +88,7 @@ private static void MapOnboarding(RouteGroupBuilder group) Describe( group.MapPut("/tenants/{tenantId:guid}", ProvisionTenantAsync) .WithName("PlatformTenantProvision") - .WithSummary("Provision a tenant and its default organization (idempotent on the id and slug)."), + .WithSummary("Provision a tenant and its default organization; an exact repeat answers from the stored record, a repeat that changes a value is refused."), typeof(OperatorActResponse)); Describe( group.MapPut("/tenants/{tenantId:guid}/host-mappings/{host}", MapHostAsync) @@ -91,7 +131,7 @@ private static Task ProvisionTenantAsync( body => body.Ticket, body => body.Slug is { } slug && body.DisplayName is { } name && body.DefaultOrganization is { Slug: { } orgSlug, DisplayName: { } orgName } organization - && IsRoot(organization.Id) + && IsOperatorId(organization.Id) ? new OperatorProvisionTenantCommand( TenantId.From(tenantId), slug, name, OrganizationId.From(organization.Id), orgSlug, orgName) : null, @@ -117,10 +157,10 @@ private static Task InitializeRoleAsync( RunAsync( http, tenantId, PlatformOperations.RoleInitialize, gate, executor, loggers, body => body.Ticket, - body => Enum.TryParse(body.BuiltInKey, ignoreCase: true, out var key) && Enum.IsDefined(key) - && Enum.TryParse(body.CapabilityScope, ignoreCase: true, out var scope) + body => TryName(body.BuiltInKey, out var key) + && TryName(body.CapabilityScope, out var scope) && scope is PermissionScope.Tenant or PermissionScope.Organization - && IsRoot(roleId) + && IsOperatorId(roleId) ? new OperatorInitializeRoleCommand(roleId, key, scope) : null, cancellationToken); @@ -131,7 +171,7 @@ private static Task CreateFirstAdminAsync( RunAsync( http, tenantId, PlatformOperations.FirstAdminCreate, gate, executor, loggers, body => body.Ticket, - body => IsSubject(body.ProviderSubject) && IsRoot(membershipId) && IsRoot(body.RoleId) + body => IsSubject(body.ProviderSubject) && IsOperatorId(membershipId) && IsOperatorId(body.RoleId) ? new OperatorCreateFirstAdminCommand(membershipId, body.RoleId, body.ProviderSubject!) : null, cancellationToken); @@ -141,7 +181,7 @@ private static Task RecoverAdminAsync( RunAsync( http, tenantId, PlatformOperations.AdminRecover, gate, executor, loggers, body => body.Ticket, - body => IsSubject(body.ProviderSubject) && IsRoot(membershipId) && IsRoot(body.RoleId) + body => IsSubject(body.ProviderSubject) && IsOperatorId(membershipId) && IsOperatorId(body.RoleId) ? new OperatorRecoverAdminCommand(membershipId, body.RoleId, body.ProviderSubject!) : null, cancellationToken); @@ -181,7 +221,7 @@ private static async Task RunAsync( return Problem(http, StatusCodes.Status415UnsupportedMediaType, "lockey_unsupported_media_type"); } - if (body is null || !IsRoot(tenantRoute) || build(body) is not { } request) + if (body is null || !IsOperatorId(tenantRoute) || build(body) is not { } request) { return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); } @@ -196,10 +236,7 @@ private static async Task RunAsync( } catch (AuditWriteFailedException failure) { - PlatformOperatorMetrics.AuditFailed(operation); - LogAuditRefused(loggers.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), failure); - RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); - return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); + return AuditUnavailableProblem(http, loggers, operation, failure); } } @@ -207,12 +244,35 @@ private static async Task RunAsync( /// An identifier the operator generates: a UUIDv7, never the nil value and never the platform sentinel, which /// is the tenant the platform's own rows belong to and which no operator act may name. /// - private static bool IsRoot(Guid id) => id != Guid.Empty && id.Version == 7 && id != TenantId.PlatformSentinel.Value; + /// + /// A MUST row that cannot be written refuses the act: a counter an operator can alert on, an error line, and a 503 with + /// its delay. Nothing changed, so the act is safe to repeat. + /// + private static IResult AuditUnavailableProblem( + HttpContext http, ILoggerFactory loggers, PlatformOperation operation, AuditWriteFailedException failure) + { + PlatformOperatorMetrics.AuditFailed(operation); + LogAuditRefused(loggers.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), failure); + RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); + return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); + } - private const int MaximumSubjectLength = 255; + private static bool IsOperatorId(Guid id) => id != Guid.Empty && id.Version == 7 && id != TenantId.PlatformSentinel.Value; + + /// + /// A member of the closed set by its exact name, case aside. Enum.TryParse is not that: it also takes + /// numerals, padded names and comma lists that OR into another member. + /// + private static bool TryName(string? value, out TEnum member) where TEnum : struct, Enum + { + member = default; + var name = Enum.GetNames().FirstOrDefault( + candidate => string.Equals(candidate, value, StringComparison.OrdinalIgnoreCase)); + return name is not null && Enum.TryParse(name, out member); + } private static bool IsSubject(string? subject) => - !string.IsNullOrWhiteSpace(subject) && subject.Length <= MaximumSubjectLength; + !string.IsNullOrWhiteSpace(subject) && subject.Length <= OperatorSubjectLimits.MaximumProviderSubjectLength; private static IResult RefusalProblem(HttpContext http, PlatformRefusal refusal) => refusal switch { @@ -222,10 +282,17 @@ private static bool IsSubject(string? subject) => }; /// An act's own refusal, in the status and shape the API gives every other failed result. - private static IResult ResultProblem(HttpContext http, Error error) => - Results.Json( + private static IResult ResultProblem(HttpContext http, Error error) + { + var status = HttpStatusMap.For(error); + + // A refusal that is a lock the act could not take answers 503 as a result, and a 503 owes its delay like every + // other the API sends. + RetryAfter.Apply(http.Response, status); + return Results.Json( ProblemDetailsFactory.For(error, http), options: null, contentType: ProblemDetailsMediaType.Value, - statusCode: HttpStatusMap.For(error)); + statusCode: status); + } } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index 8e0a15df..ae4826d1 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -135,12 +135,7 @@ private static async Task ToggleKillswitchAsync( var admission = await gate.AdmitAsync(witness, PlatformOperations.KillswitchToggle, body?.Ticket, cancellationToken); if (!admission.IsAdmitted) { - return admission.Refusal switch - { - PlatformRefusal.InvalidTicket => Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"), - PlatformRefusal.InvalidWitness => Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"), - _ => Problem(http, StatusCodes.Status403Forbidden, "lockey_forbidden"), - }; + return RefusalProblem(http, admission.Refusal); } if (bodyState == BodyState.NotJson) @@ -170,13 +165,7 @@ private static async Task ToggleKillswitchAsync( } catch (AuditWriteFailedException failure) { - // A MUST row that cannot be written refuses the act, and the refusal is a signal: - // an error line and a counter an operator can alert on, and a Retry-After like - // every other 503 the API answers. - PlatformOperatorMetrics.AuditFailed(PlatformOperations.KillswitchToggle); - LogAuditRefused(loggerFactory.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), failure); - RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); - return Problem(http, StatusCodes.Status503ServiceUnavailable, "lockey_audit_unavailable"); + return AuditUnavailableProblem(http, loggerFactory, PlatformOperations.KillswitchToggle, failure); } } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs index b043f56d..f3906881 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/OperatorTenantContext.cs @@ -4,7 +4,7 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// -/// The immutable tenant context of one admitted operator act on an existing tenant (ADR-0102 § 1). +/// The immutable tenant context of one admitted operator act, for the tenant it names, which may be the tenant the act is about to create (ADR-0102 § 1). /// /// /// Resolved and ambient, as a seed, event or job context is, with no actor: the business columns of diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs index 92d4ba38..cfc7eda0 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs @@ -33,9 +33,6 @@ public PlatformOperatorActCatalog(IEnumerableThe request types in the catalog. - public IReadOnlyCollection RequestTypes => _acts.Keys; - /// Finds the act a request type belongs to. public bool TryGet(Type requestType, out PlatformOperatorAct act) { diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs index 5732419f..b30d813c 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs @@ -6,6 +6,13 @@ namespace LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +/// The one limit the operator administrator acts and their routes share. +public static class OperatorSubjectLimits +{ + /// The longest provider subject an operator may name. + public const int MaximumProviderSubjectLength = 255; +} + /// /// Creates one finite Role template in an operator-named Tenant (ADR-0102 § 2, § 6). /// diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs index 8ff7e453..9b3450cc 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs @@ -135,7 +135,7 @@ internal static async Task> CreateAsync( CancellationToken cancellationToken) { if (!context.IsResolved || context.OrganizationId is not null || !SeedFoundationGate.ValidRoot(membershipId) - || !SeedFoundationGate.ValidRoot(roleId) || string.IsNullOrWhiteSpace(providerSubject) || providerSubject.Length > 255) + || !SeedFoundationGate.ValidRoot(roleId) || string.IsNullOrWhiteSpace(providerSubject) || providerSubject.Length > OperatorSubjectLimits.MaximumProviderSubjectLength) return OperatorIdentityFailures.Rule("MembershipId", "lockey_validation_failed"); if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) return OperatorIdentityFailures.NotFound(); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs index 710618d7..feafd026 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs @@ -283,7 +283,7 @@ public Task HasActiveTenantAdministratorAsync(CancellationToken cancellati { // The administrator Roles first, judged by the domain's own definition (kernel grants // included), then whether an Active tenant-wide Membership holds one of them. - var candidates = await db.Roles.Include(role => role.Grants) + var candidates = await db.Roles.AsNoTracking().Include(role => role.Grants) .Where(role => role.BuiltInKey == BuiltInRoleKey.TenantAdmin && role.DeletedAt == null) .ToListAsync(cancellationToken); var administratorRoles = candidates.Where(role => role.IsTenantAdministrator).Select(role => role.Id).ToList(); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs index 0e13ef85..ca8137e0 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs @@ -21,8 +21,9 @@ public sealed class OperatorSubjectResolver(IdentityDbContext db, IdentityAuthor /// public async Task ResolveActiveUserAsync(string providerSubject, CancellationToken cancellationToken = default) { - var registration = qualification.Current - ?? throw new InvalidOperationException("Identity authority qualification is unavailable."); + // An authority that is not qualified is a dependency that is not there, the same answer the sibling stores + // give a provider that is unreachable, and not an unclassified exception. + var registration = qualification.Current ?? throw new IdentityStorageProviderException(); IdentitySubjectKey key; try { @@ -35,9 +36,11 @@ public sealed class OperatorSubjectResolver(IdentityDbContext db, IdentityAuthor var authority = registration.AuthorityId.Value; var bytes = key.ToByteArray(); - var found = await db.Database + // A provider failure crosses the same boundary the sibling stores use, so it answers in the Identity + // vocabulary and not as an unclassified exception. + var found = await ContextualIdentityStorageControl.ReadAsync(() => db.Database .SqlQuery($"SELECT public.fn_identity_operator_resolve_user({authority}, {bytes}) AS \"Value\"") - .SingleAsync(cancellationToken); + .SingleAsync(cancellationToken)); return found is { } id ? UserId.From(id) : null; } } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs index d24e3a92..50d52f33 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs @@ -19,19 +19,19 @@ internal static class OperatorSubjectResolverDdl internal static void Add(MigrationBuilder migration) => migration.Sql(""" CREATE FUNCTION public.fn_identity_operator_resolve_user(selected_authority uuid, selected_subject_key bytea) RETURNS uuid LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog AS $resolve$ - DECLARE found uuid; + DECLARE resolved_user uuid; BEGIN IF session_user <> 'learnstack_app' OR NULLIF(current_setting('app.tenant_id',true),'') IS NULL OR current_setting('transaction_read_only') <> 'off' OR current_setting('transaction_isolation') <> 'read committed' - OR selected_authority IS NULL OR selected_subject_key IS NULL OR length(selected_subject_key) <> 32 + OR selected_authority IS NULL OR selected_subject_key IS NULL OR octet_length(selected_subject_key) <> 32 OR NOT EXISTS (SELECT FROM public.identity_authority a WHERE a.id=1 AND a.authority_id=selected_authority) THEN RAISE EXCEPTION 'Operator subject resolution refused.' USING ERRCODE='23514'; END IF; - SELECT u.id INTO found FROM public.users u + SELECT u.id INTO resolved_user FROM public.users u WHERE u.authority_id=selected_authority AND u.subject_key=selected_subject_key AND u.status='Active' AND u.deleted_at IS NULL; - RETURN found; + RETURN resolved_user; END $resolve$; REVOKE ALL ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) FROM PUBLIC; GRANT EXECUTE ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) TO learnstack_app; diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs index 4f03f1d8..74b4ce7b 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -229,6 +229,30 @@ private static IEnumerable SessionCalls(string source) => Regex.Matches( @"\bpg_(?:try_)?advisory_(?:lock|unlock)(?:_shared|_all)?\s*\(", RegexOptions.IgnoreCase) .Select(match => match.Value); + [Fact] + public void Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject() + { + // ADR-0102 § 5: the confined definer is reached through one adapter, and the port through the one core that + // names a person for an administrator act. A second caller would be a second way to ask whether a provider + // subject is an Active user, and is added here deliberately with its own denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "fn_identity_operator_resolve_user", except: null) + .Should().BeEquivalentTo( + [ + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs", + ], + "only the adapter calls the function and only its migration installs it"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IOperatorSubjectResolver", except: null) + .Should().BeEquivalentTo( + [ + "Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs", + "Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs", + ], + "the port is declared, implemented, registered and used by the operator administrator core, and by nothing else"); + } + private static string[] Callers(string typeName, string methodName) => ProductionAssemblies.All().SelectMany(assembly => { using var module = ModuleDefinition.ReadModule(assembly.Location); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs index 102fd8b2..8791bc8b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -55,7 +55,7 @@ SELECT set_config('app.identity_authority_id','not-a-uuid',true), } [Fact] - public async Task Applied_census_has_sixty_six_tables_and_exactly_fifteen_confined_definers() + public async Task Applied_census_has_sixty_six_tables_and_exactly_sixteen_confined_definers() { await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); await SchemaTableClasses.AssertCompleteAsync(owner); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs index aeeaa6de..cb8af710 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs @@ -6,7 +6,9 @@ using FluentAssertions; using LearnStack.Modules.Tenancy.Application.Abstractions; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; using MediatR; @@ -83,6 +85,14 @@ await AssertRuleAsync( await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization, organizationSlug: "elsewhere")), HttpStatusCode.Conflict, "lockey_identifier_taken"); + // The host mapping comes second, as the runbook orders the steps, and again on a repeat. + var mapped = await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}"""); + await AssertOkAsync(mapped); + proof.Invalidations.Should().Equal([host], "the first run drops any cached answer for the host"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}""")); + proof.Invalidations.Should().Equal([host, host], "the retry drops it again, which is the repair for a miss cached before the commit"); + (await proof.HostMappingsAsync(host)).Should().Equal(tenant); + // The first administrator needs the role and the person first; each refusal writes nothing. await AssertRuleAsync( await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject)), @@ -100,14 +110,6 @@ await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, " (await proof.CountAsync(tenant, "memberships")).Should().Be(1); (await proof.CountAsync(tenant, "membership_role_assignments")).Should().Be(1); - // The host mapping, then again. - var mapped = await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}"""); - await AssertOkAsync(mapped); - proof.Invalidations.Should().Equal([host], "the first run drops any cached answer for the host"); - await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}""")); - proof.Invalidations.Should().Equal([host, host], "the retry drops it again, which is the repair for a miss cached before the commit"); - (await proof.HostMappingsAsync(host)).Should().Equal(tenant); - // How each act ended, as the monitoring owner sees it: four first runs, five repeats that found their own // earlier result (the provisioning twice and each of the others once) and four refusals. outcomes.Counts.Should().Equal(new Dictionary @@ -285,6 +287,20 @@ public async Task An_Act_Interrupted_Between_Its_Writes_Leaves_Nothing_And_The_R (await proof.CountAsync(tenant, "organizations")).Should().Be(1); } + [Fact] + public async Task A_Lock_The_Act_Could_Not_Take_Answers_503_With_Its_Delay_Like_Every_Other_503() + { + await using var proof = await Proof.CreateAsync(parent); + using var unavailable = proof.ClientWith(services => services.Insert(0, ServiceDescriptor.Scoped< + IPipelineBehavior>, ReportUnavailable>())); + + using var refused = await proof.PutAsync( + Full, $"/tenants/{Ids.Next()}", ProvisionBody("busy-" + Ids.Short(), Ids.Next()), unavailable); + + refused.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + refused.Headers.RetryAfter.Should().NotBeNull("the operator document declares the delay on every 503"); + } + [Fact] public async Task The_Platform_Sentinel_And_A_Malformed_Request_Are_Refused_With_The_Status_An_Operator_Can_Act_On() { @@ -306,6 +322,15 @@ public async Task The_Platform_Sentinel_And_A_Malformed_Request_Are_Refused_With .Should().Be(HttpStatusCode.BadRequest); (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", """{"builtInKey":"Nobody","capabilityScope":"Tenant"}""")).StatusCode .Should().Be(HttpStatusCode.BadRequest, "an unknown template key is refused before any act"); + foreach (var lenient in new[] { "Instructor,Guardian", "1", " TenantAdmin", "tenantadmin,", "7" }) + { + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", + JsonSerializer.Serialize(new { builtInKey = lenient, capabilityScope = "Tenant" }))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, $"'{lenient}' is not the exact name of a template"); + } + + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", """{"builtInKey":"Learner","capabilityScope":"Tenant,Organization"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "nor of a scope"); (await proof.SendAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", new StringContent(RoleBody(), Encoding.UTF8, "text/plain"))).StatusCode .Should().Be(HttpStatusCode.UnsupportedMediaType); (await proof.CountAsync(tenant, "roles")).Should().Be(0); @@ -897,6 +922,17 @@ public async Task> Handle( } } + /// A lock the act could not take, as the guard reports it: a failure result and no write. + private sealed class ReportUnavailable + : IPipelineBehavior> + { + public Task> Handle( + OperatorProvisionTenantCommand request, + RequestHandlerDelegate> next, + CancellationToken cancellationToken) => + Task.FromResult(Result.FailFor>(new Error(new LocalizedMessage("lockey_dependency_unavailable")))); + } + /// The tenant store with its third write, the default-organization back-reference, failing. private sealed class FailTheLastWrite(ITenantWriteStore inner) : ITenantWriteStore { diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index b82c7bef..461c3306 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -473,6 +473,32 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum root.GetProperty("paths").EnumerateObject().Select(path => path.Name).Should().BeEquivalentTo(OperatorRoutes, "a route that is not in the closed list is an operator act nobody reviewed"); + + // What a generated client needs to know it must send, and the statuses it can meet beyond the common ones. + var schemas = root.GetProperty("components").GetProperty("schemas"); + string[] RequiredOf(string route) + { + var schema = root.GetProperty("paths").GetProperty(route).GetProperty("put").GetProperty("requestBody") + .GetProperty("content").GetProperty("application/json").GetProperty("schema"); + if (schema.TryGetProperty("$ref", out var reference)) + { + schema = schemas.GetProperty(reference.GetString()!.Split('/')[^1]); + } + + return schema.TryGetProperty("required", out var required) + ? [.. required.EnumerateArray().Select(name => name.GetString()!)] : []; + } + + RequiredOf("/api/platform/v1/tenants/{tenantId}").Should().Contain(["slug", "displayName", "defaultOrganization"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/host-mappings/{host}").Should().Contain(["isActive", "isPubliclyLive"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/roles/{roleId}").Should().Contain(["builtInKey", "capabilityScope"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}").Should().Contain(["roleId", "providerSubject"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}").Should().Contain(["roleId", "providerSubject"]); + foreach (var route in OperatorRoutes) + { + root.GetProperty("paths").GetProperty(route).GetProperty("put").GetProperty("responses").EnumerateObject() + .Select(response => response.Name).Should().Contain(["413", "429"], route); + } } private static readonly string[] OperatorRoutes = diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md index d4d21a12..06e134d7 100644 --- a/docs/decisions/0102-production-tenant-onboarding.md +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -139,6 +139,13 @@ is not proof that anything is implemented. ## Context +> **Erratum — 2026-11-19.** The first paragraph below counts "one new confined setter" +> among the costs. No setter was added and the context writers are five, not four; +> shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + Onboarding is not the platform scope's job. The scope exists to cross tenants and write platform tables, and the platform role bypasses row security. A first administrator is the opposite case: one tenant, ordinary tables, and the strongest invariants in the @@ -174,6 +181,13 @@ naming. ### Negative +> **Erratum — 2026-11-19.** The first bullet below counts "a new confined setter" among +> the widened sets. No setter was added and the context writers are five, not four; +> shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + - A new authorization source kind, a new confined setter and a new resolver widen closed sets that tests pin, so each census is edited deliberately. - An operator needs the person's `sub`, and the person must sign in first at a mapped @@ -187,6 +201,13 @@ naming. ## Implementation Notes +> **Erratum — 2026-11-19.** The first bullet below says Step 2 delivers "the setter". No +> setter was added and the context writers are five, not four; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + - Step 2 delivers the source, setter, resolver, commands, routes, audit-composition branch, Seeder mode refusal and the onboarding runbook. It touches the source enum, `OperationPolicy` and `TrustedOperationDescriptor` source guards, the authorization @@ -210,6 +231,13 @@ naming. ## Carriers +> **Erratum — 2026-11-19.** The first paragraph below names "the eleventh logical +> setter" as ADR-0040's disclosure. No setter was added and the context writers are +> five, not four; shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + Dated disclosures in [ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the target announcement), [ADR-0040](0040-ambient-unit-of-work.md) (the eleventh logical setter), [ADR-0044](0044-audit-write-path.md) and [ADR-0033](0033-audit-durability-model.md) (the @@ -225,8 +253,9 @@ specifications, and the Phase 03 Status. Step 2 of the packet shipped the five acts. Two statements of this record were false when it was accepted, and each carries an inline erratum above it: the new tenant setter -and unchanged context writers of § 1, and the proof item that revokes the last -administrator. Both were shown by the shipped code and its tests +and unchanged context writers of § 1, repeated in Context, Consequences, Implementation +Notes and Carriers, and the proof item that revokes the last administrator. Both were +shown by the shipped code and its tests (`SetTenant_Callers_Are_The_Enumerated_Four`, `PlatformOperatorActExecutorTests`, and SQLSTATE `P0303` in `PlatformOperatorOnboardingTests`). The items below refine what the record left open or stated differently from what was built; they are history, not @@ -295,12 +324,31 @@ errata. counts each act as `applied`, `replayed`, `refused` or `failed`; a `replayed` count by operation is a setup resumed at that step. Event 7109 (Warning) records an admitted act the pipeline itself refused as forbidden, which writes no durable row. -9. **Request shape.** Every identifier is a UUIDv7 and the platform sentinel is refused +9. **Shared cores.** § 2 and Consequences promise shared cores extracted from the seed + handlers so the domain logic exists once. Tenancy shares by handling the seed and + operator commands in the same classes. Identity does not extract a core: its operator + handlers compose the same aggregates and gates (`Role.Create`, `Membership.Create`, + `SeedFoundationGate`, `SeedMembershipCreation.IsDeclaredRole`) in their own + choreography, because the seed handlers' declaration, prerequisite and guard + plumbing is the part that differs. What is duplicated is the order of the steps, not + a domain rule. +10. **The ticket is not recorded.** The gate validates the optional ticket's grammar and + the five acts record it nowhere, because + [ADR-0101](0101-platform-operator-authority.md) § 9 keeps it only on tenantless + sentinel rows and these acts write none; the audit rows carry the correlation id the + answer returns, and the operator keeps the ticket beside it. +11. **Request shape.** Every identifier is a UUIDv7 and the platform sentinel is refused as a tenant (400). A host mapping must state both `isActive` and `isPubliclyLive`, because no act unmaps a host. A blank provider subject or one over 255 characters is - a 400, and a refused storage write answers in the vocabulary the sibling Identity - handlers use (`concurrency_conflict`, `dependency_unavailable`, or - `identity_foundation_refused`). + a 400, template and scope names are matched exactly and not parsed, and a refused + storage write answers in the vocabulary the sibling Identity handlers use + (`concurrency_conflict`, `dependency_unavailable`, or + `identity_foundation_refused`). An unqualified identity authority is + `dependency_unavailable`, and every 503 an act answers carries `Retry-After`. The Tenancy writes of the two Tenancy acts classify + only a unique violation: a lock timeout on a unique-index wait, as when two operators + map one host to two tenants at once, surfaces as a 500, and the same request repeated + gets the right answer. A host mapping needs only that the tenant exists and is not + deleted, where the Identity acts also need it to be Trial or Active. The business actor of every written row is `UserId.SystemActor` and the audit actor is NULL, as § 3 and [ADR-0101](0101-platform-operator-authority.md) § 9 say. A refused diff --git a/docs/glossary.md b/docs/glossary.md index 0b2fc189..53abe4c9 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -13,6 +13,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | | **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | +| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act runs in the platform scope; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | | **Org Admin** | A user with administrative rights inside a single organization within a tenant. | @@ -496,7 +497,6 @@ and recurrence definitions remain empty. | **Grace Period** | The 30-day window during which an instance keeps operating after the last successful phone-home. Bounded by `grace_until` in the **durable** `platform_entitlement_cache` row — never by a cache TTL. Collapsing the two makes the advertised 30 days into 15 minutes; see [26-hybrid-license-model.md § 5](architecture/26-hybrid-license-model.md). | | **Platform Entitlement Cache** | The `platform_entitlement_cache` table in LearnStack core — the **durable** read-only mirror of the Hub-side Entitlement Aggregate, carrying `valid_until` and `grace_until`. Despite the name it is a projection store, not a cache: the volatile layers are L1 and L2 in front of it. Third in the normative read path `L1 → L2 → platform_entitlement_cache → Hub` ([ADR-0034](decisions/0034-hub-contract-surface-invariant.md)). Eager-invalidated on the entitlement-updated event. The only sanctioned reader **and** writer is an `IEntitlementProvider` implementation; no module — Tenancy included — may query it (`Modules_Do_Not_Read_Entitlement_Cache_Directly`), and `IFeatureFlags` reaches the projection through the provider rather than through this table ([ADR-0045 § 2](decisions/0045-entitlement-and-feature-flag-socket.md)). | | **Operator Portal** | `operator-portal` — the separate Next.js app for Hub operators. Authenticates against the `learnstack-hub` Keycloak realm. | -| **Operator act** | One of the platform operator's production onboarding operations of [ADR-0102](decisions/0102-production-tenant-onboarding.md): provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator. The gate admits one operation per act, and the executor runs it on the application role through the ordinary pipeline under the target tenant's resolved ambient context. Its only authorization source is `PlatformOperator`: not a Seed act, not a Membership act. Idempotent on operator-supplied identifiers. | ## Decision Records diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index e14a433d..fcf78194 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -81,8 +81,11 @@ The internal binding service uses explicit startup qualification and fresh, physically read-only existing-binding transactions; it never creates a missing binding. Fixed seed adoption separately requires its confined admission port. Real provider/app-role, schema/body/ACL/caller and physical outcome controls are -implemented. The directory contract appears below; closure, -production first-admin and issuer rebind retain their named later owners. +implemented. The directory contract appears below; closure and issuer rebind +retain their named later owners. Production first-admin, Role-template initialization +and recovery are the operator acts of +[ADR-0102](../../decisions/0102-production-tenant-onboarding.md) +([runbook](../../runbooks/tenant-onboarding.md)). ### Retained provider-event storage @@ -339,12 +342,19 @@ P03-1 admits only the fixed development-seed capability. in API composition. The external seed/demo owner supplies bounded canonical manifest facts and actual provider-adoption witnesses to the confined Seeder implementation. Email, a realm role or SystemActor alone supplies no admission. -There is no HTTP entry, operator population or general bootstrap bypass. - -Production first-admin/provisioning admission is **P03-9/G13**, before a -production provisioner uses it. Its authority/recovery cannot inherit the seed -capability. Tenancy's current ProvisionTenant remains the ADR-0042 Tenant/default -Organization pair; no cross-module transaction or further exception is admitted. +The seed capability has no HTTP entry, operator population or general bootstrap +bypass. + +Production first-admin, Role-template initialization and recovery are the operator +acts of [ADR-0102](../../decisions/0102-production-tenant-onboarding.md) (P03-9 Step +2): `OperatorInitializeRoleCommand`, `OperatorCreateFirstAdminCommand` and +`OperatorRecoverAdminCommand`. They are admitted per act by the platform operator +gate, run under the `PlatformOperator` authorization source on the application role +and the ordered locks of ADR-0074, and name the person by provider subject through +the confined resolver definer. They cannot inherit the seed capability: neither source +is sufficient for the other's request. Tenancy's ProvisionTenant remains the ADR-0042 +Tenant/default Organization pair; the operator's provisioning is the same handler +class, and no cross-module transaction or further exception is admitted. 1. The external seed owner completes Tenancy acts and ADR-0072 trusted binding adoption, preserving all four actor/provider IDs, credentials and MFA. @@ -884,13 +894,15 @@ permission cache/session grant cannot replace a fresh check. ## Risks and open questions -Branch-specific Role configuration reopens ADR-0073. Accepted ADR-0076/0077 own -live delegation, default deny/revocation, reader handoff and trusted evidence. -Those mechanisms and the bounded scope transitions/DTOs are implemented, as are the -verified invitation writers of [ADR-0093](../../decisions/0093-verified-invitation-acceptance-and-handoff.md); -[Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification. -P03-5 dynamic values, P03-9 production first-admin/recovery and P03-10 -closure/locators remain named later writers, not implicit foundation authority. +Branch-specific Role configuration reopens ADR-0073. Accepted ADR-0076/0077 own live +delegation, default deny/revocation, reader handoff and trusted evidence. Those +mechanisms and the bounded scope transitions/DTOs are implemented, as are the verified +invitation writers of +[ADR-0093](../../decisions/0093-verified-invitation-acceptance-and-handoff.md); +[Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification. P03-5 +dynamic values and P03-10 closure/locators remain named later writers, not implicit +foundation authority; P03-9's production first-admin and recovery are the operator acts +above. | Subject/control | Current state | Owner / scope | |---|---|---| diff --git a/docs/modules/tenancy/README.md b/docs/modules/tenancy/README.md index 5be3dcdc..684ea4db 100644 --- a/docs/modules/tenancy/README.md +++ b/docs/modules/tenancy/README.md @@ -616,6 +616,15 @@ inserts the default `organizations` row, updates `tenants.default_organization_id`, and returns; the behavior completes the scope, which commits. One transaction, one connection, one commit point. +**The operator's production provisioning** +([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) is +`OperatorProvisionTenantCommand`, handled by this same class. It carries no +`IProvisionsTenant` announcement: the operator act executor installs a resolved ambient +context for the new tenant's id, which the ordinary transaction behavior announces, and +the self-keyed insert policy admits it the same way. The operator's host mapping +(`OperatorMapHostCommand`) shares `MapHostToTenantCommandHandler` likewise. Both are +idempotent on the operator's identifiers and refuse a repeat that changes a value. + **The handler opens nothing and announces nothing.** Both belong to `TransactionBehavior`, and the distinction is not stylistic. A `BeginTransactionAsync` from inside a handler is a *joiner* — [ADR-0040](../../decisions/0040-ambient-unit-of-work.md) diff --git a/docs/runbooks/killswitch.md b/docs/runbooks/killswitch.md index 7d4d9451..ce8091e4 100644 --- a/docs/runbooks/killswitch.md +++ b/docs/runbooks/killswitch.md @@ -105,9 +105,9 @@ Confirm by the response (`after` is `true`) and by the result row. | 503 | The audit row could not be written, so the table was not changed | Repeat the request after `Retry-After` | | 500 | Something failed unexpectedly: the platform credential is missing, or the final commit's outcome is unknown and the flip may have landed. The instance still dropped its cached copy | Read the switch's row (above) before repeating | -An admission with neither a matching `results_total` increment nor an -`audit_failures_total` increment is an act whose outcome is unknown; read the row for it -too. +For a killswitch act, an admission with neither a matching `results_total` increment nor +an `audit_failures_total` increment is an act whose outcome is unknown; read the row for +it too. The onboarding acts are counted by `acts_total` and are not judged this way. ## Not recoverable here diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 3e1ebb75..e75f8709 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -154,10 +154,11 @@ production realm. | 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached: at start, or for more than 15 minutes after its keys were last fetched | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | | 403 | The token is good and this operator holds no grant for the act | Ask for the grant | | 400 | The ticket or the body is malformed | Fix the request | -| 404 | Unknown killswitch key, or the surface is not configured | Check the key and the issuer setting | +| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, or the surface is not configured | Check the key or the tenant and the issuer setting | +| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant) | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) | | 415 | The body is not `application/json` | Send the header shown above | | 503 | The audit row could not be written, so nothing changed. `Retry-After` says when to try again | Retry; the act is safe to repeat | -| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)) | +| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request | The answer to a refused credential is always the same; the reason is in the signals, not the response. @@ -168,7 +169,8 @@ the response. |---|---| | `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate; `operation` is the audit slug, for example `tenancy.killswitch.toggle` | | `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `request_aborted`, `metadata_stale`, `metadata_unavailable`, `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_algorithm`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `invalid_ticket`, `missing_permission`, `unknown_operation`, `invalid_witness` | -| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed | +| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by the platform scope, so the killswitch act only | +| `learnstack_platform_operator_acts_total{operation,outcome}` | Onboarding acts by how they ended (`applied`, `replayed`, `refused`, `failed`); see the [onboarding runbook](tenant-onboarding.md#signals) | | `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | | `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs, new keys are not learned; a fetch that failed is not retried for 30 seconds, and once the keys held are more than 15 minutes old with a later fetch failed, every operator is refused (`metadata_stale`) | @@ -176,12 +178,16 @@ A log line accompanies each. Search by event id: 7102 (Warning) a refused act, 7 (Warning) a refused credential with its cause, 7106 (Warning) a metadata failure, 7105 (Error) a refused audit write, and 7101 (Error) a grant configuration that failed validation on reload; while 7101 appears every operator act is refused until the -configuration is valid. Every admitted platform act logs a Warning with event 7001 and +configuration is valid. Every admitted killswitch act logs a Warning with event 7001 and the text "Platform-admin scope entered" (other hosts reuse the number for unrelated -lines, so match the text too). A refused operator leaves no database row. +lines, so match the text too); the onboarding acts do not enter the platform scope and +log no 7001. Event 7109 (Warning) is an onboarding act the request pipeline itself +refused as forbidden. A refused operator leaves no database row; the one exception is an +onboarding act an admitted operator had refused for a business reason, which writes a +`failed` row in the tenant. ## Not recoverable here -A refusal leaves no record in the audit log, only the counter and the log line. An -operator cannot grant themselves anything: grants are configuration, edited by whoever -deploys it. +A refusal at the gate leaves no record in the audit log, only the counter and the log +line. An operator cannot grant themselves anything: grants are configuration, edited by +whoever deploys it. diff --git a/docs/runbooks/tenant-onboarding.md b/docs/runbooks/tenant-onboarding.md index e71a2c95..16221c39 100644 --- a/docs/runbooks/tenant-onboarding.md +++ b/docs/runbooks/tenant-onboarding.md @@ -19,7 +19,9 @@ tenant's own row security, through the same pipeline a request uses. You also need, before you start: - A tenant id, an organization id, a role id per template and a membership id, each a - **UUIDv7** that you generate. The ids are the acts' identity: sending an act again + **UUIDv7** that you generate (`psql -At -c 'SELECT uuidv7()'` against any PostgreSQL + 18, including the local stack's; `uuidgen` makes a version 4, which is refused with a + `400` that names no field). The ids are the acts' identity: sending an act again with the same ids is a retry and never a second write. - A slug for the tenant and for its default organization, and the host the tenant will answer on. @@ -74,7 +76,10 @@ act that has not been answered `200`. It refuses any tenant that has had a tenant-wide Membership, so it cannot add an administrator to a tenant that has members. -The `ticket` in each body is optional, and is the operator's own reference. Every answer +The `ticket` in each body is optional and is the operator's own reference: LearnStack +validates its grammar and **does not record it** (it is kept only on the platform's +tenantless rows, which these acts do not write), so keep it with the correlation id in +your own change record. Every answer is `200 { "result": ..., "correlationId": "..." }`. Keep the correlation id. ## Recovering a tenant with no administrator @@ -99,7 +104,7 @@ leaves the last-administrator guard as it found it. |---|---|---| | 400 | `validation_failed` | The body is malformed, a value is out of its grammar, an id is not a UUIDv7 (or is the platform sentinel), a host mapping omits a flag, the `providerSubject` is blank or over 255 characters, or the ticket is not 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -` | | 401 | | The token does not meet the profile; there is one answer for every cause, and the cause is in the operator's signals | -| 403 | | The token is good and the operator holds no grant for this act | +| 403 | | The token is good and the operator holds no grant for this act. An admitted act the request pipeline itself refused as forbidden also answers `403`; that is a defect, not a grant, and logs event 7109 | | 404 | | The tenant does not exist, or the act can no longer see it. Provision first | | 409 | `lockey_slug_taken`, `lockey_identifier_taken` | Another tenant has the slug, or an id is already used by a different record. Use another value; an exact repeat of your own act is a `200` | | 409 | `lockey_bootstrap_required` | The named person has not signed in at the tenant's host (or is not Active). Ask them to sign in, then repeat | @@ -110,8 +115,13 @@ leaves the last-administrator guard as it found it. | 409 | `lockey_host_taken` | The host is mapped to another tenant, or to this one with other flags; the answer never says which | | 409 | `lockey_host_reserved` | The host is a platform host and can never resolve to a tenant | | 409 | `lockey_organization_not_in_tenant` | The `organizationId` of a host mapping is not one of this tenant's | -| 409 | `lockey_concurrency_conflict` | Another change won, or a lock timed out; repeat the same request. If it repeats, a second template of the same key and scope already exists | -| 503 | | The audit row could not be written or a dependency could not answer, so nothing changed. Retry after a short delay | +| 409 | `lockey_concurrency_conflict` | Another change won, or a statement's lock timed out; repeat the same request. If it repeats, a second template of the same key and scope already exists | +| 503 | | The audit row could not be written, or the act could not take its ordered tenant lock (`lockey_dependency_unavailable`), so nothing changed. Retry after a short delay | + +The reason of a `409` is in the problem's `errors`, keyed by the body field it concerns, +as `{"slug": [{"key": "lockey_slug_taken"}]}`, or by `$` when it concerns the tenant as +a whole, as `{"$": [{"key": "lockey_tenant_has_memberships"}]}`. A `400` raised at the +gate or by a route check carries no `errors`. A business refusal of an admitted act (a `409`) writes a `failed` audit row in the tenant, so the attempt is on the record. A refusal at the gate (`401`, `403`, or a `400` @@ -159,8 +169,22 @@ The operator's digest is computed as in [Killswitch](killswitch.md#reading-the-r `applied`, `replayed`, `refused` or `failed`; a `replayed` count is a setup resumed at that step. Event 7109 (Warning) means an admitted act was refused as forbidden by the request pipeline itself, which is a defect and not an operator mistake, and which writes -no audit row. The gate's counters and events 7101 to 7108 are in -[operator access](operator-access.md). +no audit row. The gate's counters and events 7101 to 7103, 7105 and 7106 are in +[operator access](operator-access.md); 7104, 7107 and 7108 belong to the killswitch. + +## Not recoverable here + +- **A host mapping's flags and organization pin.** No act updates or removes a mapping, + and a repeat that changes a flag or the pin is refused as `lockey_host_taken`. A + mistaken mapping stays until the platform owner repairs it at the database; escalate. +- **A wrong administrator.** A mistyped `sub` makes that person the administrator, and + this surface has no act to remove or replace them: the first administrator and + recovery both refuse once an administrator is active, and the database refuses to + revoke the last one. Confirm the `sub` before step 5, and escalate a mistake. +- **A tenant.** Nothing here renames, suspends or deprovisions one, or moves it to + another issuer. +- **Role templates after the first Membership.** They can no longer be created here; + the tenant's own administrators edit them. ## What this does not do diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 8a89771a..65192621 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -5658,7 +5658,10 @@ setter. The [federation host-alias read](#federation-host-alias-read) is the fou logical setter; it adds no definer and no physical context writer. The [operator subject resolution](#operator-subject-resolution) is the sixteenth definer; it adds no logical tenant setter. The operator act executor that installs an operator act's -resolved context is the fifth writer of the context accessor +resolved context is a fifth logical writer of the context accessor, beside the four of +[ADR-0036 Amendment 2](../decisions/0036-tenant-resolution-trusted-inputs.md) (the Hub +correlation writer is the one not yet built); the earlier counts in this section +describe their own slices ([ADR-0040 Amendment 25](../decisions/0040-ambient-unit-of-work.md)). ### Invitation root and constrained transitions @@ -6275,8 +6278,10 @@ answers exactly that: else, and it writes nothing. - **Caller.** `OperatorSubjectResolver`, which derives the key with the one `IdentitySubjectKey` implementation under the deployment's qualified authority, so a - request supplies the provider subject and nothing else. The exact SQL, ACL, owner and - caller are pinned by the definer census (sixteen definers). + request supplies the provider subject and nothing else. The body, ACL, owner and + volatility are pinned by the definer census (sixteen definers), and the callers of the + function and of its port by + [`Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject`](21-architecture-tests-catalogue.md#only_the_operator_administrator_core_resolves_an_operator_subject). A Membership written under that answer still passes the ordinary admission guard, which re-reads the User's eligibility under the user fence, so the resolver is a lookup and diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 88279778..0842b044 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**382 test methods run in +**383 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**286 rules in this catalogue are Implemented, and 168 of them are in that assembly.** +**287 rules in this catalogue are Implemented, and 169 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -5951,6 +5951,23 @@ structural test proves — and what it does not. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 2). - **Phase:** P03-9. +#### `Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject` + +- **Asserts:** the files, by their path under `backend/src`, that name + `fn_identity_operator_resolve_user` in code are exactly the adapter that calls it and + the migration helper that installs it, and the files that name + `IOperatorSubjectResolver` are exactly the port, the operator administrator core, the + registration and the adapter. A second caller is a second way to ask whether a + provider subject is an Active user; adding one is a deliberate edit here, with its + denied proof. +- **Why it matters:** the definer is executable by the application role, so what may ask + it is what the code, and not the database, confines + ([Database Standards § Operator subject resolution](05-database.md#operator-subject-resolution)). +- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 5. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityFoundationConventionTests`, P03-9 Step 2). +- **Phase:** P03-9. + #### `Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer` - **Asserts:** the write verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` From fd11198ead445046986f2b4b5377ffd58c66d184 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 00:03:48 +0300 Subject: [PATCH 11/28] docs(roadmap): record P03-9 step 2 delivery, reviews and proof Appends the Step 2 implementation record, review round 1 and round 2 to the Phase 03 delivery log with the final-code proof (178 heavy architecture cases and the full 4,478-case Integration suite), and moves the packet's Status row to steps 1 and 2 delivered. Co-Authored-By: Claude Sonnet 5.5 --- docs/roadmap/phase-03-delivery-log.md | 212 +++++++++++++++++++++++- docs/roadmap/phase-03-identity-admin.md | 2 +- 2 files changed, 212 insertions(+), 2 deletions(-) diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 6aaba743..5ec90910 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,12 +509,15 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 595 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 802 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 107 lines - [P03-9 Step 1 — review round 2 and its fixes (2026-11-19)](#p03-9-step-1--review-round-2-and-its-fixes-2026-11-19) — 116 lines + - [P03-9 Step 2 — production onboarding (2026-11-19)](#p03-9-step-2--production-onboarding-2026-11-19) — 126 lines + - [P03-9 Step 2 — review round 1 and its fixes (2026-11-19)](#p03-9-step-2--review-round-1-and-its-fixes-2026-11-19) — 46 lines + - [P03-9 Step 2 — review round 2 and its fixes (2026-11-19)](#p03-9-step-2--review-round-2-and-its-fixes-2026-11-19) — 35 lines @@ -24767,3 +24770,210 @@ reported the generic wording instead, so the mutation control inside the case di match. The case passed alone, the whole class passed twice more, and the same case passed in the earlier full run on the same code, so it is recorded as an inference flake in an unrelated control and not as a defect of this change. + +### P03-9 Step 2 — production onboarding (2026-11-19) + +Step 2 delivers [ADR-0102](../decisions/0102-production-tenant-onboarding.md): five +operator acts that create a production tenant and its first administrator, on the +application role, through the ordinary request pipeline. The decisions were Accepted in +`a396f50e`; this record is the implementation and its proof. + +Delivered: + +- **A fourth trusted-operation source.** `AuthorizationSourceKind.PlatformOperator`, a + `PlatformOperatorAttribution` the descriptor carries (issuer, subject digest, `acr`, + executor, closed reason slug), and `PlatformOperatorOperationSource`, the fourth + `MintingSource`, scoped to one frame and bound to the operation of one admission. The + seed, delivery and job sources and their policies are unchanged, so neither authority + can perform the other's acts. +- **The executor.** `PlatformOperatorActExecutor` consumes the single-use admission, + refuses a request outside its closed catalog, an admission for another operation, the + platform sentinel and a stale admission before it is spent, opens a fresh scope, + installs an immutable resolved `OperatorTenantContext` for the tenant the route names, + sends the command and restores the accessor. It is the fifth writer of the context + accessor and adds no tenant setter. +- **Five commands and their handlers.** `OperatorProvisionTenantCommand` and + `OperatorMapHostCommand` are handled by the same classes as the seed commands, so the + three-write order, the conflict mapping and the one cross-aggregate exception exist + once. `OperatorInitializeRoleCommand`, `OperatorCreateFirstAdminCommand` and + `OperatorRecoverAdminCommand` are new Identity handlers. `OperatorActGuard` + (SharedKernel) restates source, context and transaction on the handler's own owner, + takes the ordered locks of [ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md) + and asks again before every write. +- **The person.** A sixteenth confined definer, `fn_identity_operator_resolve_user`, + resolves a provider subject to the `UserId` of an Active user for the stored + authority; `users` is invisible to a tenant announcement otherwise. +- **Five routes** under `/api/platform/v1/tenants/...`, each a `PUT` on + operator-supplied identifiers, so a reply lost on the wire is repaired by sending the + request again; the operator document `platform-v1` describes them. +- **Audit.** The composer, authorization context and evidence coordinator gain the + operator branch: a null actor, the closed reason slug and `metadata.operator`, no + ticket. A refused act writes the ordinary `failed` MUST row in the tenant; an + authorization refusal of an operator request writes none. +- **The Seeder refuses outside Development** (exit 2, before it reads a credential). +- **Signals.** `learnstack_platform_operator_acts_total{operation,outcome}` and event + 7109. +- **Documents.** The onboarding runbook, ADR errata and Amendments in ADR-0102, 0040, + 0036 and 0033, Standards 05, 11, 18, 19 and 21, the Identity and Tenancy module + specifications, the glossary, the seed skill and the README. + +Findings made while implementing, each fixed or recorded: + +- **ADR-0102 § 1 could not be built as written.** It promised one new confined tenant + setter and unchanged context writers. The query filters and the transaction behavior + read the accessor, so an act that is not installed in it is invisible to row security. + The executor installs the context, the ordinary behavior announces it, the setter + census stays at fourteen and the writers are five. Inline errata and + [ADR-0040](../decisions/0040-ambient-unit-of-work.md) Amendment 25 and + [ADR-0036](../decisions/0036-tenant-resolution-trusted-inputs.md) Amendment 22 record + it. The test that enumerates writers keeps its name, which three Accepted records cite. +- **The last-administrator guard makes recovery a break-glass.** The real-database proof + showed the deferred `fn_identity_complete_graph_guard` (`P0303`) rejects any commit + that leaves a tenant without an available administrator, so the state § 8 recovers + from is unreachable by revocation, and users have no update owner. The predicate is + implemented as accepted, the proof reaches the state by an owner-level repair that + steps around the guard and shows the invariant intact after the recovery, and + Amendment 1 item 4 records it. A predicate that also reads the User's eligibility needs + a second confined definer and is the maintainer's decision. +- **A refused act is audited.** Refused acts write `failed` rows in the target tenant, so + the first proof's assertion that nothing failed was wrong and the attempts are now the + evidence. +- **Row security applies to the owner.** The owner credential cannot read a tenant's rows + or the host index without announcing the tenant, and the memberships guards need the + advisory locks. The fixtures that repair state announce and lock like a handler does. +- **Six Step 1 leftovers.** The fast architecture classes had not been run over Step 1's + rounds: the metadata readers were not on the transport-holder list, the killswitch + ordering test sat under `Database/` without a Docker need, the realm-file test named + the Keycloak fixture, the endpoint built a killswitch key from the route (the registry + now resolves it), and Standard 21's counts were two methods and one rule behind. All + fixed here. +- **The pre-commit hook.** `dotnet format` adds a byte-order mark to a new C# file, which + made the stash restore conflict once, and an intent-to-add entry fails the hook; both + are recorded in the working notes, not in the repository. + +#### Proof run locally + +| Suite | Result | +|---|---| +| Unit | 4,283 passed (new: guard 14, executor 12, catalog disjointness 1) | +| Integration, `PlatformOperatorOnboardingTests` (real PostgreSQL through the actual Program, as `learnstack_app`) | 16 passed | +| Integration, `OperatorSubjectResolverTests`, `SeederDevelopmentOnlyTests`, `SeedOperationSourceTests`, `PlatformOperatorHttpTests` | 3, 7, 15 and 28 passed | +| Integration, definer, schema and migration census classes | passed after the pins moved to 16 definers and 29 functions | +| Architecture (Release), every class except the four IL-census classes | 492 passed | +| Architecture (Release, 42 min), `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests`, `BackgroundJobAdmissionBoundaryTests`, run on the final code after both review rounds | 178 passed | +| Integration, the whole suite, on the final code after both review rounds (1 h 25 min) | 4,478 passed, none failed, none skipped | + +What the real-database cases show: each act answers `200` and again `200` on a repeat; +a changed value under the same identifiers is refused; a reply lost after the commit +(the outermost behavior fails once the commit is done) and an act interrupted between +its writes both leave the state the retry then completes once; a grant is judged per act +and a refused act writes nothing; an unknown tenant is `404`; a taken slug, host or +identifier is `409`; a tenant with Membership history refuses the first administrator +and the Role templates; recovery refuses while an administrator is active, succeeds once +none is, and leaves the database's last-administrator guard as it found it; an +Organization-scope or another tenant's administrator Role does not qualify; every row +carries `actor_user_id` NULL, the closed reason slug and the operator's issuer, `acr`, +executor and subject digest, and never the person's subject, the operator's raw subject +or the ticket; the correlation id the answer returns finds the rows. + +#### Mutation checks + +Thirty-two mutations of the new guards, each applied, built, run and restored with the +restored file touched. Twenty-two were killed at once: the guard accepting a read-only or +rollback-only unit, a global identity transaction, another tenant's plan or announcement, +or a lost lock not rolling the act back; the executor ignoring the operation binding, +admitting the sentinel or a stale or reused admission, or leaving its context installed; +the source answering in another context or for another operation; the first +administrator ignoring Membership history; recovery ignoring an active administrator; +Role templates ignoring history; the resolver returning a non-Active user, accepting +another authority, another session or a short key; route ids not checked; and a +provisioning replay accepting any pair. Ten survived. Five exposed gaps in the tests and +were killed after they were strengthened: the guard allowing a user, an organization or a +host scope that was already in the context when the act began, the source ignoring the +policy's sources, and recovery accepting any Role. Five are equivalent mutants: the +guard's checks of the source kind, the policy's sources and the descriptor's liveness, +which the coordinator and the invocation already enforce (the invocation can be built +only by the coordinator, so no test can present a mismatch); the executor's refusal of a +platform-role operation, which the act catalog refuses first; and the source's +frame-open check, which the disposal of the source with the scope makes redundant. + +### P03-9 Step 2 — review round 1 and its fixes (2026-11-19) + +Three independent reviewers, each read-only, read the range from the accepted decisions +to the implementation: authority and security, correctness and concurrency, and tests, +censuses and documentation. None reported a Blocker. Each finding was checked against +the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Provisioning | A replay compared only the slug and organization id and answered with the request's organization slug, which was never stored | The replay reads the stored organization and compares the whole request; the answer is what was stored and a changed value is refused | +| Identity acts | A retry was refused when the person's state or the template had changed after the first run | The Membership and Role replays are judged before the present state, and a template edited by the new administrator no longer unmakes the original act | +| Host mapping | The retry did not drop the cached resolution again; both flags defaulted to live although the factory defaults them off and no act unmaps a host | The retry invalidates again; both flags are required | +| Routes | The platform sentinel as a tenant answered 500; a blank or over-long subject was a `409` on the wrong field; ids were checked only at the tenant | The sentinel and every identifier are checked at the route (400); the subject is checked at the route | +| Resolver | It was called before the act was known to be live | The guard's `RequireLiveAct` is asked first | +| Storage refusals | Every refusal answered `identity_foundation_refused` | They answer in the sibling handlers' vocabulary: `concurrency_conflict`, `dependency_unavailable`, or the foundation refusal | +| Signals | § 11 promised per-act counters and none existed; the code comment and Standard 18 claimed a counter and a log for a refusal inside the pipeline | The act counter and event 7109 exist; the documents say what they emit | +| HTTP/2 | A body without a content length or transfer encoding was read as absent | Only HTTP/1.x reads absence from the headers | +| Migration | The resolver migration was reversible although every recent Identity head refuses reversal | Forward-only; the rollback census names the new head | +| Documents | The ADR errata had been mangled by the 88-column reflow and sat after the span they correct | Rewritten in the form [ADR-0041](../decisions/0041-correcting-false-statements-in-accepted-adrs.md) prescribes, before the span, with the evidence and the Current authority line | +| Documents | The runbook promised a retry refusal the code did not give; Standard 05 said "no grant" and "reads no other relation" | Corrected | + +New cases: a reply lost after the commit, an act interrupted between its writes, +sentinel and malformed requests, exact template and scope names, both host flags +required, a host held by another tenant, a foreign organization, Organization-scope +templates, another tenant's Role, a retry after the Role was edited, an ineligible +person, the resolver's remaining refusals, the act counter, and the no-denial-row +coordinator case with a seed control. + +#### Recorded, not changed + +- **The user-eligibility recovery predicate.** A 17th definer; the maintainer decides. +- **The classification of the ADR-0102 § 1 correction.** Inline errata, Decision + unchanged and an Amendment; a superseding ADR was weighed and not chosen. + +#### Mutation checks + +Eleven further mutations after the fixes, each applied, built, run and restored: the +coordinator's observed-denial skip, a host replay not counted or keeping the stale cache, +a provisioning replay ignoring the display name or the organization slug, the sentinel +and any subject accepted at the route, a Role and a Membership replay not counted, and a +Membership replay judged after the Role's state were all killed. The coordinator's first +denial skip, in `RecordDenial`, survived and is an equivalent mutant: the observed-denial +path is reached first and carries its own skip. + +### P03-9 Step 2 — review round 2 and its fixes (2026-11-19) + +Three further independent reviewers, with lenses different from round 1: composition, +regression risk and the whole attack surface; SQL, row security, locks, the migration +and performance; and operability, the API contract, maintainability and the coherence of +the document set. None reported a Blocker. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Contract | A `503` answered as a result carried no `Retry-After` although the operator document declares it on every `503`; the runbook described a lock timeout as a `409` | The helper that answers a result sets it; the runbook separates the lock the act could not take from the statement that timed out | +| Contract | The operator document listed a 409 reason that does not exist, a killswitch-only 404 and 400, no 413 or 429, and no required fields for the five bodies | The request records state their required fields, the ticket grammar and the subject length; the status texts are truthful; the test asserts the required members | +| Routes | `Enum.TryParse` accepted numerals, padded names and comma lists that OR into another member | Exact names only | +| Resolver | A provider fault or an unqualified authority escaped as an unclassified exception; the definer named a variable `found` and measured a key by `length` | Classified like the sibling stores; renamed; `octet_length` | +| Census | Standard 05 claimed the resolver's callers were pinned and nothing pinned them | `Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject` | +| Maintainability | The killswitch route repeated the refusal switch and the audit-503 block; `RequestTypes` had no caller; a summary and a 255 literal were stale or duplicated | One shared helper each; the member is removed; one constant | +| Documents | The Identity and Tenancy module specifications still said no production first-admin exists; the ADR repeated the setter claim in Context, Consequences, Implementation Notes and Carriers with no erratum; the runbook had no "Not recoverable here" section; the sibling runbooks applied killswitch-only signals to every act; the seeder's rule was missing from the seed skill and README | All corrected; Amendment 1 gains the shared-cores, unrecorded-ticket and request-shape items | + +#### Recorded, not changed + +- **A lock timeout on a unique-index wait in the Tenancy writes surfaces as a 500**, as + when two operators map one host to two tenants at once. The writes classify only a + unique violation, the translating save is shared with the seed, and the same request + repeated gets the right answer. Amendment 1 item 11 says so. +- **The ticket is not recorded.** The gate validates it, the five acts store it nowhere, + and the runbook says so. +- **A host mapping needs only that the tenant exists and is not deleted**, where the + Identity acts also need Trial or Active. Whether a suspended tenant may be mapped is + the maintainer's decision. +- **A repeated act commits MUST rows with no captured change**, counted as `replayed`; a + metadata marker on the row is not built. +- **A `replayed` flag in the response** would tell an operator resuming a setup without + reading the metric; the response shape is the contract and is left as it is. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 48265e7c..67a422fa 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -37,7 +37,7 @@ > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | -> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch) and Step 2 (production onboarding) delivered and twice reviewed, Steps 3 to 5 pending | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | From e23088bf1adebdb4fda113d36ab8aca019b313af Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 00:21:19 +0300 Subject: [PATCH 12/28] feat(identity): add the issuer-rebind role, storage and freeze locks P03-9 Step 3 (ADR-0104), first part. The sixth login role learnstack_identity_rebind (roles script, compose, env example, fixtures), a forward-only Identity migration with its exact column grants, the identity_authority update policy, the users and audit_log policy arms and the trigger that refuses any change of the authority key, the shared rebind advisory lock in authority qualification and in the User-creation admission (with an explicit issuer comparison after the wait), the registered platform.identity_authority.admin permission and rebind operation, and the two witness-bound audit methods with their off-path declarations. Proof: column-privilege census, role behaviour as the role itself, key trigger, six lock-ordering cases against real PostgreSQL, the audit seam's refusals, and the gate's grant matrix. Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 16 +- .../PostgresAuditStore.cs | 81 ++++ .../Persistence/IdentityLockObservation.cs | 7 +- .../Persistence/NpgsqlUnitOfWork.cs | 36 ++ .../Audit/IAuditStore.cs | 36 +- .../Identity/IdentityAdvisoryLockKey.cs | 12 + .../IdentityAuthorityChangedException.cs | 11 + .../Platform/PlatformOperation.cs | 25 +- .../Platform/PlatformPermissions.cs | 7 +- .../Audit/IdentityAuditCatalogSource.cs | 4 + .../GlobalIdentityBindingService.Bootstrap.cs | 1 + .../Bindings/GlobalIdentityBindingService.cs | 1 + .../IdentityAuthorityQualification.cs | 8 + .../Persistence/IdentityAuthorityRebindDdl.cs | 79 ++++ ...120090000_add_identity_authority_rebind.cs | 17 + .../Database/DatabaseRoleTests.cs | 59 ++- .../Database/DisposableSchemaDatabase.cs | 2 + .../GlobalIdentitySchemaTests.Controls.cs | 4 +- .../HangfireGenerationPhaseHarness.cs | 1 + .../IdentityAuthorityRebindLockTests.cs | 260 +++++++++++++ .../IdentityAuthorityRebindStorageTests.cs | 367 ++++++++++++++++++ .../Database/IdentityPublicReadFixture.cs | 17 + .../Database/IdentityRebindAuditStoreTests.cs | 254 ++++++++++++ .../Database/MigrationRollbackTests.cs | 10 +- .../Database/PostgresFixture.cs | 7 +- .../Database/PublicReadFixture.cs | 3 +- .../Database/TenancySchemaTests.cs | 6 +- .../Identity/GlobalIdentityKeyTests.cs | 11 + .../MultiTenancy/PlatformAdminGateTests.cs | 36 +- infra/compose/README.md | 14 +- infra/compose/dev.yml | 5 +- .../compose/postgres-init/02-create-roles.sql | 40 +- 32 files changed, 1390 insertions(+), 47 deletions(-) create mode 100644 backend/src/LearnStack.SharedKernel/Persistence/IdentityAuthorityChangedException.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs diff --git a/.env.example b/.env.example index f63e6eaa..13e40acc 100644 --- a/.env.example +++ b/.env.example @@ -35,11 +35,12 @@ POSTGRES_USER=learnstack POSTGRES_PASSWORD=learnstack POSTGRES_DB=learnstack -# ─── The four database roles (ADR-0003 Amendment 3) ────────────────────── +# ─── The database roles (ADR-0003 Amendment 3, 14) ─────────────────────── # Read by infra/compose/postgres-init/02-create-roles.sql through psql's -# \getenv on first boot. Four roles and four separate login credentials; -# the role model is closed and a fifth role requires an ADR. Additional -# application-role sources do not create roles (ADR-0076/0077). +# \getenv on first boot. Four baseline roles, the confined fifth and sixth +# below, and one login credential each; the role model is closed and a further +# role requires an ADR. Additional application-role sources do not create +# roles (ADR-0076/0077). # An unset variable aborts initdb rather than creating a passwordless role. LEARNSTACK_MIGRATION_PW=learnstack-migration-dev LEARNSTACK_APP_PW=learnstack-app-dev @@ -47,6 +48,9 @@ LEARNSTACK_PLATFORM_PW=learnstack-platform-dev LEARNSTACK_OUTBOX_PW=learnstack-outbox-dev # ADR-0097 confined machine intake; no business/Platform/outbox access. LEARNSTACK_IDENTITY_INGRESS_PW=learnstack-identity-ingress-dev +# ADR-0104 offline issuer-rebind tool only; no API, worker, seeder or web host +# ever receives this credential or its connection string. +LEARNSTACK_IDENTITY_REBIND_PW=learnstack-identity-rebind-dev # ─── Baseline connection strings ──────────────────────────────────────── # Double underscore is the .NET environment spelling of `ConnectionStrings:X`. @@ -103,6 +107,10 @@ Federation__ClientSecret=learnstack-federation-admin-dev-secret # Federation__Egress__AllowedHosts__0=idp.corp.internal:8443 # IdentityEvents__RealmId= # ConnectionStrings__IdentityIngress=Host=localhost;Port=5432;Database=learnstack;Username=learnstack_identity_ingress;Password= +# The sixth role's connection string exists ONLY in the environment of the offline +# rebind tool for the minutes it runs (docs/runbooks/identity-issuer-rebind.md). +# Never place it in this file, a compose service block or a host configuration: +# ConnectionStrings__IdentityRebind=Host=;Port=5432;Database=learnstack;Username=learnstack_identity_rebind;Password= # Optional native tenant BFF (ADR-0070). Explicit false keeps the anonymous demo # independent of Keycloak. For local watch mode, opt in with true and the issuer # below; production launch requires an HTTPS issuer and a trusting private CA. diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index 07cfcebf..adf06d34 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -469,6 +469,87 @@ public async Task WritePlatformOperatorResultAsync( } } + /// + public Task WriteIdentityRebindIntentAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + WriteIdentityRebindAsync(entry, admission, connection, transaction, result: false, cancellationToken); + + /// + public Task WriteIdentityRebindResultAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + WriteIdentityRebindAsync(entry, admission, connection, transaction, result: true, cancellationToken); + + private async Task WriteIdentityRebindAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + bool result, + CancellationToken cancellationToken) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(admission); + RefuseGlobalCapture(); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + + // The same facts the role's policy arm restates in SQL, checked first so a caller error is an argument + // error rather than a database refusal: the one rebind operation, its attempt or result slug as + // declared off-path, the platform sentinel, no actor, no organization, no network or mail attribution, + // and the admitted operator and correlation id. The intent is indeterminate; the result is a success. + var operation = admission.Operation; + var slug = result ? operation.AuditSlug : operation.AttemptAuditSlug; + if (!ReferenceEquals(operation, PlatformOperations.IdentityAuthorityRebind) + || slug is null + || !_catalog.TryGetOffPath(slug, out var declared) + || declared.Operation != slug || declared.ModuleName != "identity" + || declared.OperationClass != OperationClass.Must || declared.OperationType != OperationType.SecurityEvent + || declared.EntityType is null + || entry.TenantId != TenantId.PlatformSentinel + || entry.OrganizationId is not null + || entry.Operation != declared.Operation || entry.ModuleName != declared.ModuleName + || entry.OperationClass != declared.OperationClass || entry.OperationType != declared.OperationType + || !string.Equals(entry.EntityType, declared.EntityType.Name, StringComparison.Ordinal) + || !string.Equals(entry.Reason, operation.ReasonSlug, StringComparison.Ordinal) + || entry.ActorUserId is not null || entry.ActorEmail is not null + || entry.IpAddress is not null || entry.UserAgent is not null + || entry.Outcome != (result ? AuditOutcome.Success : AuditOutcome.Indeterminate) + || !string.Equals(entry.CorrelationId, admission.Operator.CorrelationId, StringComparison.Ordinal) + || !MetadataNamesAdmittedOperator(entry, admission)) + { + throw new ArgumentException( + "The identity rebind row does not match its admission and its declared operation.", nameof(entry)); + } + + try + { + await using var command = connection.CreateCommand(); + command.CommandText = InsertSql; + command.Transaction = transaction; + + Bind(command.Parameters, entry); + + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbException failure) + { + throw new AuditWriteFailedException( + result + ? "The identity rebind result row could not be written, so the rebind must not commit." + : "The identity rebind intent row could not be written, so the rebind must not begin.", + failure); + } + } + /// /// Whether metadata.operator names exactly the admitted issuer and subject digest, /// and carries a ticket only on a sentinel-tenant row, and only the admitted one. diff --git a/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs b/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs index 943c74e5..4a19b903 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs @@ -4,7 +4,7 @@ namespace LearnStack.Infrastructure.Persistence; -public enum IdentityLockKind { Subject = 1, User = 2, Tenant = 3 } +public enum IdentityLockKind { Subject = 1, User = 2, Tenant = 3, Authority = 4 } /// Closed process signals; no scope, SQL, exception or person value is a dimension. public static class IdentityLockObservation @@ -32,6 +32,10 @@ internal static void Complete(IdentityLockKind kind, long started, Exception? fa Refusals.Add(1, new("lock_kind", Name(kind)), new("reason", outcome)); } + /// A creation that waited out a rebind and then read an issuer other than its own. + internal static void AuthorityChanged() => + Refusals.Add(1, new("lock_kind", Name(IdentityLockKind.Authority)), new("reason", "mismatch")); + /// Called once by the owning adapter when a real guard rejects its lock plan. public static void PlanFault(IdentityLockKind kind) => Refusals.Add(1, new("lock_kind", Name(kind)), new("reason", "fault")); @@ -41,6 +45,7 @@ public static void PlanFault(IdentityLockKind kind) => IdentityLockKind.Subject => "subject", IdentityLockKind.User => "user", IdentityLockKind.Tenant => "tenant", + IdentityLockKind.Authority => "authority", _ => throw new ArgumentOutOfRangeException(nameof(kind)), }; } diff --git a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs index 904fc3fa..21baf7ab 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs @@ -336,8 +336,24 @@ public async Task AcquireGlobalIdentitySubjectLockAsync(GlobalIdentityOwnerDescr if (_mode != TransactionMode.ReadWrite || _globalIdentityLocked || _globalIdentitySealed) throw new InvalidOperationException("The global identity subject lock belongs only to its fresh creation owner."); await ExecuteAsync("SET LOCAL lock_timeout = '2s'", cancellationToken); + // Fixed order, rebind before subject (ADR-0104 § 5): the offline rebind tool takes only the first key, so + // no cycle exists. A creation that waits out a rebind reads the issuer afresh under READ COMMITTED. var started = Stopwatch.GetTimestamp(); try + { + await ExecuteAsync("SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", cancellationToken, + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + IdentityLockObservation.Complete(IdentityLockKind.Authority, started); + } + catch (Exception failure) when (failure is not OutOfMemoryException and not StackOverflowException) + { + IdentityLockObservation.Complete(IdentityLockKind.Authority, started, failure); + throw; + } + + await RequireUnchangedAuthorityAsync(descriptor.Subject, cancellationToken); + started = Stopwatch.GetTimestamp(); + try { await ExecuteAsync("SELECT pg_catalog.pg_advisory_xact_lock(@key)", cancellationToken, ("key", IdentityAdvisoryLockKey.ForSubject(descriptor.Subject))); @@ -351,6 +367,26 @@ await ExecuteAsync("SELECT pg_catalog.pg_advisory_xact_lock(@key)", cancellation _globalIdentityLocked = true; } + // The qualified facts of the process that asked for the creation must still be the stored ones. A process that + // qualified before a rebind and is still running would otherwise create Users from the old realm's tokens + // once the rebind released its lock. + private async Task RequireUnchangedAuthorityAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken) + { + await using var command = _connection!.CreateCommand(); + command.CommandTimeout = 10; + command.CommandText = "SELECT authority_id, issuer FROM public.identity_authority WHERE id = 1"; + command.Transaction = (NpgsqlTransaction?)_transaction; + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken) + || reader.GetGuid(0) != subject.AuthorityId.Value + || !string.Equals(reader.GetString(1), subject.Issuer, StringComparison.Ordinal) + || await reader.ReadAsync(cancellationToken)) + { + IdentityLockObservation.AuthorityChanged(); + throw new IdentityAuthorityChangedException(); + } + } + public void EnrollGlobalIdentityContext(object context, GlobalIdentityOwnerDescriptor descriptor) { RequireWriteAllowed(); diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index d8e07b9f..25341d7f 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -5,7 +5,7 @@ namespace LearnStack.SharedKernel.Audit; /// -/// The only sanctioned way to put a row in audit_log. Ten writes, and +/// The only sanctioned way to put a row in audit_log. Thirteen writes, and /// no update. /// /// @@ -170,6 +170,40 @@ Task WritePlatformOperatorResultAsync( CancellationToken cancellationToken = default) => throw new InvalidOperationException("This audit store cannot write a platform operator result."); + /// + /// Writes the controlled issuer rebind's intent row on the offline tool's own short transaction, before the + /// rebind's main transaction begins (ADR-0104 § 8). + /// + /// + /// A witness-bound method for the one act that runs outside the pipeline and the platform scope. The + /// binds the row to the rebind operation's attempt slug, its closed reason and + /// the admitted operator; the tenant is the platform sentinel, the actor is NULL and the outcome is + /// indeterminate because the attempt's end is not yet known. The caller owns the transaction. + /// + Task WriteIdentityRebindIntentAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + throw new InvalidOperationException("This audit store cannot write an identity rebind intent."); + + /// + /// Writes the controlled issuer rebind's MUST result row on the main transaction, so it commits with the + /// issuer change or not at all (ADR-0104 § 8). + /// + /// + /// Bound like to the result slug with the outcome + /// success. A refused draft or a failed write requires the caller to roll the issuer change back. + /// + Task WriteIdentityRebindResultAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + throw new InvalidOperationException("This audit store cannot write an identity rebind result."); + /// Inserts a MUST terminal audit on the successful transition's live transaction. /// /// The producer transition store is the only caller in P02b-2. The operation diff --git a/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs b/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs index 378728de..dd1ba813 100644 --- a/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs +++ b/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs @@ -35,6 +35,18 @@ public static long ForSubject(GlobalIdentitySubject subject) return BinaryPrimitives.ReadInt64BigEndian(hash.GetHashAndReset()); } + /// + /// The one key of the controlled issuer rebind (ADR-0104 § 5): the offline tool holds it exclusively for the + /// whole of its proof, and authority qualification and the User-creation admission take it shared. + /// + public static long ForAuthorityRebind() + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes("learnstack.identity.lock.v1")); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes("authority-rebind")); + return BinaryPrimitives.ReadInt64BigEndian(hash.GetHashAndReset()); + } + private static long ForIdentifier(string kind, Guid identifier) { using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); diff --git a/backend/src/LearnStack.SharedKernel/Persistence/IdentityAuthorityChangedException.cs b/backend/src/LearnStack.SharedKernel/Persistence/IdentityAuthorityChangedException.cs new file mode 100644 index 00000000..7220a16a --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Persistence/IdentityAuthorityChangedException.cs @@ -0,0 +1,11 @@ +using LearnStack.SharedKernel.Errors; + +namespace LearnStack.SharedKernel.Persistence; + +/// +/// A creation transaction found the stored identity authority different from the facts its process qualified at +/// start, which is what a controlled issuer rebind leaves behind for a process that was not restarted (ADR-0104). +/// +/// A fixed adapter failure; it retains no issuer, authority or subject value. +public sealed class IdentityAuthorityChangedException() + : InfrastructureException("The stored identity authority no longer matches this process."); diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index 1a26534b..7e7297e2 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -11,9 +11,15 @@ namespace LearnStack.SharedKernel.Platform; public sealed record PlatformOperation { internal PlatformOperation( - string auditSlug, string reasonSlug, PermissionDefinition permission, bool needsPlatformRole) + string auditSlug, string reasonSlug, PermissionDefinition permission, bool needsPlatformRole, + string? attemptAuditSlug = null) { ArgumentException.ThrowIfNullOrWhiteSpace(auditSlug); + if (attemptAuditSlug is not null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(attemptAuditSlug); + } + ArgumentException.ThrowIfNullOrWhiteSpace(reasonSlug); ArgumentNullException.ThrowIfNull(permission); if (permission.Scope != PermissionScope.Platform) @@ -25,11 +31,18 @@ internal PlatformOperation( ReasonSlug = reasonSlug; Permission = permission; NeedsPlatformRole = needsPlatformRole; + AttemptAuditSlug = attemptAuditSlug; } /// The audit operation slug of the result row. public string AuditSlug { get; } + /// + /// The audit slug of the intent row written before the act's own transaction, or null when the act writes + /// no such row. Only an act that runs outside the request pipeline has one (ADR-0104 § 8). + /// + public string? AttemptAuditSlug { get; } + /// The closed reason slug every row of this act carries. public string ReasonSlug { get; } @@ -67,9 +80,17 @@ public static class PlatformOperations public static PlatformOperation AdminRecover { get; } = new( "identity.membership.recover_admin", "admin_recover", PlatformPermissions.TenantBootstrapWrite, false); + /// + /// Rebind the identity authority's issuer from the offline tool, which neither enters the platform scope nor + /// runs through the pipeline and writes an intent row and a result row of its own role (ADR-0104 § 8). + /// + public static PlatformOperation IdentityAuthorityRebind { get; } = new( + "identity.authority.rebind", "issuer_rebind", PlatformPermissions.IdentityAuthorityAdmin, false, + attemptAuditSlug: "identity.authority.rebind_attempt"); + /// Every registered operation. public static IReadOnlyList All { get; } = - [KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover]; + [KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover, IdentityAuthorityRebind]; /// Whether is one of the registered instances. public static bool IsRegistered(PlatformOperation? operation) => diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs index ded690a5..5b704e6d 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -32,8 +32,13 @@ public static class PlatformPermissions public static PermissionDefinition TenantBootstrapWrite { get; } = new(PermissionScope.Platform, "platform.tenant_bootstrap.write"); + /// Rebind the identity authority's issuer through the offline tool (ADR-0104). + public static PermissionDefinition IdentityAuthorityAdmin { get; } = + new(PermissionScope.Platform, "platform.identity_authority.admin"); + /// Every registered Platform permission. - public static IReadOnlyList All { get; } = [KillswitchWrite, TenantWrite, TenantBootstrapWrite]; + public static IReadOnlyList All { get; } = + [KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin]; /// Finds a registered Platform permission by its key. public static bool TryGet(string? key, out PermissionDefinition definition) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs index a47b4a9a..c8f8c949 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs @@ -88,5 +88,9 @@ public void Describe(IAuditCatalogBuilder builder) builder.Off(); builder.DeclareOffPath("identity.user.create", OperationType.SecurityEvent, OperationClass.Must, typeof(User)); builder.DeclareOffPath("identity.authorization.deny", OperationType.SecurityEvent, OperationClass.Must); + // The controlled issuer rebind (ADR-0104 § 8): an intent row on its own short transaction and a result + // row with the change, both from the offline tool's role and neither through the pipeline. + builder.DeclareOffPath("identity.authority.rebind_attempt", OperationType.SecurityEvent, OperationClass.Must, typeof(IdentityAuthority)); + builder.DeclareOffPath("identity.authority.rebind", OperationType.SecurityEvent, OperationClass.Must, typeof(IdentityAuthority)); } } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs index 5831489e..ab892c2d 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs @@ -57,6 +57,7 @@ public async Task BootstrapAsync(GlobalIdentitySubject } catch (NpgsqlException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } catch (UserBindingStorageException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } + catch (IdentityAuthorityChangedException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } catch (TimeoutException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } finally { cleanupSucceeded = await DisposeOwnerAsync(frame); } return cleanupSucceeded ? result : IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs index 44760de4..5fc6b412 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs @@ -114,6 +114,7 @@ private async Task CreateAsync(GlobalIdentitySubject subj catch (NpgsqlException) { result = StorageFailure(owner); } catch (AuditWriteFailedException) { result = StorageFailure(owner); } catch (UserBindingStorageException) { result = StorageFailure(owner); } + catch (IdentityAuthorityChangedException) { result = StorageFailure(owner); } catch (IOException) { result = StorageFailure(owner); } catch (TimeoutException) { result = StorageFailure(owner); } finally { cleanupSucceeded = await DisposeOwnerAsync(owner); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs index 6dc5add4..0b4b1b8d 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs @@ -1,4 +1,5 @@ using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identity; using System.Data; using Npgsql; @@ -36,6 +37,13 @@ private async Task QualifyCoreAsync(CancellationToken cancellationToken) await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); await using (var readOnly = new NpgsqlCommand("SET TRANSACTION READ ONLY", connection, transaction)) await readOnly.ExecuteNonQueryAsync(cancellationToken); + // Shared and first (ADR-0104 § 5): a start that overlaps a controlled issuer rebind waits for it here, + // and the next statement takes a fresh READ COMMITTED snapshot, so it compares against the new value. + await using (var rebind = new NpgsqlCommand("SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", connection, transaction)) + { + rebind.Parameters.AddWithValue("key", IdentityAdvisoryLockKey.ForAuthorityRebind()); + await rebind.ExecuteNonQueryAsync(cancellationToken); + } string database; await using (var command = new NpgsqlCommand( "SELECT current_user, authority_id, issuer, current_database() FROM public.identity_authority WHERE id = 1", connection, transaction)) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs new file mode 100644 index 00000000..6bb39565 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs @@ -0,0 +1,79 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The storage the offline issuer-rebind tool needs and nothing else (ADR-0104 § 2, § 7, § 8). +/// +/// +/// +/// learnstack_identity_rebind is a login role without BYPASSRLS that no runtime host +/// holds. It reads identity_authority, may change its issuer column and no other, reads +/// the four users columns the continuity proof compares, and inserts audit_log rows that +/// one policy arm limits to the platform sentinel, the identity module and the two rebind operations. +/// +/// +/// One permissive policy per command: the read policy gains the role, a third policy admits its +/// update, the users and audit_log isolation policies each gain one arm, and a second +/// permissive policy is never added. The trigger refuses any change of id or +/// authority_id for every role, so the stable key the subject keys hash cannot move; the issuer +/// grammar stays in the tool and in qualification, not in SQL. +/// +/// +internal static class IdentityAuthorityRebindDdl +{ + internal static void Add(MigrationBuilder migration) => migration.Sql(""" + GRANT SELECT ON public.identity_authority TO learnstack_identity_rebind; + GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind; + GRANT SELECT (authority_id, subject_key, provider_subject, status) ON public.users TO learnstack_identity_rebind; + GRANT INSERT ON public.audit_log TO learnstack_identity_rebind; + + ALTER POLICY identity_authority_read ON public.identity_authority + USING (current_user IN ('learnstack_app','learnstack_migration','learnstack_identity_rebind')); + CREATE POLICY identity_authority_rebind ON public.identity_authority FOR UPDATE + USING (current_user='learnstack_identity_rebind' AND id=1) + WITH CHECK (current_user='learnstack_identity_rebind' AND id=1); + + ALTER POLICY users_isolation ON public.users + USING ((current_user='learnstack_app' + AND authority_id::text=NULLIF(current_setting('app.identity_authority_id',true),'') + AND encode(subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key',true),'')) + OR current_user='learnstack_migration' + OR current_user='learnstack_identity_rebind'); + + ALTER POLICY audit_log_isolation ON public.audit_log + WITH CHECK ( + (tenant_id = NULLIF(current_setting('app.tenant_id',true),'')::uuid + AND ((organization_id IS NULL AND NULLIF(current_setting('app.organization_id',true),'') IS NULL) + OR organization_id = NULLIF(current_setting('app.organization_id',true),'')::uuid)) + OR (current_user='learnstack_app' + AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid + AND organization_id IS NULL AND module='identity' AND operation='identity.user.create' + AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='User' + AND outcome IN ('success','failed','indeterminate') + AND metadata->>'identity_source' IN ('identity-bootstrap','identity-seed-adoption') + AND metadata->>'identity_authority_id'=NULLIF(current_setting('app.identity_authority_id',true),'') + AND metadata->>'identity_subject_key'=NULLIF(current_setting('app.identity_subject_key',true),'')) + OR (current_user='learnstack_identity_rebind' + AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid + AND organization_id IS NULL AND module='identity' + AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='IdentityAuthority' + AND reason='issuer_rebind' AND actor_user_id IS NULL + AND actor_email IS NULL AND ip_address IS NULL AND user_agent IS NULL + AND metadata->'operator' IS NOT NULL + AND ((operation='identity.authority.rebind_attempt' AND outcome='indeterminate') + OR (operation='identity.authority.rebind' AND outcome='success')))); + + CREATE FUNCTION public.fn_identity_authority_immutable_key() RETURNS trigger + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + IF NEW.id IS DISTINCT FROM OLD.id OR NEW.authority_id IS DISTINCT FROM OLD.authority_id THEN + RAISE EXCEPTION 'The identity authority key cannot change.' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_authority_immutable_key() FROM PUBLIC; + CREATE TRIGGER tg_identity_authority_immutable_key BEFORE UPDATE ON public.identity_authority + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_authority_immutable_key(); + """); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs new file mode 100644 index 00000000..dd093e2c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs @@ -0,0 +1,17 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261120090000_add_identity_authority_rebind")] +public sealed class add_identity_authority_rebind : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => IdentityAuthorityRebindDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0104): like every recent Identity head, the rebind grants and the key trigger are + // retired by a reviewed forward migration, so a reversal cannot silently leave an issuer writable. + throw new NotSupportedException("The issuer-rebind storage requires a reviewed forward migration."); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs index 44bd3d61..24ab68b0 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs @@ -43,6 +43,7 @@ public async Task ThePublishedDatabasePortIsExclusivelyLoopback() [InlineData("learnstack_platform", true)] [InlineData("learnstack_outbox_admin", true)] [InlineData("learnstack_identity_ingress", false)] + [InlineData("learnstack_identity_rebind", false)] public async Task EachRoleExistsWithItsDeclaredBypassPosture(string role, bool expectedBypass) { await using var connection = await PostgresFixture.OpenAsync(_postgres.MigrationConnectionString); @@ -194,8 +195,9 @@ public async Task ABypassRoleWithNoGrantIsStillRefused() [Fact] public async Task EveryRoleCredentialActuallyLogsIn() { - // All four, including learnstack_outbox_admin, whose connection string no - // other case opens. A password the script never set, or set to something + // All six, including learnstack_outbox_admin, whose connection string no + // other case opens, and the two confined roles (ADR-0097, ADR-0104), whose + // credentials only their own tools use. A password the script never set, or set to something // else, is invisible until the dispatcher tries to start — in Phase 02b, // far from here. // Compared against the EXPECTED role, not against one derived from the same @@ -210,6 +212,8 @@ public async Task EveryRoleCredentialActuallyLogsIn() ("learnstack_app", _postgres.AppConnectionString), ("learnstack_platform", _postgres.PlatformConnectionString), ("learnstack_outbox_admin", _postgres.OutboxConnectionString), + ("learnstack_identity_ingress", _postgres.IdentityIngressConnectionString), + ("learnstack_identity_rebind", _postgres.IdentityRebindConnectionString), ]; foreach (var (expected, connectionString) in roles) @@ -226,7 +230,7 @@ public async Task EveryRoleCredentialActuallyLogsIn() public async Task PublicHoldsNoConnectPrivilegeOnTheDatabase() { // PUBLIC holds CONNECT and TEMPORARY on every database by default, so the - // script's four explicit grants add nothing until that default is revoked. + // script's explicit grants add nothing until that default is revoked. // Asserted because nothing else in this suite would notice: removing the // REVOKE from the script leaves all the other cases green, which was // measured — the grants and the roles are unaffected, only the reach is. @@ -249,7 +253,7 @@ public async Task PublicHoldsNoConnectPrivilegeOnTheDatabase() entries.Should().NotBeEmpty("an ACL of NULL means PostgreSQL's permissive default is still in force"); entries.Should().NotContain(e => e.StartsWith('='), - "PUBLIC must hold no privilege on this database; the four explicit grants are the whole of the reach"); + "PUBLIC must hold no privilege on this database; the explicit grants are the whole of the reach"); entries.Should().Contain(e => e.StartsWith("learnstack_app="), "and learnstack_app must still hold the CONNECT it was granted"); } @@ -303,6 +307,51 @@ public async Task TheRolesScriptTakesBackAnEscalatedAttribute() } } + [Fact] + public async Task TheRebindRoleIsNoInheritMemberOfNothingAndTheScriptTakesBackItsEscalation() + { + // The sixth role (ADR-0104) is bounded by its few grants and its policy arms and + // by nothing it could inherit, so an out-of-band INHERIT, BYPASSRLS or membership + // would make those bounds meaningless while every grant census still read correctly. + try + { + await _postgres.ExecuteAsSuperuserAsync( + "ALTER ROLE learnstack_identity_rebind INHERIT BYPASSRLS; " + + "GRANT learnstack_migration TO learnstack_identity_rebind; " + + "GRANT learnstack_identity_rebind TO learnstack_app"); + + (await RebindPostureAsync()).Should().Be((true, true, true, true), "the escalation must be real for the test to mean anything"); + + var result = await _postgres.RunRolesScriptAgainAsync(); + result.ExitCode.Should().Be(0, "{0}", result.Stderr); + + (await RebindPostureAsync()).Should().Be((false, false, false, false), + "re-running the script restores NOINHERIT NOBYPASSRLS and revokes every membership in both directions"); + } + finally + { + await _postgres.ExecuteAsSuperuserAsync( + "ALTER ROLE learnstack_identity_rebind NOINHERIT NOBYPASSRLS; " + + "REVOKE learnstack_migration FROM learnstack_identity_rebind; " + + "REVOKE learnstack_identity_rebind FROM learnstack_app"); + } + } + + private async Task<(bool Inherit, bool Bypass, bool MemberOfOwner, bool ApplicationIsMember)> RebindPostureAsync() + { + await using var connection = await PostgresFixture.OpenAsync(_postgres.MigrationConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT r.rolinherit, r.rolbypassrls, + pg_has_role('learnstack_identity_rebind', 'learnstack_migration', 'MEMBER'), + pg_has_role('learnstack_app', 'learnstack_identity_rebind', 'MEMBER') + FROM pg_roles r WHERE r.rolname = 'learnstack_identity_rebind' + """, (NpgsqlConnection)connection); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return (reader.GetBoolean(0), reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3)); + } + [Theory] // Directly, and through a bridge role that holds the membership on the // application role's behalf — because a fix keyed on the four names would @@ -339,7 +388,7 @@ await _postgres.ExecuteAsSuperuserAsync( result.ExitCode.Should().Be(0, "{0}", result.Stderr); (await ReachesABypassRoleAsync()).Should().BeFalse( - "re-running the script revokes every membership the four roles hold"); + "re-running the script revokes every membership the six roles hold"); } finally { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs b/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs index 7020b606..2e600621 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs @@ -22,12 +22,14 @@ private DisposableSchemaDatabase(PostgresFixture postgres) AppConnectionString = For(postgres.AppConnectionString); PlatformConnectionString = For(postgres.PlatformConnectionString); OutboxConnectionString = For(postgres.OutboxConnectionString); + IdentityRebindConnectionString = For(postgres.IdentityRebindConnectionString); } public string MigrationConnectionString { get; } public string AppConnectionString { get; } public string PlatformConnectionString { get; } public string OutboxConnectionString { get; } + public string IdentityRebindConnectionString { get; } public static async Task CreateAsync( PostgresFixture postgres, bool applyMigrations = true) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index e7d13f4f..c32ca8b0 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -407,12 +407,12 @@ private static CanonicalFunction[] CompiledFunctions() : attributes.Contains("STABLE", StringComparison.Ordinal) ? "s" : "v", attributes.Contains("STRICT", StringComparison.Ordinal)); }).OrderBy(function => function.Name, StringComparer.Ordinal).ToArray(); - functions.Should().HaveCount(29, "the closed set includes three provider definers, one target transition guard, the federation connection guard and the operator resolver"); + functions.Should().HaveCount(30, "the closed set includes three provider definers, one target transition guard, the federation connection guard, the operator resolver and the identity authority key guard"); functions.Count(function => function.Definer).Should().Be(16); functions.Single(function => function.Name == "fn_tenancy_own_field_consent_scope").Signature .Should().Be("public.fn_tenancy_own_field_consent_scope(uuid,uuid,uuid,text,uuid,uuid,integer)", nameof(MembershipFieldConsentStorageTests.Definer_scope_is_subject_and_host_capped_with_a_closed_bounded_interface)); - functions.SelectMany(function => function.Triggers).Should().HaveCount(29); + functions.SelectMany(function => function.Triggers).Should().HaveCount(30); var globalNames = EffectiveFunctionDeclarations(migrationSql[0]) .Select(match => match.Groups["name"].Value.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); globalNames.Should().NotBeEmpty("the first Identity migration installs its confined global functions"); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs b/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs index c32793c9..77958cb6 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs @@ -76,6 +76,7 @@ internal static async Task RunAsync(string scenario, st .WithEnvironment("LEARNSTACK_PLATFORM_PW", Guid.NewGuid().ToString("N")) .WithEnvironment("LEARNSTACK_OUTBOX_PW", outboxPassword) .WithEnvironment("LEARNSTACK_IDENTITY_INGRESS_PW", Guid.NewGuid().ToString("N")) + .WithEnvironment("LEARNSTACK_IDENTITY_REBIND_PW", Guid.NewGuid().ToString("N")) // Module commands append to its existing PostgreSQL arguments; // an extra executable token would become an invalid argument. .WithCommand("-c", "log_min_messages=panic", "-c", "log_min_error_statement=panic", diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs new file mode 100644 index 00000000..8ac1ec74 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs @@ -0,0 +1,260 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The freeze of ADR-0104 § 5 against real PostgreSQL: authority qualification and the User-creation admission +/// take the shared form of the rebind lock, wait for a running rebind and then read the value it left. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindLockTests(PublicReadFixture parent) +{ + private const string OldIssuer = "https://old.example.test/realms/learnstack"; + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task A_start_that_overlaps_a_rebind_waits_for_it_and_then_fails_on_the_new_issuer() + { + await using var proof = await Proof.CreateAsync(parent); + var qualification = proof.Qualification(proof.Old); + await using var rebind = await proof.BeginRebindAsync(); + + var start = qualification.QualifyAsync(); + await proof.WaitForSharedWaiterAsync(); + start.IsCompleted.Should().BeFalse("the start waits for the lock and does not read the old value"); + + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + + var act = async () => await start; + (await act.Should().ThrowAsync()) + .Which.Message.Should().Be("Identity authority startup qualification is unavailable or does not match deployment configuration."); + qualification.Current.Should().BeNull("a failed qualification stays failed until the process restarts"); + + await proof.Qualification(proof.Renamed).QualifyAsync(); + } + + [Fact] + public async Task A_start_that_overlaps_a_rebind_that_rolls_back_qualifies_against_the_unchanged_issuer() + { + await using var proof = await Proof.CreateAsync(parent); + var qualification = proof.Qualification(proof.Old); + await using var rebind = await proof.BeginRebindAsync(); + await rebind.ChangeIssuerAsync(NewIssuer); + + var start = qualification.QualifyAsync(); + await proof.WaitForSharedWaiterAsync(); + await rebind.RollbackAsync(); + + await start; + qualification.Current.Should().Be(proof.Old); + } + + [Fact] + public async Task A_start_that_follows_a_committed_rebind_with_the_old_configuration_is_refused_without_waiting() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var rebind = await proof.BeginRebindAsync()) + { + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + } + + var act = async () => await proof.Qualification(proof.Old).QualifyAsync(); + await act.Should().ThrowAsync(); + await proof.Qualification(proof.Renamed).QualifyAsync(); + } + + [Fact] + public async Task A_creation_during_a_rebind_is_refused_within_its_lock_timeout_and_binds_nobody() + { + await using var proof = await Proof.CreateAsync(parent); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "locked-" + person.Value.ToString("N"); + RebindSession? rebind = null; + try + { + var timing = Stopwatch.StartNew(); + var result = await proof.Database.TryAdoptAsync(proof.Old, person, subject, async () => + { + rebind = await proof.BeginRebindAsync(); + timing.Restart(); + }); + timing.Stop(); + + result.IsBound.Should().BeFalse("the creation owner's 2 s lock timeout refuses it while the rebind runs"); + timing.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15)); + } + finally + { + if (rebind is not null) await rebind.DisposeAsync(); + } + + (await proof.CountUsersAsync()).Should().Be(2, "no user was created"); + } + + [Fact] + public async Task A_process_that_qualified_before_a_rebind_cannot_create_a_user_after_it() + { + await using var proof = await Proof.CreateAsync(parent); + var person = UserId.From(Guid.CreateVersion7()); + + var result = await proof.Database.TryAdoptAsync(proof.Old, person, "straggler-" + person.Value.ToString("N"), async () => + { + await using var rebind = await proof.BeginRebindAsync(); + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + }); + + result.IsBound.Should().BeFalse("it would otherwise create a person from the old realm under the new issuer"); + (await proof.CountUsersAsync()).Should().Be(2); + } + + [Fact] + public async Task A_process_started_after_a_rebind_creates_users_under_the_new_issuer_with_the_same_authority() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var rebind = await proof.BeginRebindAsync()) + { + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + } + + var person = UserId.From(Guid.CreateVersion7()); + var result = await proof.Database.TryAdoptAsync(proof.Renamed, person, "after-" + person.Value.ToString("N")); + + result.IsBound.Should().BeTrue(); + result.Actor.Should().Be(person); + (await proof.CountUsersAsync()).Should().Be(3); + } + + private sealed class Proof : IAsyncDisposable + { + private readonly List _sources = []; + + private Proof(IdentityPublicReadFixture database) + { + Database = database; + Old = database.Registration; + Renamed = new IdentityAuthorityRegistration(Old.AuthorityId, NewIssuer); + } + + internal IdentityPublicReadFixture Database { get; } + + internal IdentityAuthorityRegistration Old { get; } + + /// The same stable authority under the new issuer, which is what the deployment configures afterwards. + internal IdentityAuthorityRegistration Renamed { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var first = UserId.From(Guid.CreateVersion7()); + var second = UserId.From(Guid.CreateVersion7()); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, OldIssuer, + new Dictionary + { + [first] = "lock-proof-" + first.Value.ToString("N"), + [second] = "lock-proof-" + second.Value.ToString("N"), + }); + return new Proof(database); + } + + internal IdentityAuthorityQualification Qualification(IdentityAuthorityRegistration registration) + { + var source = NpgsqlDataSource.Create(Database.AppConnectionString); + _sources.Add(source); + return new IdentityAuthorityQualification(new Lazy(() => source), registration); + } + + internal async Task BeginRebindAsync() + { + var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.IdentityRebindConnectionString); + var transaction = await connection.BeginTransactionAsync(); + var session = new RebindSession(connection, transaction); + await session.TakeLockAsync(); + return session; + } + + /// Observed from outside: a start's shared request is queued behind the exclusive holder. + internal async Task WaitForSharedWaiterAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + var key = IdentityAdvisoryLockKey.ForAuthorityRebind(); + var deadline = Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(20)) + { + await using var command = new NpgsqlCommand( + """ + SELECT count(*) FROM pg_catalog.pg_locks + WHERE locktype = 'advisory' AND NOT granted AND mode = 'ShareLock' AND objsubid = 1 + AND ((classid::bigint << 32) | objid::bigint) = @key + """, connection); + command.Parameters.AddWithValue("key", key); + if ((long)(await command.ExecuteScalarAsync())! > 0) return; + await Task.Delay(50); + } + + throw new TimeoutException("No shared waiter queued behind the rebind lock."); + } + + internal async Task CountUsersAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.IdentityRebindConnectionString); + await using var command = new NpgsqlCommand("SELECT count(*) FROM public.users", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + public async ValueTask DisposeAsync() + { + foreach (var source in _sources) await source.DisposeAsync(); + await Database.DisposeAsync(); + } + } + + private sealed class RebindSession(NpgsqlConnection connection, NpgsqlTransaction transaction) : IAsyncDisposable + { + private bool _finished; + + internal async Task TakeLockAsync() + { + await using var command = new NpgsqlCommand("SELECT pg_catalog.pg_advisory_xact_lock(@key)", connection, transaction); + command.Parameters.AddWithValue("key", IdentityAdvisoryLockKey.ForAuthorityRebind()); + await command.ExecuteNonQueryAsync(); + } + + internal async Task ChangeIssuerAsync(string issuer) + { + await using var command = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = @issuer WHERE id = 1", connection, transaction); + command.Parameters.AddWithValue("issuer", issuer); + (await command.ExecuteNonQueryAsync()).Should().Be(1); + } + + internal async Task CommitAsync() + { + await transaction.CommitAsync(); + _finished = true; + } + + internal async Task RollbackAsync() + { + await transaction.RollbackAsync(); + _finished = true; + } + + public async ValueTask DisposeAsync() + { + if (!_finished) await transaction.RollbackAsync(); + await transaction.DisposeAsync(); + await connection.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs new file mode 100644 index 00000000..499a4260 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs @@ -0,0 +1,367 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The storage contract of learnstack_identity_rebind against real PostgreSQL (ADR-0104 § 2, § 7, § 8, +/// Database Standards § Controlled issuer rebind storage). +/// +/// +/// Table-level views do not show column grants, so every privilege is read from the column view, and every +/// refusal is exercised as the role itself rather than asserted from the grant text. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindStorageTests(PublicReadFixture parent) +{ + private const string Sentinel = "00000000-0000-7000-8000-000000000002"; + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task The_Role_Holds_Exactly_The_Declared_Column_Privileges_And_Nothing_Else() + { + await using var proof = await Proof.CreateAsync(parent); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString); + + var columns = await ReadAsync(owner, """ + SELECT table_name || '.' || column_name || ' ' || privilege_type + FROM information_schema.column_privileges + WHERE grantee = 'learnstack_identity_rebind' AND table_schema = 'public' + AND table_name NOT IN ('audit_log') + ORDER BY 1 + """); + columns.Should().Equal( + "identity_authority.authority_id SELECT", + "identity_authority.id SELECT", + "identity_authority.issuer SELECT", + "identity_authority.issuer UPDATE", + "users.authority_id SELECT", + "users.provider_subject SELECT", + "users.status SELECT", + "users.subject_key SELECT"); + + var audit = await ReadAsync(owner, """ + SELECT DISTINCT privilege_type FROM information_schema.column_privileges + WHERE grantee = 'learnstack_identity_rebind' AND table_schema = 'public' AND table_name = 'audit_log' + """); + audit.Should().Equal(["INSERT"], "the role writes audit rows and reads, changes and removes none"); + + var auditColumns = await ReadAsync(owner, """ + SELECT count(*)::text FROM information_schema.column_privileges p + JOIN information_schema.columns c USING (table_schema, table_name, column_name) + WHERE p.grantee = 'learnstack_identity_rebind' AND p.table_name = 'audit_log' AND p.privilege_type = 'INSERT' + """); + var allAuditColumns = await ReadAsync(owner, """ + SELECT count(*)::text FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'audit_log' + """); + auditColumns.Should().Equal(allAuditColumns, "the policy, not the column list, bounds the audit row"); + + var beyond = await ReadAsync(owner, """ + SELECT 'function ' || p.oid::regprocedure::text FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'public' + AND EXISTS (SELECT 1 FROM aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) a + WHERE a.grantee = 'learnstack_identity_rebind'::regrole) + UNION ALL SELECT 'schema create' WHERE has_schema_privilege('learnstack_identity_rebind', 'public', 'CREATE') + UNION ALL SELECT 'database create' WHERE has_database_privilege('learnstack_identity_rebind', current_database(), 'CREATE') + UNION ALL SELECT 'sequence ' || c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind = 'S' + AND CASE WHEN c.relkind = 'S' + THEN has_sequence_privilege('learnstack_identity_rebind', c.oid, 'USAGE,SELECT,UPDATE') END + """); + beyond.Should().BeEmpty("no function, schema CREATE, database CREATE or sequence privilege is granted to the role itself"); + } + + [Fact] + public async Task The_Role_Changes_The_Issuer_And_Nothing_Else_On_The_Authority_Row() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.ScalarAsync("SELECT issuer FROM public.identity_authority WHERE id = 1")) + .Should().Be(proof.OldIssuer); + + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET authority_id = uuidv7() WHERE id = 1")) + .Should().Be("42501", "no column grant covers the stable key"); + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET id = 2 WHERE id = 1")) + .Should().Be("42501", "no column grant covers the singleton id"); + (await proof.Rebind.RefusalAsync("DELETE FROM public.identity_authority")).Should().Be("42501"); + (await proof.Rebind.RefusalAsync("INSERT INTO public.identity_authority (id, authority_id, issuer) VALUES (2, uuidv7(), 'https://x.example.test/realms/learnstack')")) + .Should().Be("42501"); + (await proof.Rebind.RefusalAsync("TRUNCATE public.identity_authority")).Should().Be("42501"); + (await proof.Rebind.RefusalAsync($"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1")) + .Should().BeNull("the one admitted change"); + + (await proof.ReadIssuerAsync()).Should().Be(NewIssuer); + (await proof.ReadAuthorityAsync()).Should().Be(proof.AuthorityId, "the stable key is untouched"); + } + + [Fact] + public async Task No_Other_Role_Can_Change_The_Issuer() + { + await using var proof = await Proof.CreateAsync(parent); + + foreach (var (name, connectionString) in new (string, string)[] + { + ("learnstack_app", proof.AppConnectionString), + ("learnstack_platform", proof.PlatformConnectionString), + ("learnstack_outbox_admin", proof.OutboxConnectionString), + }) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand( + $"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1", connection); + var act = async () => await command.ExecuteNonQueryAsync(); + (await act.Should().ThrowAsync(name)).Which.SqlState.Should().Be("42501", name); + } + + // The owner holds the privilege and no policy admits it: the row security filters its target away. + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString)) + { + await using var command = new NpgsqlCommand( + $"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1", owner); + (await command.ExecuteNonQueryAsync()).Should().Be(0, "no policy admits an owner update"); + } + + (await proof.ReadIssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task The_Key_Trigger_Refuses_A_Change_Of_The_Id_Or_The_Authority_Id_Whoever_Holds_The_Grant() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString)) + { + await IdentityMembershipFixture.ExecuteAsync(owner, null, + "GRANT UPDATE (id, authority_id) ON public.identity_authority TO learnstack_identity_rebind"); + } + + // The trigger is the second line behind the missing column grant, so it is proved with the grant present. + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET authority_id = uuidv7() WHERE id = 1")) + .Should().Be("23514"); + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET id = 2 WHERE id = 1")).Should().Be("23514"); + (await proof.Rebind.RefusalAsync($"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1")) + .Should().BeNull("an issuer change is not a key change"); + + (await proof.ReadAuthorityAsync()).Should().Be(proof.AuthorityId); + } + + [Fact] + public async Task The_Role_Reads_Four_User_Columns_Without_Any_Announcement_And_Writes_None() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.ScalarAsync("SELECT count(*) FROM public.users WHERE authority_id = @authority", ("authority", proof.AuthorityId))) + .Should().Be(2, "the continuity proof reads every user of the stored authority"); + (await proof.Rebind.ScalarAsync( + "SELECT count(*) FROM public.users WHERE status = 'Active' AND provider_subject IS NOT NULL AND octet_length(subject_key) = 32")) + .Should().Be(2); + + foreach (var statement in new[] + { + "SELECT id FROM public.users", + "SELECT creation_audit_id FROM public.users", + "INSERT INTO public.users (id, authority_id, subject_key, provider_subject, status) VALUES (uuidv7(), uuidv7(), '\\x00', 'x', 'Active')", + "UPDATE public.users SET status = 'Closed'", + "DELETE FROM public.users", + }) + { + (await proof.Rebind.RefusalAsync(statement)).Should().Be("42501", statement); + } + + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.AppConnectionString); + await using var control = new NpgsqlCommand("SELECT count(*) FROM public.users", app); + (await control.ExecuteScalarAsync()).Should().Be(0L, "the control: the application role without its announcement sees no user"); + } + + [Fact] + public async Task The_Role_Inserts_The_Two_Rebind_Rows_And_Nothing_Else_Into_The_Audit_Log() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.RefusalAsync(AuditInsert(Row()))).Should().BeNull("the intent row"); + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.authority.rebind", outcome: "success")))) + .Should().BeNull("the result row"); + + await using (var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.PlatformConnectionString)) + { + await using var count = new NpgsqlCommand( + $"SELECT count(*) FROM public.audit_log WHERE tenant_id = '{Sentinel}' AND module = 'identity' AND operation LIKE 'identity.authority.rebind%'", + platform); + (await count.ExecuteScalarAsync()).Should().Be(2L); + } + + var refused = new (string Why, string Insert)[] + { + ("a real tenant", AuditInsert(Row(tenant: Guid.CreateVersion7().ToString("D")))), + ("an organization", AuditInsert(Row(organization: Guid.CreateVersion7().ToString("D")))), + ("another module", AuditInsert(Row(module: "tenancy"))), + ("the result slug with the intent outcome", AuditInsert(Row(operation: "identity.authority.rebind"))), + ("the intent slug with the result outcome", AuditInsert(Row(outcome: "success"))), + ("a failed outcome", AuditInsert(Row(outcome: "failed"))), + ("a Should row", AuditInsert(Row(operationClass: "Should"))), + ("another operation type", AuditInsert(Row(operationType: "Create"))), + ("another entity type", AuditInsert(Row(entityType: "User"))), + ("another reason", AuditInsert(Row(reason: "host_map"))), + ("an actor", AuditInsert(Row(actor: Guid.CreateVersion7().ToString("D")))), + ("a mail address", AuditInsert(Row(email: "operator@example.test"))), + ("no operator attribution", AuditInsert(Row(metadata: "{}"))), + }; + foreach (var (why, insert) in refused) + { + (await proof.Rebind.RefusalAsync(insert)).Should().Be("42501", why); + } + + // The creation witness guard of ADR-0072 refuses the one operation it governs, and the policy would refuse it too. + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.user.create")))) + .Should().Be("23514", "the global creation guard answers before the policy"); + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.authority.rebind_other")))) + .Should().Be("42501", "another operation of the identity module"); + + foreach (var statement in new[] + { + "SELECT count(*) FROM public.audit_log", + "UPDATE public.audit_log SET reason = 'x'", + "DELETE FROM public.audit_log", + "TRUNCATE public.audit_log", + }) + { + (await proof.Rebind.RefusalAsync(statement)).Should().Be("42501", statement); + } + } + + [Fact] + public async Task The_Application_And_Ingress_Roles_Cannot_Write_The_Rebind_Rows() + { + await using var proof = await Proof.CreateAsync(parent); + + // The application role announces no tenant here and the sentinel guard of ADR-0072 refuses its attribution + // before the policy; the ingress role holds no audit privilege at all. + foreach (var (name, connectionString, expected) in new (string, string, string)[] + { + ("learnstack_app", proof.AppConnectionString, "23514"), + ("learnstack_identity_ingress", parent.Postgres.IdentityIngressConnectionString, "42501"), + }) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await using var command = new NpgsqlCommand(AuditInsert(Row()), connection, transaction); + var act = async () => await command.ExecuteNonQueryAsync(); + (await act.Should().ThrowAsync(name)).Which.SqlState.Should().Be(expected, name); + } + } + + private static async Task ReadAsync(NpgsqlConnection connection, string sql) + { + await using var command = new NpgsqlCommand(sql, connection); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(reader.GetString(0)); + } + + return [.. rows]; + } + + private static string Row( + string tenant = Sentinel, string? organization = null, string module = "identity", + string operation = "identity.authority.rebind_attempt", string operationType = "SecurityEvent", + string operationClass = "Must", string entityType = "IdentityAuthority", string outcome = "indeterminate", + string reason = "issuer_rebind", string? actor = null, string? email = null, + string metadata = """{"operator":{"issuer":"https://operator.example.test/realms/learnstack-hub"}}""") => + string.Join('\u001f', tenant, organization ?? string.Empty, module, operation, operationType, operationClass, + entityType, outcome, reason, actor ?? string.Empty, email ?? string.Empty, metadata); + + private static string AuditInsert(string row) + { + var f = row.Split('\u001f'); + string Nullable(string value) => value.Length == 0 ? "NULL" : $"'{value}'"; + return $""" + INSERT INTO public.audit_log + (id, tenant_id, organization_id, actor_user_id, actor_email, module, operation, operation_type, + operation_class, entity_type, entity_id, outcome, reason, metadata, timestamp) + VALUES (uuidv7(), '{f[0]}', {Nullable(f[1])}, {Nullable(f[9])}, {Nullable(f[10])}, '{f[2]}', '{f[3]}', '{f[4]}', + '{f[5]}', '{f[6]}', 'authority', '{f[7]}', '{f[8]}', '{f[11]}'::jsonb, now()) + """; + } + + /// An installed authority, two bound users and a role session on its own connection each time. + private sealed class Proof : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + + private Proof(IdentityPublicReadFixture database) => _database = database; + + internal string OldIssuer => _database.Registration.Issuer; + internal Guid AuthorityId => _database.Registration.AuthorityId.Value; + internal string MigrationConnectionString => _database.MigrationConnectionString; + internal string AppConnectionString => _database.AppConnectionString; + internal string PlatformConnectionString => _database.PlatformConnectionString; + internal string OutboxConnectionString => _database.OutboxConnectionString; + internal RoleSession Rebind => new(_database.IdentityRebindConnectionString); + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var first = UserId.From(Guid.CreateVersion7()); + var second = UserId.From(Guid.CreateVersion7()); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", + new Dictionary + { + [first] = "rebind-storage-" + first.Value.ToString("N"), + [second] = "rebind-storage-" + second.Value.ToString("N"), + }); + return new Proof(database); + } + + internal async Task ReadIssuerAsync() => await ReadAsApplicationAsync("SELECT issuer FROM public.identity_authority"); + + internal async Task ReadAuthorityAsync() => await ReadAsApplicationAsync("SELECT authority_id FROM public.identity_authority"); + + // Read through the application role, whose policy admits the one authority row. + private async Task ReadAsApplicationAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var command = new NpgsqlCommand(sql, connection); + return (T)(await command.ExecuteScalarAsync())!; + } + + public ValueTask DisposeAsync() => _database.DisposeAsync(); + } + + private sealed class RoleSession(string connectionString) + { + /// The SQLSTATE the statement raises as the role, or null when it succeeds. + internal async Task RefusalAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + try + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + await command.ExecuteNonQueryAsync(); + await transaction.CommitAsync(); + return null; + } + catch (PostgresException failure) + { + return failure.SqlState; + } + } + + internal async Task ScalarAsync(string sql, params (string Name, object Value)[] values) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand(sql, connection); + foreach (var (name, value) in values) + { + command.Parameters.Add(new NpgsqlParameter(name, value is Guid ? NpgsqlDbType.Uuid : NpgsqlDbType.Text) { Value = value }); + } + + return (T)(await command.ExecuteScalarAsync())!; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs index 9ba48be8..eec32946 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs @@ -132,6 +132,23 @@ internal async Task AdoptAsync(UserId actor, string opaqueSubject) result.Actor.Should().Be(actor); } + /// + /// One process of the given registration: it qualifies, runs while it is + /// up (a rebind, for instance), and then it tries one adoption. The result is returned, never asserted. + /// + internal async Task TryAdoptAsync(IdentityAuthorityRegistration registration, UserId actor, + string opaqueSubject, Func? afterQualification = null) + { + var subject = new GlobalIdentitySubject(registration.AuthorityId, registration.Issuer, opaqueSubject); + await using var source = ApplicationDataSource.Build(AppConnectionString); + await using var provider = SeedComposition.Build(source, null, NullLoggerFactory.Instance, + identityAuthority: registration, seedAdmission: new ExactBindingAdmission(subject, actor)); + await provider.GetRequiredService().QualifyAsync(); + if (afterQualification is not null) await afterQualification(); + await using var scope = provider.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().AdoptAsync(subject, actor); + } + protected override void ConfigureTestHost(IWebHostBuilder builder) { base.ConfigureTestHost(builder); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs new file mode 100644 index 00000000..e1142452 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs @@ -0,0 +1,254 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The two witness-bound audit methods of the controlled issuer rebind (ADR-0104 § 8) against real PostgreSQL, +/// written on the rebind role's own connection exactly as the offline tool writes them. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityRebindAuditStoreTests(PublicReadFixture parent) +{ + private static readonly PlatformOperation Rebind = PlatformOperations.IdentityAuthorityRebind; + + [Fact] + public async Task The_Intent_And_The_Result_Rows_Are_Written_Bound_To_The_Admission_And_Carry_The_Ticket() + { + await using var scope = Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(ticket: "CHG-104"); + var authority = Guid.CreateVersion7(); + var intent = Intent(admission, authority); + var result = Result(admission, authority); + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindIntentAsync(intent, admission, connection, transaction); + await transaction.CommitAsync(); + } + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindResultAsync(result, admission, connection, transaction); + await transaction.CommitAsync(); + } + + var rows = await ReadAsync(admission.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.Outcome)).Should().BeEquivalentTo( + [("identity.authority.rebind_attempt", "indeterminate"), ("identity.authority.rebind", "success")]); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null + && row.Reason == "issuer_rebind" && row.Module == "identity" && row.Entity == "IdentityAuthority" + && OperatorNode(row.Metadata).GetProperty("ticket").GetString() == "CHG-104" + && OperatorNode(row.Metadata).GetProperty("subjectDigest").GetString() == admission.Operator.SubjectDigest); + } + + [Fact] + public async Task The_Result_Row_Commits_With_The_Transaction_Or_Not_At_All() + { + await using var scope = Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(); + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindResultAsync(Result(admission, Guid.CreateVersion7()), admission, connection, transaction); + await transaction.RollbackAsync(); + } + + (await ReadAsync(admission.Operator.CorrelationId!)).Should().BeEmpty(); + } + + [Fact] + public async Task A_Row_That_Differs_From_Its_Admission_Or_Its_Declaration_Is_Refused_Before_The_Database() + { + await using var scope = Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(ticket: "CHG-104"); + var authority = Guid.CreateVersion7(); + var good = Result(admission, authority); + var digest = admission.Operator.SubjectDigest; + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + + var refused = new Dictionary + { + ["a real tenant"] = good with { TenantId = TenantId.From(Guid.CreateVersion7()) }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["an organization"] = good with { OrganizationId = OrganizationId.From(Guid.CreateVersion7()) }, + ["another module"] = good with { ModuleName = "tenancy" }, + ["another operation"] = good with { Operation = "identity.user.create" }, + ["the intent slug for a result"] = good with { Operation = "identity.authority.rebind_attempt" }, + ["a failed outcome"] = good with { Outcome = AuditOutcome.Failed }, + ["the intent outcome for a result"] = good with { Outcome = AuditOutcome.Indeterminate }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["another operation type"] = good with { OperationType = OperationType.Create }, + ["another entity"] = good with { EntityType = "User" }, + ["another reason"] = good with { Reason = "host_map" }, + ["an actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["a mail address"] = good with { ActorEmail = "operator@example.test" }, + ["an address"] = good with { IpAddress = System.Net.IPAddress.Parse("203.0.113.7") }, + ["a user agent"] = good with { UserAgent = "tool" }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["no metadata"] = good with { Metadata = null }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["the digest in the wrong place"] = good with + { + Metadata = "{\"note\":\"" + digest + "\",\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\"}}", + }, + ["another operator issuer"] = good with { Metadata = Metadata(admission, "https://elsewhere.example.test/realms/x", "CHG-104") }, + ["a ticket the admission never held"] = good with { Metadata = Metadata(admission, admission.Operator.Issuer, "CHG-999") }, + }; + + foreach (var (attribute, draft) in refused) + { + var act = async () => await audit.WriteIdentityRebindResultAsync(draft, admission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + + // The intent method refuses the result's slug and outcome in turn. + var intentOfResult = async () => await audit.WriteIdentityRebindIntentAsync(good, admission, connection, transaction); + await intentOfResult.Should().ThrowAsync("the result slug is not the attempt slug"); + + // Another operation's admission binds no rebind row, and the other operations have no attempt slug. + var killswitch = TestPlatformAdmissions.Admission(PlatformOperations.KillswitchToggle, correlationId: admission.Operator.CorrelationId); + var other = async () => await audit.WriteIdentityRebindResultAsync(good, killswitch, connection, transaction); + await other.Should().ThrowAsync("another operation's admission"); + var noAttempt = async () => await audit.WriteIdentityRebindIntentAsync( + Intent(killswitch, authority), killswitch, connection, transaction); + await noAttempt.Should().ThrowAsync("only the rebind operation has an attempt slug"); + } + + [Fact] + public async Task A_Database_Refusal_Is_An_Audit_Write_Failure_So_The_Rebind_Cannot_Commit() + { + await using var scope = Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(); + + // The application role announces no tenant and the policy refuses the row. + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + + var act = async () => await audit.WriteIdentityRebindResultAsync( + Result(admission, Guid.CreateVersion7()), admission, connection, transaction); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task The_Identity_Catalogue_Declares_Both_Slugs_Off_Path_As_Must_Security_Events() + { + var catalog = new AuditCatalog([new IdentityAuditCatalogSource()]); + + foreach (var slug in new[] { "identity.authority.rebind_attempt", "identity.authority.rebind" }) + { + catalog.TryGetOffPath(slug, out var declared).Should().BeTrue(slug); + declared.ModuleName.Should().Be("identity"); + declared.OperationClass.Should().Be(OperationClass.Must); + declared.OperationType.Should().Be(OperationType.SecurityEvent); + declared.EntityType!.Name.Should().Be("IdentityAuthority"); + } + + Rebind.AuditSlug.Should().Be("identity.authority.rebind"); + Rebind.AttemptAuditSlug.Should().Be("identity.authority.rebind_attempt"); + Rebind.ReasonSlug.Should().Be("issuer_rebind"); + Rebind.NeedsPlatformRole.Should().BeFalse("the tool uses its own role and never the platform scope"); + Rebind.Permission.Key.Should().Be("platform.identity_authority.admin"); + } + + private static System.Text.Json.JsonElement OperatorNode(string metadata) => + System.Text.Json.JsonDocument.Parse(metadata).RootElement.GetProperty("operator"); + + private static PlatformAdmission Admit(string? ticket = null) => + TestPlatformAdmissions.Admission(Rebind, ticket, correlationId: "00-rebind-" + Guid.NewGuid().ToString("N")); + + private static string Metadata(PlatformAdmission admission, string issuer, string? ticket) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + admission.Operator.SubjectDigest + + "\",\"kind\":\"human\"" + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + private static AuditEntryDraft Intent(PlatformAdmission admission, Guid authority) => + Draft(admission, authority, admission.Operation.AttemptAuditSlug ?? "identity.authority.rebind_attempt", AuditOutcome.Indeterminate); + + private static AuditEntryDraft Result(PlatformAdmission admission, Guid authority) => + Draft(admission, authority, admission.Operation.AuditSlug, AuditOutcome.Success); + + private static AuditEntryDraft Draft(PlatformAdmission admission, Guid authority, string operation, AuditOutcome outcome) => new() + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "identity", + Operation = operation, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = "IdentityAuthority", + EntityId = authority.ToString("D"), + Outcome = outcome, + ErrorKey = null, + Reason = Rebind.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = "{\"operator\":" + PlatformOperatorAttribution.From(admission).ToOperatorJson(admission.Ticket) + "}", + }; + + private AsyncServiceScope Store() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The rebind rows are written on the caller's own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService() + .CreateAsyncScope(); + + private sealed record Row(Guid Tenant, string Operation, string Outcome, Guid? Actor, string? Reason, string Module, string Entity, string Metadata); + + private async Task> ReadAsync(string correlationId) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.PlatformConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT tenant_id, operation, outcome, actor_user_id, reason, module, entity_type, metadata::text + FROM public.audit_log WHERE correlation_id = @correlation ORDER BY timestamp, operation + """, connection); + command.Parameters.AddWithValue("correlation", correlationId); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new Row(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? null : reader.GetString(4), + reader.GetString(5), reader.GetString(6), reader.GetString(7))); + } + + return rows; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 1a36cf5e..b2286e3a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -103,8 +103,8 @@ public async Task Reversible_chain_prefixes_reverse_to_empty_and_current_heads_r (await CountAsync(connection, AuditFunctionQuery)).Should().Be(2L); (await CountAsync(connection, EducationFunctionQuery)).Should().Be(3L); (await CountAsync(connection, InboxFunctionQuery)).Should().Be(1L); - (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(24L, - "current Identity also installs three provider definers, one target transition guard, the federation connection guard and the operator subject resolver"); + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(25L, + "current Identity also installs three provider definers, one target transition guard, the federation connection guard, the operator subject resolver and the authority key guard"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); @@ -215,14 +215,16 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() federation.Should().Throw().WithMessage("Federation connection storage requires a reviewed forward migration."); Action releaseV4 = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.role_registry_release_v4().DownOperations; releaseV4.Should().Throw().WithMessage("Role release adoption requires a reviewed forward migration."); + Action operatorResolver = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_operator_subject_resolver().DownOperations; + operatorResolver.Should().Throw().WithMessage("Operator subject resolution requires a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] { (tenancy, "20261029112940_guard_retained_tenancy_defaults", TenancyReversibleHead, "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), (platform, "20261105020229_lock_invitation_envelope_parent", PlatformReversibleHead, "20261110013140_add_custom_field_protected_receipts", "Retained custom field receipts require a reviewed forward migration."), - (identity, "20261113120259_add_federation_connections", IdentityReversibleHead, - "20261119140000_add_operator_subject_resolver", "Operator subject resolution requires a reviewed forward migration."), + (identity, "20261119140000_add_operator_subject_resolver", IdentityReversibleHead, + "20261120090000_add_identity_authority_rebind", "The issuer-rebind storage requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, "20261109230218_membership_custom_field_definitions", "Retained custom field definitions require a reviewed forward migration."), }) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs index c7856d59..11e3fe6b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs @@ -90,6 +90,7 @@ public sealed class PostgresFixture : IAsyncLifetime private const string PlatformPassword = "platform-test"; private const string OutboxPassword = "outbox-test"; private const string IngressPassword = "ingress-test"; + private const string RebindPassword = "rebind-test"; private const string ContainerScriptPath = "/tmp/02-create-roles.sql"; // Pinned to the tag infra/compose/dev.yml runs. A fixture on a different major would @@ -110,6 +111,7 @@ public sealed class PostgresFixture : IAsyncLifetime .WithEnvironment("LEARNSTACK_PLATFORM_PW", PlatformPassword) .WithEnvironment("LEARNSTACK_OUTBOX_PW", OutboxPassword) .WithEnvironment("LEARNSTACK_IDENTITY_INGRESS_PW", IngressPassword) + .WithEnvironment("LEARNSTACK_IDENTITY_REBIND_PW", RebindPassword) // Keep concurrent publishers in one allocator address family, including identity fixtures. .WithCreateParameterModifier(parameters => ContainerLoopbackPorts.Configure(parameters, "5432/tcp")) .Build(); @@ -128,6 +130,9 @@ public sealed class PostgresFixture : IAsyncLifetime public string IdentityIngressConnectionString => For("learnstack_identity_ingress", IngressPassword); + /// NOBYPASSRLS; only the offline issuer-rebind tool's equivalent (ADR-0104). + public string IdentityRebindConnectionString => For("learnstack_identity_rebind", RebindPassword); + // An owned auxiliary fixture may attach this database to its disposable Docker network. internal string ContainerId => _container.Id; @@ -167,7 +172,7 @@ public async Task InitializeAsync() if (result.ExitCode != 0) { throw new InvalidOperationException( - $"Provisioning the four database roles failed (exit {result.ExitCode}).{Environment.NewLine}" + $"Provisioning the database roles failed (exit {result.ExitCode}).{Environment.NewLine}" + $"{result.Stderr}{Environment.NewLine}{result.Stdout}"); } } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs index cc012e6b..1848f726 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs @@ -38,7 +38,8 @@ public class PublicReadFixture : ConstructionOnlyApiFactory, IAsyncLifetime public string AppConnectionString => _database?.AppConnectionString ?? Postgres.AppConnectionString; public string OutboxConnectionString => _database?.OutboxConnectionString ?? Postgres.OutboxConnectionString; internal string MigrationConnectionString => _database?.MigrationConnectionString ?? Postgres.MigrationConnectionString; - private string PlatformConnectionString => _database?.PlatformConnectionString ?? Postgres.PlatformConnectionString; + internal string PlatformConnectionString => _database?.PlatformConnectionString ?? Postgres.PlatformConnectionString; + internal string IdentityRebindConnectionString => _database?.IdentityRebindConnectionString ?? Postgres.IdentityRebindConnectionString; public PublicReadObservation Observation { get; } = new(); internal static async Task CreateIsolatedAsync(PublicReadFixture parent) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs index 113c5742..9c25e5c9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs @@ -1338,7 +1338,7 @@ public async Task TheGrantMatrixIsExactlyWhatTheMigrationsWrote() SELECT grantee || ' ' || table_name || ' ' || string_agg(privilege_type, ',' ORDER BY privilege_type) FROM information_schema.table_privileges WHERE table_schema = 'public' - AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'PUBLIC') + AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_identity_rebind', 'PUBLIC') GROUP BY grantee, table_name """); @@ -1357,7 +1357,9 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi "learnstack_app identity_provider_event_targets SELECT", "learnstack_identity_ingress identity_provider_event_receipts SELECT", "learnstack_identity_ingress identity_provider_event_scan INSERT,SELECT", - "learnstack_identity_ingress identity_provider_event_problems INSERT,SELECT"]), + "learnstack_identity_ingress identity_provider_event_problems INSERT,SELECT", + "learnstack_identity_rebind identity_authority SELECT", + "learnstack_identity_rebind audit_log INSERT"]), "every line is one line of the migration chains' grant matrices, and " + "learnstack_outbox_admin holds only declared outbox/delivery scheduling columns " + "and terminal audit INSERT"); diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs index 10d883e1..42238746 100644 --- a/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs @@ -23,6 +23,17 @@ public void User_and_tenant_keys_have_independent_signed_network_order_vectors( userKey.Should().NotBe(tenantKey); } + // SHA-256 over the length-prefixed UTF-8 strings "learnstack.identity.lock.v1" and "authority-rebind", first + // eight bytes as a big-endian signed integer, calculated outside the C# helper. + [Fact] + public void The_rebind_key_is_one_fixed_value_that_no_user_tenant_or_subject_key_shares() + { + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().Be(-6667816513393306176L); + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().Be(IdentityAdvisoryLockKey.ForAuthorityRebind()); + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().NotBe(IdentityAdvisoryLockKey.ForUser(UserId.From(Authority.Value))) + .And.NotBe(IdentityAdvisoryLockKey.ForTenant(TenantId.From(Authority.Value))); + } + [Fact] public void A_contextual_lock_plan_copies_deduplicates_and_orders_actual_users_and_keeps_mode() { diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 5b22d3b5..5a9c8ec1 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -56,6 +56,38 @@ public async Task An_Operator_Without_The_Grant_Is_Refused_Even_With_A_Valid_Wit result.Refusal.Should().Be(PlatformRefusal.MissingPermission); } + [Fact] + public async Task The_Rebind_Operation_Is_Admitted_Only_For_The_Identity_Authority_Admin_Grant() + { + // ADR-0104 § 3: the offline tool's operator holds platform.identity_authority.admin, and no other + // Platform grant stands in for it, the killswitch and the onboarding grants included. + var rebind = PlatformOperations.IdentityAuthorityRebind; + rebind.Permission.Key.Should().Be("platform.identity_authority.admin"); + + var admitted = await Gate(Grants("operator-1", PlatformPermissions.IdentityAuthorityAdmin.Key)) + .AdmitAsync(TestPlatformAdmissions.Witness(), rebind, "CHG-104"); + admitted.IsAdmitted.Should().BeTrue(); + admitted.Admission!.Operation.Should().BeSameAs(rebind); + admitted.Admission.Ticket.Should().Be("CHG-104"); + + foreach (var other in PlatformPermissions.All.Where(permission => permission != PlatformPermissions.IdentityAuthorityAdmin)) + { + (await Gate(Grants("operator-1", other.Key)).AdmitAsync(TestPlatformAdmissions.Witness(), rebind, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, other.Key); + } + + // The converse: the rebind grant admits no other act. + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, rebind))) + { + (await Gate(Grants("operator-1", PlatformPermissions.IdentityAuthorityAdmin.Key)) + .AdmitAsync(TestPlatformAdmissions.Witness(), operation, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, operation.AuditSlug); + } + + // An admission for the rebind cannot be spent on the scope or the executor, neither of which is its owner. + rebind.NeedsPlatformRole.Should().BeFalse(); + } + [Fact] public async Task A_Grant_For_Another_Permission_Does_Not_Admit() { @@ -128,7 +160,7 @@ public async Task An_Unregistered_Operation_Is_Refused() // A lookalike is not the registered instance, however identical its content. var lookalike = typeof(PlatformOperation).GetConstructors( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] - .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true]); + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true, null]); (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), (PlatformOperation)lookalike, null)) .Refusal.Should().Be(PlatformRefusal.UnknownOperation); @@ -152,7 +184,7 @@ public async Task Entry_With_An_Unregistered_Operation_Never_Touches_The_Credent var scope = Build(out var dataSource); var lookalike = typeof(PlatformOperation).GetConstructors( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] - .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true]); + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true, null]); var act = async () => await scope.EnterAsync( TestPlatformAdmissions.Admission((PlatformOperation)lookalike), CancellationToken.None); diff --git a/infra/compose/README.md b/infra/compose/README.md index 57868990..a9f6d3f3 100644 --- a/infra/compose/README.md +++ b/infra/compose/README.md @@ -72,7 +72,7 @@ fresh `postgres-data` volume**: | Script | Creates | |---|---| | `postgres-init/01-create-keycloak-db.sql` | the `keycloak` database Keycloak stores its realm state in | -| `postgres-init/02-create-roles.sql` | the four baseline database roles plus ADR-0097’s confined `learnstack_identity_ingress` login, reading passwords from `LEARNSTACK_*_PW` in the environment | +| `postgres-init/02-create-roles.sql` | the four baseline database roles plus ADR-0097’s confined `learnstack_identity_ingress` and ADR-0104’s confined `learnstack_identity_rebind` logins, reading passwords from `LEARNSTACK_*_PW` in the environment | **A volume created before Phase 02a Packet 6 has no roles**, and nothing will tell you: init scripts do not re-run, `make dev` reports healthy, and the first @@ -85,11 +85,13 @@ docker compose --env-file .env -f infra/compose/dev.yml exec -T postgres sh -c ``` The script converges passwords, attributes and memberships on every run; it is -not a no-op. P03-6's forward Identity migration requires the fifth role to exist. -For a warm volume, set `LEARNSTACK_IDENTITY_INGRESS_PW` in the selected private -environment, recreate the postgres container with the existing volume to pass -the new environment value, then apply the roles script above before `make migrate`. -Do not delete a volume to add the role. No runtime process receives the migration +not a no-op. P03-6's forward Identity migration requires the fifth role to exist, +and the P03-9 Step 3 Identity migration requires the sixth. For a warm volume, set +`LEARNSTACK_IDENTITY_INGRESS_PW` and `LEARNSTACK_IDENTITY_REBIND_PW` in the selected +private environment, recreate the postgres container with the existing volume to pass +the new environment values, then apply the roles script above before `make migrate`. +Do not delete a volume to add a role. The sixth role's connection string is never a +compose or host setting: it exists only in the environment of the offline rebind tool. No runtime process receives the migration password. The [database contract](../../docs/standards/05-database.md#provider-event-intake-storage) owns the private machine source and its bounds; installing storage alone does not activate provider polling. diff --git a/infra/compose/dev.yml b/infra/compose/dev.yml index 2121dda5..a6be328d 100644 --- a/infra/compose/dev.yml +++ b/infra/compose/dev.yml @@ -61,14 +61,15 @@ services: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-learnstack} POSTGRES_DB: ${POSTGRES_DB:-learnstack} # Read by postgres-init/02-create-roles.sql through psql's \getenv on the - # first boot of a fresh volume. The four-role model of ADR-0003 - # Amendment 3; an unset one aborts initdb rather than creating a + # first boot of a fresh volume. The role model of ADR-0003 + # Amendment 3 and 14; an unset one aborts initdb rather than creating a # passwordless role. LEARNSTACK_MIGRATION_PW: ${LEARNSTACK_MIGRATION_PW:-learnstack-migration-dev} LEARNSTACK_APP_PW: ${LEARNSTACK_APP_PW:-learnstack-app-dev} LEARNSTACK_PLATFORM_PW: ${LEARNSTACK_PLATFORM_PW:-learnstack-platform-dev} LEARNSTACK_OUTBOX_PW: ${LEARNSTACK_OUTBOX_PW:-learnstack-outbox-dev} LEARNSTACK_IDENTITY_INGRESS_PW: ${LEARNSTACK_IDENTITY_INGRESS_PW:-learnstack-identity-ingress-dev} + LEARNSTACK_IDENTITY_REBIND_PW: ${LEARNSTACK_IDENTITY_REBIND_PW:-learnstack-identity-rebind-dev} # Dev-only. Production secrets come from Vault via ISecretProvider. ports: - "127.0.0.1:5432:5432" diff --git a/infra/compose/postgres-init/02-create-roles.sql b/infra/compose/postgres-init/02-create-roles.sql index 5e51ebca..07960d16 100644 --- a/infra/compose/postgres-init/02-create-roles.sql +++ b/infra/compose/postgres-init/02-create-roles.sql @@ -1,7 +1,7 @@ -- Postgres init script — runs ONCE on a fresh `postgres-data` volume, after -- 01-create-keycloak-db.sql. Provisions the four-role baseline plus the confined --- fifth provider-intake role of ADR-0097. The baseline is --- ADR-0003 Amendment 3, whose canonical definition is +-- fifth provider-intake role of ADR-0097 and the confined sixth issuer-rebind role +-- of ADR-0104. The baseline is ADR-0003 Amendment 3, whose canonical definition is -- docs/standards/05-database.md § Database roles. -- -- WHY FOUR ROLES AND NOT ONE. The single `POSTGRES_USER` this stack used to run @@ -22,6 +22,7 @@ \getenv platform_pw LEARNSTACK_PLATFORM_PW \getenv outbox_pw LEARNSTACK_OUTBOX_PW \getenv ingress_pw LEARNSTACK_IDENTITY_INGRESS_PW +\getenv rebind_pw LEARNSTACK_IDENTITY_REBIND_PW \getenv db POSTGRES_DB -- Idempotent in the shape 01-create-keycloak-db.sql already uses: PostgreSQL has @@ -56,6 +57,13 @@ SELECT format('CREATE ROLE learnstack_identity_ingress LOGIN NOINHERIT PASSWORD WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_ingress') \gexec +-- The sixth role belongs to the offline issuer-rebind tool alone (ADR-0104): no API, +-- worker or seeder host is ever given its credential. NOINHERIT and NOBYPASSRLS like +-- the fifth, so its few grants are bounded by policies and nothing is inherited. +SELECT format('CREATE ROLE learnstack_identity_rebind LOGIN NOINHERIT PASSWORD %L NOBYPASSRLS', :'rebind_pw') +WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_rebind') +\gexec + -- Then CONVERGE, unconditionally. The creates above fire only when the role is -- absent, so on a cluster that already has them — the documented recovery path -- is "apply this file by hand, it is idempotent" — a changed password in `.env` @@ -68,11 +76,11 @@ WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_ingr -- way to put it back. (The runtime refuses to start against such a role anyway — -- the composition root asks the server `rolbypassrls OR rolsuper` on every -- physical connection — but this is what fixes it rather than reporting it.) --- NOSUPERUSER on all five, and it is not decoration: a SUPERUSER bypasses row +-- NOSUPERUSER on all six, and it is not decoration: a SUPERUSER bypasses row -- security whatever `rolbypassrls` says — measured — so a superuser -- learnstack_app makes every policy in the database inert while the attribute -- this script converges still reads `f`. NOCREATEDB / NOCREATEROLE / --- NOREPLICATION for the same reason in miniature: none of the five needs any of +-- NOREPLICATION for the same reason in miniature: none of the six needs any of -- them, learnstack_migration owns tables rather than databases or roles, and an -- attribute nothing needs is one an escalation can use. ALTER ROLE learnstack_migration WITH LOGIN PASSWORD :'migration_pw' @@ -87,22 +95,26 @@ ALTER ROLE learnstack_outbox_admin WITH LOGIN PASSWORD :'outbox_pw' ALTER ROLE learnstack_identity_ingress WITH LOGIN PASSWORD :'ingress_pw' NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; --- And revoke every role MEMBERSHIP the five hold. Attributes were only half of +ALTER ROLE learnstack_identity_rebind WITH LOGIN PASSWORD :'rebind_pw' + NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; + +-- And revoke every role MEMBERSHIP the six hold. Attributes were only half of -- it: `GRANT learnstack_platform TO learnstack_app` leaves learnstack_app's own -- rolbypassrls false and still lets it `SET ROLE learnstack_platform` — measured, -- directly and through a bridge role holding the membership on its behalf. None --- of the four needs to be a member of anything; every privilege they hold is +-- of the six needs to be a member of anything; every privilege they hold is -- granted to them directly, in the migration that creates each table. -- --- Generated per membership rather than written as four REVOKEs, because the +-- Generated per membership rather than written as a fixed list of REVOKEs, because the -- grantor is not knowable in advance and a bridge role has no fixed name. No -- rows means no statements, so a clean cluster is a no-op. SELECT format('REVOKE %I FROM %I', granted.rolname, member.rolname) FROM pg_auth_members am JOIN pg_roles granted ON granted.oid = am.roleid JOIN pg_roles member ON member.oid = am.member -WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learnstack_migration', 'learnstack_app', - 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress') +WHERE granted.rolname IN ('learnstack_identity_ingress', 'learnstack_identity_rebind') + OR member.rolname IN ('learnstack_migration', 'learnstack_app', 'learnstack_platform', + 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_identity_rebind') \gexec -- No `GRANT learnstack_platform TO learnstack_app`, ever. Membership would make @@ -114,10 +126,10 @@ WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learn -- reaches learnstack_platform). -- PUBLIC holds CONNECT and TEMPORARY on every database by default, so the grant --- below adds nothing until that default is removed. Revoke first, and the four +-- below adds nothing until that default is removed. Revoke first, and the -- explicit grants become the whole of the reach INTO THIS DATABASE — measured: -- afterwards `pg_database.datacl` carries no `=Tc` entry for PUBLIC, only the --- four `c` grants and the owner's. +-- `c` grants and the owner's. -- -- Scope is exactly one database, and that is worth saying because it is easy to -- read as more. Measured: `learnstack_app` can still connect to `keycloak` and @@ -134,7 +146,8 @@ WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learn -- exist. REVOKE CONNECT, TEMPORARY ON DATABASE :"db" FROM PUBLIC; GRANT CONNECT ON DATABASE :"db" - TO learnstack_migration, learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress; + TO learnstack_migration, learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress, + learnstack_identity_rebind; -- Since PostgreSQL 15 the public schema no longer grants CREATE to PUBLIC, and -- the schema is owned by pg_database_owner. Without the CREATE grant below the @@ -145,7 +158,8 @@ GRANT CONNECT ON DATABASE :"db" REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO learnstack_migration; GRANT USAGE ON SCHEMA public - TO learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress; + TO learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress, + learnstack_identity_rebind; -- No per-table grants here. This script runs at initdb time, before any table -- exists, and under the entrypoint's ON_ERROR_STOP a single From 897e686493d1f834b80d5806c0303219ee143770 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 01:03:21 +0300 Subject: [PATCH 13/28] feat(platform): add the offline issuer-rebind tool and shared validator P03-9 Step 3 (ADR-0104), second part. The operator token validator moves from the API project into Infrastructure so the bearer scheme and the offline tool take one definition of the parameters, the bounded metadata manager and the closed profile; the tool is the second caller of the profile, not a second minter. IdentityIssuerRebind drives the proof on the confined role: exclusive lock first, no-op when the target is already stored, intent row on its own transaction, freeze check, continuity proof, one-column change and result row on one transaction, and reconciliation of an unknown commit. The new tool project reads the new realm with an operator-supplied view-users credential and prints one line of classes and counts. The audit_log grant and policy arm move to a central audit installer. Proof: 66 rebind integration cases on real PostgreSQL, the tool as a child process, the pinned Keycloak enumeration, the continuity function, and the architecture census edits. Also adds the Step 2 Docker classes the CI shard plan was missing. Co-Authored-By: Claude Sonnet 5.5 --- .claude/skills/local-dev-setup/SKILL.md | 5 +- backend/Directory.Packages.props | 4 + backend/LearnStack.slnx | 1 + backend/README.md | 1 + .../PlatformOperatorAuthentication.cs | 231 +------ .../TenantAuthenticationBackchannel.cs | 1 + .../IdentityRebindAuditInstaller.cs | 64 ++ .../Identity}/BoundedMetadataReader.cs | 6 +- .../LearnStack.Infrastructure.csproj | 2 + .../PlatformOperatorMetadata.cs | 29 +- .../PlatformOperatorSettings.cs | 43 +- .../PlatformOperatorTokenProfile.cs | 190 ++++++ .../PlatformOperatorTokenValidator.cs | 170 ++++++ .../KeycloakRealmContinuitySource.cs | 223 +++++++ ...Stack.Tools.IdentityAuthorityRebind.csproj | 35 ++ .../Program.cs | 60 ++ .../RebindTool.cs | 153 +++++ .../RebindToolInput.cs | 83 +++ .../Bindings/INewRealmContinuitySource.cs | 30 + .../Bindings/IdentityIssuerRebind.cs | 480 +++++++++++++++ .../Bindings/IdentityRebindContinuity.cs | 115 ++++ .../Bindings/IdentityRebindOutcome.cs | 125 ++++ .../Persistence/IdentityAuthorityRebindDdl.cs | 36 +- .../AuditConventionTests.cs | 7 +- .../AuthenticationAuthorityTests.Shapes.cs | 10 +- .../AuthenticationAuthorityTests.cs | 1 + .../FederationAdapterConventionTests.cs | 10 +- .../IdentityAuditConventionTests.cs | 23 + .../LearnStack.Tests.Architecture.csproj | 1 + .../PersistenceConventionTests.cs | 3 + .../PlatformAdminScopeConventionTests.cs | 63 +- .../Database/IdentityAuthorityRebindTests.cs | 574 ++++++++++++++++++ .../IdentityAuthorityRebindToolTests.cs | 325 ++++++++++ .../Database/IdentityRebindAuditStoreTests.cs | 24 +- .../Database/RebindProofSupport.cs | 224 +++++++ .../FakeKeycloakRealm.cs | 161 +++++ .../KeycloakRealmContinuitySourceTests.cs | 124 ++++ .../LearnStack.Tests.Integration.csproj | 1 + .../PlatformOperatorTokenValidatorTests.cs | 212 +++++++ .../KeycloakEnumerationTests.cs | 137 +++++ .../PlatformOperatorRealmTests.cs | 5 +- .../PlatformOperatorAuthenticationTests.cs | 5 +- .../PlatformOperatorMetadataHealthTests.cs | 1 + .../Identity/IdentityRebindContinuityTests.cs | 144 +++++ .../PlatformOperatorActExecutorTests.cs | 2 +- ...membership-and-identity-data-foundation.md | 13 + .../0104-controlled-issuer-rebind.md | 64 ++ docs/glossary.md | 3 +- docs/modules/identity/README.md | 15 +- docs/modules/identity/audit.md | 2 + docs/runbooks/README.md | 1 + docs/runbooks/identity-issuer-rebind.md | 202 ++++++ docs/runbooks/operator-access.md | 8 + docs/standards/05-database.md | 129 +++- docs/standards/10-observability.md | 2 + docs/standards/11-security.md | 23 +- docs/standards/18-audit-coverage.md | 6 +- docs/standards/19-permissions.md | 9 +- .../21-architecture-tests-catalogue.md | 67 +- scripts/ci-test-shards-plan.json | 7 + 60 files changed, 4344 insertions(+), 351 deletions(-) create mode 100644 backend/src/LearnStack.Infrastructure.Audit/IdentityRebindAuditInstaller.cs rename backend/src/{LearnStack.Api/Authentication => LearnStack.Infrastructure/Identity}/BoundedMetadataReader.cs (93%) rename backend/src/{LearnStack.Api/Authentication => LearnStack.Infrastructure/PlatformOperator}/PlatformOperatorMetadata.cs (88%) rename backend/src/{LearnStack.Api/Authentication => LearnStack.Infrastructure/PlatformOperator}/PlatformOperatorSettings.cs (71%) create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs create mode 100644 backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs create mode 100644 backend/src/LearnStack.Tools.IdentityAuthorityRebind/LearnStack.Tools.IdentityAuthorityRebind.csproj create mode 100644 backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs create mode 100644 backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs create mode 100644 backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs create mode 100644 docs/runbooks/identity-issuer-rebind.md diff --git a/.claude/skills/local-dev-setup/SKILL.md b/.claude/skills/local-dev-setup/SKILL.md index a7c966e7..93fba8b7 100644 --- a/.claude/skills/local-dev-setup/SKILL.md +++ b/.claude/skills/local-dev-setup/SKILL.md @@ -220,7 +220,10 @@ a fresh `postgres-data` volume `learnstack_migration` owns every table, `learnstack_app` is what the API connects as, and `learnstack_platform` / `learnstack_outbox_admin` hold audited bypasses. The four roles/passwords and baseline connection strings are in -`.env.example`, and their privileges are not interchangeable. The accepted +`.env.example`, and their privileges are not interchangeable. Two confined roles join +them: `learnstack_identity_ingress` (provider intake) and `learnstack_identity_rebind`, +the offline issuer-rebind tool's role, whose connection string is never a stack or host +setting ([runbook](../../../docs/runbooks/identity-issuer-rebind.md)). The accepted P03-2 application-role sources do not expand this role set. Running migrations as the runtime role would make it the table owner, which is the arrangement `FORCE ROW LEVEL SECURITY` exists to defeat. diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index 5290d075..2f7f490e 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -13,6 +13,10 @@ 2.12.0 or later. --> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs new file mode 100644 index 00000000..95ff0126 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs @@ -0,0 +1,60 @@ +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using Microsoft.Extensions.Configuration; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using LearnStack.Infrastructure.PlatformOperator; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// +/// The controlled issuer rebind tool (ADR-0104). It takes every value from its environment and one line of standard +/// input, never an argument, and prints one fixed line. See docs/runbooks/identity-issuer-rebind.md. +/// +internal static class Program +{ + private const string UsageRefusal = "rebind: outcome=refused_input"; + private static readonly TimeSpan Deadline = TimeSpan.FromMinutes(10); + + public static async Task Main(string[] args) + { + if (args.Length != 0) + { + Console.Error.WriteLine(UsageRefusal); + return RebindTool.Refused; + } + + try + { + var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); + if (!RebindToolInput.TryRead( + name => Environment.GetEnvironmentVariable(name), + () => Console.IsInputRedirected ? Console.In.ReadLine() : null, + configuration, + out var input)) + { + Console.Error.WriteLine(UsageRefusal); + return RebindTool.Refused; + } + + using var meters = input!.OtlpEndpoint is null + ? null + : Sdk.CreateMeterProviderBuilder() + .AddMeter(IdentityRebindMetrics.MeterName, PlatformOperatorMetrics.MeterName) + .AddOtlpExporter() + .Build(); + using var deadline = new CancellationTokenSource(Deadline); + using var client = KeycloakRealmContinuitySource.CreateClient(); + var realm = new KeycloakRealmContinuitySource(client, input.RealmClientId, input.RealmClientSecret); + var exit = await RebindTool.RunAsync(input, realm, Console.Out, deadline.Token); + meters?.ForceFlush(5000); + return exit; + } +#pragma warning disable CA1031 // The tool emits one fixed line, never an exception payload that could carry a credential. + catch (Exception) +#pragma warning restore CA1031 + { + Console.Error.WriteLine("rebind: outcome=refused_unexpected"); + return RebindTool.Refused; + } + } +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs new file mode 100644 index 00000000..2b1ac075 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs @@ -0,0 +1,153 @@ +using System.Text; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Npgsql; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// +/// The offline controlled issuer rebind (ADR-0104): validate the human, admit the act, run it, and say how it ended in +/// one fixed line that carries counts and classes and never an identifier. +/// +/// +/// +/// Exit codes: 0 the issuer was changed or already was; 2 refused with the state unchanged (a retry +/// repeats the whole proof); 3 the commit's outcome could not be read back, so the operator reads the stored +/// issuer before anything else. +/// +/// +/// The operator token is validated by the same the API scheme is +/// configured from, and the grant is read per act from PlatformOperator:Grants, never from a claim. The +/// tool is the second caller of the witness minter's closed census: it mints nothing itself. +/// +/// +internal static class RebindTool +{ + internal const int Applied = 0; + internal const int Refused = 2; + internal const int Unknown = 3; + + internal static async Task RunAsync( + RebindToolInput input, INewRealmContinuitySource realm, TextWriter output, CancellationToken cancellationToken) + { + PlatformOperatorSettings? settings; + try + { + settings = PlatformOperatorSettings.FromConfiguration(input.Configuration, input.Mode); + } + catch (InvalidOperationException) + { + return Refuse(output, "operator_configuration_invalid"); + } + + if (settings is null) + { + return Refuse(output, "operator_issuer_not_configured"); + } + + var clock = new SystemClock(); + var correlation = "rebind-" + Guid.NewGuid().ToString("N"); + using var backchannel = new PlatformOperatorBackchannel(); + var health = new PlatformOperatorMetadataHealth(clock); + var manager = PlatformOperatorValidation.CreateConfigurationManager(settings, backchannel, health, NullLogger.Instance); + var validation = await new PlatformOperatorTokenValidator(settings, manager, health, clock).ValidateAsync( + input.OperatorToken, PlatformOperatorSettings.RebindToolExecutor, correlation, cancellationToken); + if (!validation.IsValid) + { + return Refuse(output, "operator_token_" + validation.Cause, correlation); + } + + using var services = new ServiceCollection() + .AddLogging() + .AddSingleton(clock) + .AddOptions() + .Bind(input.Configuration.GetSection(PlatformOperatorGrantOptions.SectionName)).Services + .AddSingleton>(new PlatformOperatorGrantOptionsValidator(input.Mode)) + .AddSingleton() + .AddSingleton() + .BuildServiceProvider(); + var admitted = await services.GetRequiredService().AdmitAsync( + validation.Witness!, PlatformOperations.IdentityAuthorityRebind, input.Ticket, cancellationToken); + if (!admitted.IsAdmitted) + { + return Refuse(output, "operator_" + Cause(admitted.Refusal), correlation); + } + + await using var store = StoreScope(); + var outcome = await new IdentityIssuerRebind(store.ServiceProvider.GetRequiredService(), clock) + .RunAsync(input.ConnectionString, input.Target, admitted.Admission!, realm, cancellationToken: cancellationToken); + output.WriteLine(Line(outcome, correlation)); + return outcome.Result switch + { + IdentityRebindResult.Applied or IdentityRebindResult.AlreadyApplied => Applied, + IdentityRebindResult.Unknown => Unknown, + _ => Refused, + }; + } + + /// The closed audit-store graph the rebind rows are written through, on the role's own connection. + private static AsyncServiceScope StoreScope() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The rebind rows are written on the tool's own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService() + .CreateAsyncScope(); + + /// One line: the outcome class, the correlation id that finds the audit rows, and counts. + internal static string Line(IdentityRebindOutcome outcome, string correlation) + { + var line = new StringBuilder("rebind: outcome=").Append(IdentityRebindMetrics.Label(outcome)) + .Append(" correlation=").Append(correlation); + if (outcome.LiveSessions is { } sessions) + { + line.Append(" sessions=").Append(sessions); + } + + if (outcome.Continuity is { } counts) + { + line.Append(" active=").Append(counts.StoredActive).Append(" closing=").Append(counts.StoredClosing) + .Append(" closed=").Append(counts.StoredClosed).Append(" reported=").Append(counts.Enumerated) + .Append(" unkeyable=").Append(counts.Unkeyable).Append(" missing_active=").Append(counts.MissingActive) + .Append(" reappearing_closed=").Append(counts.ReappearingClosed) + .Append(" unbootstrapped=").Append(counts.Unbootstrapped); + } + + return line.ToString(); + } + + internal static int Refuse(TextWriter output, string reason, string? correlation = null) + { + output.WriteLine("rebind: outcome=refused_" + reason + (correlation is null ? string.Empty : " correlation=" + correlation)); + return Refused; + } + + private static string Cause(PlatformRefusal refusal) => refusal switch + { + PlatformRefusal.InvalidWitness => "invalid_witness", + PlatformRefusal.UnknownOperation => "unknown_operation", + PlatformRefusal.InvalidTicket => "invalid_ticket", + PlatformRefusal.MissingPermission => "missing_permission", + _ => "not_admitted", + }; +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs new file mode 100644 index 00000000..a832489a --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs @@ -0,0 +1,83 @@ +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.Extensions.Configuration; +using Npgsql; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// What the operator hands the tool, read from the process environment and one line of standard input. +/// +/// Nothing is an argument: an argument is visible to every user of the host and survives in shell history. The +/// operator token comes from LEARNSTACK_OPERATOR_TOKEN or, when that is unset, the first line of standard +/// input. The realm credential is a view-users client the operator creates for the run and deletes after it. +/// +internal sealed record RebindToolInput( + string ConnectionString, + IdentityAuthorityRegistration Target, + string OperatorToken, + string? Ticket, + string RealmClientId, + string RealmClientSecret, + DeploymentMode Mode, + IConfiguration Configuration, + string? OtlpEndpoint) +{ + internal const string ConnectionStringKey = "ConnectionStrings__IdentityRebind"; + internal const string TokenKey = "LEARNSTACK_OPERATOR_TOKEN"; + internal const string TicketKey = "LEARNSTACK_REBIND_TICKET"; + internal const string RealmClientIdKey = "LEARNSTACK_REBIND_REALM_CLIENT_ID"; + internal const string RealmClientSecretKey = "LEARNSTACK_REBIND_REALM_CLIENT_SECRET"; + private const int MaximumTokenCharacters = 16 * 1024; + + /// Reads and validates the input; false means nothing was usable, and no value is reported. + internal static bool TryRead( + Func environment, Func standardInput, IConfiguration configuration, out RebindToolInput? input) + { + input = null; + var connection = environment(ConnectionStringKey); + var token = environment(TokenKey); + if (string.IsNullOrWhiteSpace(token)) + { + token = standardInput(); + } + + var clientId = environment(RealmClientIdKey); + var clientSecret = environment(RealmClientSecretKey); + var ticket = environment(TicketKey); + if (string.IsNullOrWhiteSpace(connection) || string.IsNullOrWhiteSpace(token) || token.Length > MaximumTokenCharacters + || string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret) + || !Guid.TryParseExact(environment("Identity__AuthorityId"), "D", out var authority) || authority == Guid.Empty + || string.IsNullOrEmpty(environment("Authentication__Tenant__Issuer"))) + { + return false; + } + + // The mode is explicit, as it is for the API: it decides whether a loopback operator issuer and the demo + // operator's grant are admitted, so a tool that guessed it could admit what the API refuses. + if (!Enum.TryParse(environment("Deployment__Mode"), ignoreCase: false, out var mode) + || !Enum.IsDefined(mode)) + { + return false; + } + + try + { + if (new NpgsqlConnectionStringBuilder(connection).Username != IdentityIssuerRebind.RoleName) + { + return false; + } + + var target = new IdentityAuthorityRegistration( + IdentityAuthorityId.From(authority), environment("Authentication__Tenant__Issuer")!); + input = new RebindToolInput( + connection, target, token.Trim(), string.IsNullOrWhiteSpace(ticket) ? null : ticket, + clientId, clientSecret, mode, configuration, environment("OTEL_EXPORTER_OTLP_ENDPOINT")); + return true; + } + catch (ArgumentException) + { + return false; + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs new file mode 100644 index 00000000..f690ecba --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs @@ -0,0 +1,30 @@ +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// +/// What the tool read from the new realm: its discovery issuer, the size of its published key set, and the users it +/// reports (ADR-0104 § 6). +/// +/// The issuer of the new realm's discovery document. +/// How many signing keys its key set publishes. +/// Whether the enumeration reached the end of the realm, not merely a page. +/// The sub of every user the realm reported. +public sealed record NewRealmSnapshot( + string DiscoveredIssuer, int SigningKeyCount, bool Complete, IReadOnlyCollection Subjects); + +/// +/// The read-only view of the new realm the continuity proof needs. The tool implements it over the realm's own +/// endpoints with an operator-supplied view-users credential; a test implements it over a fixed list. +/// +/// +/// An implementation reads, and refuses by throwing ; it never writes and +/// never returns a partial enumeration as complete. +/// +public interface INewRealmContinuitySource +{ + /// Reads the discovery document, the key set and every user of the realm behind . + Task ReadAsync(string issuer, CancellationToken cancellationToken = default); +} + +/// The new realm could not be read completely. A fixed message: no address, credential or body is retained. +public sealed class NewRealmUnavailableException() + : Exception("The new realm could not be read completely."); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs new file mode 100644 index 00000000..a34da74d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs @@ -0,0 +1,480 @@ +using System.Data; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Time; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// +/// The controlled issuer rebind (ADR-0104): the database half the offline tool drives, on the confined role +/// learnstack_identity_rebind and nothing else. +/// +/// +/// +/// Order, and why. One direct, non-pooled transaction takes the exclusive rebind advisory lock as its first +/// statement, so a start or a creation waits for it. Under that lock the tool reads the stored authority; a run whose +/// target already equals the stored issuer ends there, writing nothing, not even a row. Otherwise the intent row +/// commits on its own short transaction, so an aborted attempt is on record, and only then the freeze check, the +/// continuity proof, the issuer update and the result row run on the main transaction, which commits them together +/// or not at all. +/// +/// +/// Every refusal leaves the state unchanged and a retry repeats the whole proof. An unknown COMMIT is +/// reconciled by reading the issuer on a fresh connection: the target means it applied, the old value means it did +/// not, anything else is reported as unknown. +/// +/// +public sealed class IdentityIssuerRebind(IAuditStore audit, IClock clock) +{ + /// The only database role the tool may use. + public const string RoleName = "learnstack_identity_rebind"; + + /// The runtime roles whose sessions freeze the rebind: the platform role runs in the same hosts. + private static readonly string[] RuntimeRoles = + ["learnstack_app", "learnstack_outbox_admin", "learnstack_identity_ingress", "learnstack_platform"]; + + private const string AdvisoryLock = "SELECT pg_catalog.pg_advisory_xact_lock(@key)"; + + /// The longest the tool waits for the exclusive lock when none is asked for. + public static readonly TimeSpan DefaultLockWait = TimeSpan.FromSeconds(30); + + /// Runs one rebind to and returns how it ended; it never throws for a refusal. + /// The rebind role's connection string; any other role is refused. + /// The stable authority and the new issuer. + /// The operator's admission for the rebind operation. + /// The read-only view of the new realm. + /// How long the first statement waits for the exclusive lock; when null. + /// The run's deadline. + public async Task RunAsync( + string connectionString, + IdentityAuthorityRegistration target, + PlatformAdmission admission, + INewRealmContinuitySource realm, + TimeSpan? lockWait = null, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionString); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(admission); + ArgumentNullException.ThrowIfNull(realm); + + var outcome = await RunCoreAsync(connectionString, target, admission, realm, lockWait ?? DefaultLockWait, cancellationToken); + IdentityRebindMetrics.Record(outcome); + return outcome; + } + + private async Task RunCoreAsync( + string connectionString, + IdentityAuthorityRegistration target, + PlatformAdmission admission, + INewRealmContinuitySource realm, + TimeSpan lockWait, + CancellationToken cancellationToken) + { + // The admission is the operator's authority: this operation only, fresh when the run begins (the proof + // may run longer than the admission's age, which bounds the start and not the work), and spent once. + if (!ReferenceEquals(admission.Operation, PlatformOperations.IdentityAuthorityRebind) + || string.IsNullOrEmpty(admission.Operator.CorrelationId) + || (clock.UtcNow - admission.IssuedAt).Duration() > PlatformAdmission.MaximumAge + || !admission.TryConsume()) + { + return Refused(IdentityRebindRefusal.NotAdmitted); + } + + var connection = Normalize(connectionString, lockWait); + if (connection is null) + { + return Refused(IdentityRebindRefusal.RoleInvalid); + } + + NpgsqlConnection? main = null; + NpgsqlTransaction? transaction = null; + try + { + main = await OpenAsync(connection, cancellationToken); + if (!await HasExactPostureAsync(main, cancellationToken)) + { + return Refused(IdentityRebindRefusal.RoleInvalid); + } + + transaction = await main.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); + await ExecuteAsync(main, transaction, AdvisoryLock, cancellationToken, + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + + var (storedAuthority, storedIssuer) = await ReadAuthorityAsync(main, transaction, cancellationToken); + if (storedAuthority == target.AuthorityId.Value + && string.Equals(storedIssuer, target.Issuer, StringComparison.Ordinal)) + { + await transaction.RollbackAsync(cancellationToken); + return new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied); + } + + if (!await TryWriteIntentAsync(connection, admission, storedAuthority, storedIssuer, target.Issuer, cancellationToken)) + { + return Refused(IdentityRebindRefusal.AuditFailed); + } + + if (storedAuthority != target.AuthorityId.Value) + { + return Refused(IdentityRebindRefusal.AuthorityMismatch); + } + + var sessions = await CountRuntimeSessionsAsync(main, transaction, cancellationToken); + if (sessions > 0) + { + return new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.LiveSessions, null, sessions); + } + + var snapshot = await ReadRealmAsync(realm, target.Issuer, cancellationToken); + if (snapshot is null) + { + return Refused(IdentityRebindRefusal.NewRealmUnavailable); + } + + if (!string.Equals(snapshot.DiscoveredIssuer, target.Issuer, StringComparison.Ordinal)) + { + return Refused(IdentityRebindRefusal.NewRealmIssuerMismatch); + } + + if (!snapshot.Complete || snapshot.SigningKeyCount < 1) + { + return Refused(IdentityRebindRefusal.NewRealmIncomplete); + } + + var stored = await ReadUsersAsync(main, transaction, storedAuthority, cancellationToken); + var continuity = IdentityRebindContinuity.Evaluate(target.AuthorityId, stored, snapshot.Subjects); + if (!continuity.Holds) + { + return new IdentityRebindOutcome( + IdentityRebindResult.Refused, IdentityRebindRefusal.ContinuityBroken, continuity, sessions); + } + + await ChangeIssuerAsync(main, transaction, storedIssuer, target.Issuer, cancellationToken); + await audit.WriteIdentityRebindResultAsync( + Draft(admission, admission.Operation.AuditSlug, AuditOutcome.Success, storedAuthority, + storedIssuer, target.Issuer, continuity), + admission, main, transaction, cancellationToken); + + return await CommitAsync(transaction, connection, storedIssuer, target.Issuer, continuity, cancellationToken); + } + catch (AuditWriteFailedException) + { + return Refused(IdentityRebindRefusal.AuditFailed); + } + catch (PostgresException failure) when (failure.SqlState == PostgresErrorCodes.LockNotAvailable) + { + return Refused(IdentityRebindRefusal.RebindInProgress); + } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException) + { + return Refused(IdentityRebindRefusal.DatabaseUnavailable); + } + catch (OperationCanceledException) + { + return Refused(IdentityRebindRefusal.Cancelled); + } + finally + { + // An uncommitted transaction rolls back here, and with it the lock. + if (transaction is not null) + { + await transaction.DisposeAsync(); + } + + if (main is not null) + { + await main.DisposeAsync(); + } + } + } + + private static async Task CommitAsync( + NpgsqlTransaction transaction, + string connection, + string oldIssuer, + string newIssuer, + IdentityRebindContinuityResult continuity, + CancellationToken cancellationToken) + { + try + { + await transaction.CommitAsync(cancellationToken); + return new IdentityRebindOutcome(IdentityRebindResult.Applied, Continuity: continuity); + } + catch (Exception failure) when (failure is not OutOfMemoryException) + { + // The server may have committed before the connection failed. Read the issuer on a fresh connection: + // the target means it applied, the old value means it did not, and anything else is not guessed at. + try + { + await using var reader = await OpenAsync(connection, CancellationToken.None); + await using var command = new NpgsqlCommand("SELECT issuer FROM public.identity_authority WHERE id = 1", reader); + var current = (string?)await command.ExecuteScalarAsync(CancellationToken.None); + if (string.Equals(current, newIssuer, StringComparison.Ordinal)) + { + return new IdentityRebindOutcome(IdentityRebindResult.Applied, Continuity: continuity); + } + + return string.Equals(current, oldIssuer, StringComparison.Ordinal) + ? new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.CommitFailed, continuity) + : new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); + } + catch (Exception reconcile) when (reconcile is NpgsqlException or TimeoutException or InvalidOperationException) + { + return new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); + } + } + } + + /// Normalizes the connection string, or null when it is not the rebind role's. + private static string? Normalize(string connectionString, TimeSpan lockWait) + { + var builder = new NpgsqlConnectionStringBuilder(connectionString); + if (!string.Equals(builder.Username, RoleName, StringComparison.Ordinal)) + { + return null; + } + + // A direct, never-pooled, never-multiplexed connection of its own, so the lock belongs to this transaction + // and no other session shares it. The first statement is the lock, so the wait is bounded here by the + // server and not by a statement; a transaction that idles longer than a proof could is the tool's fence. + builder.Pooling = false; + builder.Multiplexing = false; + builder.Enlist = false; + builder.IncludeErrorDetail = false; + builder.LogParameters = false; + builder.Timeout = 15; + builder.CommandTimeout = 120; + builder.ApplicationName = "learnstack-identity-rebind"; + builder.Options = FormattableString.Invariant( + $"-c lock_timeout={(int)Math.Max(1, lockWait.TotalMilliseconds)} -c statement_timeout=120000 -c idle_in_transaction_session_timeout=900000"); + return builder.ConnectionString; + } + + private static async Task OpenAsync(string connectionString, CancellationToken cancellationToken) + { + var connection = new NpgsqlConnection(connectionString); + try + { + await connection.OpenAsync(cancellationToken); + return connection; + } + catch + { + await connection.DisposeAsync(); + throw; + } + } + + /// + /// The role is exactly what the migration granted: itself, no attribute that escalates, no membership either way, + /// no privilege on any other table, and the one column it may change. + /// + private static async Task HasExactPostureAsync(NpgsqlConnection connection, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + """ + SELECT session_user::text, current_user::text, r.rolcanlogin, r.rolinherit, r.rolbypassrls, r.rolsuper, + r.rolcreatedb, r.rolcreaterole, r.rolreplication, + EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR m.roleid = r.oid), + has_schema_privilege(r.oid, 'public', 'CREATE'), + has_database_privilege(r.oid, current_database(), 'CREATE'), + (SELECT count(*) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'f') + AND c.relname NOT IN ('identity_authority', 'users', @audit) + AND has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES')), + has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES'), + has_column_privilege(r.oid, 'public.users', 'id', 'SELECT,UPDATE,REFERENCES'), + has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,DELETE,TRUNCATE,TRIGGER,REFERENCES'), + has_column_privilege(r.oid, 'public.identity_authority', 'authority_id', 'UPDATE,INSERT,REFERENCES'), + has_column_privilege(r.oid, 'public.identity_authority', 'id', 'UPDATE,INSERT,REFERENCES'), + has_column_privilege(r.oid, 'public.identity_authority', 'issuer', 'UPDATE'), + has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES'), + has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), 'INSERT') + FROM pg_catalog.pg_roles r WHERE r.rolname = current_user + """, connection); + command.Parameters.AddWithValue("audit", IdentityRebindAuditInstaller.Table); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + return false; + } + + return reader.GetString(0) == RoleName && reader.GetString(1) == RoleName + && reader.GetBoolean(2) + && !reader.GetBoolean(3) && !reader.GetBoolean(4) && !reader.GetBoolean(5) + && !reader.GetBoolean(6) && !reader.GetBoolean(7) && !reader.GetBoolean(8) + && !reader.GetBoolean(9) && !reader.GetBoolean(10) && !reader.GetBoolean(11) + && reader.GetInt64(12) == 0 + && !reader.GetBoolean(13) && !reader.GetBoolean(14) + && !reader.GetBoolean(15) && !reader.GetBoolean(16) && !reader.GetBoolean(17) + && reader.GetBoolean(18) + && !reader.GetBoolean(19) && reader.GetBoolean(20); + } + + private static async Task<(Guid Authority, string Issuer)> ReadAuthorityAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "SELECT authority_id, issuer FROM public.identity_authority WHERE id = 1", connection, transaction); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + throw new InvalidOperationException("No identity authority is installed."); + } + + var result = (reader.GetGuid(0), reader.GetString(1)); + if (await reader.ReadAsync(cancellationToken)) + { + throw new InvalidOperationException("The identity authority is not a singleton."); + } + + return result; + } + + /// + /// The intent row, on its own connection and its own short transaction so it commits whether or not the main + /// transaction does. It takes no lock the main transaction holds, because it reads nothing. + /// + private async Task TryWriteIntentAsync( + string connection, PlatformAdmission admission, Guid authority, string oldIssuer, string newIssuer, + CancellationToken cancellationToken) + { + try + { + await using var intent = await OpenAsync(connection, cancellationToken); + await using var transaction = await intent.BeginTransactionAsync(cancellationToken); + await audit.WriteIdentityRebindIntentAsync( + Draft(admission, admission.Operation.AttemptAuditSlug!, AuditOutcome.Indeterminate, authority, + oldIssuer, newIssuer, continuity: null), + admission, intent, transaction, cancellationToken); + await transaction.CommitAsync(cancellationToken); + return true; + } + catch (Exception failure) when (failure is AuditWriteFailedException or NpgsqlException or TimeoutException) + { + return false; + } + } + + private static async Task CountRuntimeSessionsAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) + { + // pg_stat_activity shows another role's session as a row with its role and database even where its query + // is hidden, which is all the freeze needs: a session of a runtime role, other than this one's own. + await using var command = new NpgsqlCommand( + """ + SELECT count(*) FROM pg_catalog.pg_stat_activity + WHERE datname = current_database() AND usename::text = ANY(@roles) AND pid <> pg_catalog.pg_backend_pid() + """, connection, transaction); + command.Parameters.AddWithValue("roles", RuntimeRoles); + return (int)(long)(await command.ExecuteScalarAsync(cancellationToken))!; + } + + private static async Task ReadRealmAsync( + INewRealmContinuitySource realm, string issuer, CancellationToken cancellationToken) + { + try + { + return await realm.ReadAsync(issuer, cancellationToken); + } + catch (NewRealmUnavailableException) + { + return null; + } + } + + private static async Task> ReadUsersAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, Guid authority, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "SELECT subject_key, provider_subject, status FROM public.users WHERE authority_id = @authority", + connection, transaction); + command.Parameters.AddWithValue("authority", authority); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + var users = new List(); + while (await reader.ReadAsync(cancellationToken)) + { + if (!Enum.TryParse(reader.GetString(2), ignoreCase: false, out var status)) + { + throw new InvalidOperationException("A stored user has a status this rebind does not know."); + } + + users.Add(new IdentityRebindStoredUser( + IdentitySubjectKey.FromBytes(reader.GetFieldValue(0)), + reader.IsDBNull(1) ? null : reader.GetString(1), + status)); + } + + return users; + } + + private static async Task ChangeIssuerAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, string oldIssuer, string newIssuer, + CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = @new WHERE id = 1 AND issuer = @old", connection, transaction); + command.Parameters.AddWithValue("new", newIssuer); + command.Parameters.AddWithValue("old", oldIssuer); + if (await command.ExecuteNonQueryAsync(cancellationToken) != 1) + { + throw new InvalidOperationException("The identity authority issuer did not change as read."); + } + } + + private static async Task ExecuteAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, CancellationToken cancellationToken, + params (string Name, object Value)[] parameters) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + foreach (var (name, value) in parameters) + { + command.Parameters.AddWithValue(name, value); + } + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + private AuditEntryDraft Draft( + PlatformAdmission admission, string operation, AuditOutcome outcome, Guid authority, string oldIssuer, + string newIssuer, IdentityRebindContinuityResult? continuity) => new() + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "identity", + Operation = operation, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = nameof(IdentityAuthority), + EntityId = authority.ToString("D"), + Outcome = outcome, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = "{\"issuer\":" + AuditJson.Quote(oldIssuer) + "}", + AfterState = "{\"issuer\":" + AuditJson.Quote(newIssuer) + "}", + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = clock.UtcNow, + Metadata = "{\"operator\":" + PlatformOperatorAttribution.From(admission).ToOperatorJson(admission.Ticket) + + (continuity is null ? string.Empty : ",\"continuity\":" + ContinuityJson(continuity)) + "}", + }; + + private static string ContinuityJson(IdentityRebindContinuityResult counts) => + "{\"active\":" + counts.StoredActive + ",\"closing\":" + counts.StoredClosing + ",\"closed\":" + counts.StoredClosed + + ",\"reported\":" + counts.Enumerated + ",\"unkeyable\":" + counts.Unkeyable + + ",\"unbootstrapped\":" + counts.Unbootstrapped + "}"; + + private static IdentityRebindOutcome Refused(IdentityRebindRefusal refusal) => + new(IdentityRebindResult.Refused, refusal); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs new file mode 100644 index 00000000..6f9cfd06 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs @@ -0,0 +1,115 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// One stored user as the continuity proof reads it: only the four columns the rebind role may see. +public sealed record IdentityRebindStoredUser(IdentitySubjectKey SubjectKey, string? ProviderSubject, UserStatus Status); + +/// What the continuity proof counted. Counts and classes only; no subject, key or person is named. +/// Active users of the stored authority. +/// Closing users, which neither rule below judges unless only their key is retained. +/// Closed tombstones, which retain only a key. +/// Distinct subjects the new realm reported. +/// Reported subjects that cannot be a LearnStack subject (blank, over 255 characters or not storable text). +/// Active users whose exact subject the new realm does not report. +/// Retained keys of Closed (or key-only Closing) users that a reported subject would claim again. +/// Reported subjects that match no stored user, which is a person who has not signed in yet. +public sealed record IdentityRebindContinuityResult( + int StoredActive, + int StoredClosing, + int StoredClosed, + int Enumerated, + int Unkeyable, + int MissingActive, + int ReappearingClosed, + int Unbootstrapped) +{ + /// Whether continuity holds: no Active user is lost and no closed person can reappear. + public bool Holds => MissingActive == 0 && ReappearingClosed == 0; +} + +/// +/// The continuity proof of a controlled issuer rebind (ADR-0104 § 6) as a pure function of what the database +/// retains and what the new realm reports. +/// +/// +/// +/// Active rows retain the exact subject, so presence is a direct ordinal comparison. Closed rows retain only the +/// key, so absence needs the canonical encoding: the key of no reported subject may equal a retained Closed key, +/// which is what stops a tombstoned person from reappearing under the new issuer. A reported subject with no +/// stored key is allowed, because that person has not bootstrapped. +/// +/// +/// A Closing user is judged by neither rule while it retains its subject, because closure owns that transition; a +/// Closing user that retains only its key is judged like a Closed one. A reported subject that cannot be a +/// LearnStack subject is counted and cannot equal any stored one, since every stored subject was keyed under the +/// same rules. +/// +/// +public static class IdentityRebindContinuity +{ + /// Compares the stored users of with the complete set the new realm reported. + public static IdentityRebindContinuityResult Evaluate( + IdentityAuthorityId authority, + IReadOnlyCollection stored, + IReadOnlyCollection reported) + { + ArgumentNullException.ThrowIfNull(stored); + ArgumentNullException.ThrowIfNull(reported); + + var subjects = new HashSet(reported, StringComparer.Ordinal); + var reportedKeys = new HashSet(StringComparer.Ordinal); + var unkeyable = 0; + foreach (var subject in subjects) + { + try + { + reportedKeys.Add(IdentitySubjectKey.Compute(authority, subject).Hex); + } + catch (ArgumentException) + { + unkeyable++; + } + } + + int active = 0, closing = 0, closed = 0, missing = 0, reappearing = 0; + var storedKeys = new HashSet(StringComparer.Ordinal); + foreach (var user in stored) + { + storedKeys.Add(user.SubjectKey.Hex); + switch (user.Status) + { + case UserStatus.Active: + active++; + if (user.ProviderSubject is null || !subjects.Contains(user.ProviderSubject)) + { + missing++; + } + + break; + case UserStatus.Closing: + closing++; + if (user.ProviderSubject is null && reportedKeys.Contains(user.SubjectKey.Hex)) + { + reappearing++; + } + + break; + default: + closed++; + if (reportedKeys.Contains(user.SubjectKey.Hex)) + { + reappearing++; + } + + break; + } + } + + return new IdentityRebindContinuityResult( + active, closing, closed, subjects.Count, unkeyable, missing, reappearing, + reportedKeys.Count(key => !storedKeys.Contains(key))); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs new file mode 100644 index 00000000..7964ba52 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs @@ -0,0 +1,125 @@ +using System.Diagnostics.Metrics; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// How a controlled issuer rebind ended (ADR-0104 § 9). +public enum IdentityRebindResult +{ + /// The issuer changed and its result row committed with it. + Applied = 1, + + /// The stored issuer already equalled the target; nothing was written, not even a row. + AlreadyApplied = 2, + + /// The state is unchanged; a retry repeats the whole proof. + Refused = 3, + + /// The commit's outcome could not be read back; the operator reads the stored issuer before anything else. + Unknown = 4, +} + +/// Why a rebind was refused: a closed set that reports a class and never a value. +public enum IdentityRebindRefusal +{ + None = 0, + NotAdmitted, + RoleInvalid, + RebindInProgress, + DatabaseUnavailable, + AuthorityMismatch, + LiveSessions, + NewRealmUnavailable, + NewRealmIssuerMismatch, + NewRealmIncomplete, + ContinuityBroken, + AuditFailed, + CommitFailed, + Cancelled, +} + +/// The end of one run and what it counted. +/// How the run ended. +/// The class of a refusal, or . +/// The continuity counts, when the proof ran. +/// How many sessions of a runtime role the freeze check saw, when it ran. +public sealed record IdentityRebindOutcome( + IdentityRebindResult Result, + IdentityRebindRefusal Refusal = IdentityRebindRefusal.None, + IdentityRebindContinuityResult? Continuity = null, + int? LiveSessions = null); + +/// Counters of the rebind: runs by outcome, and the continuity proof's counts by class (ADR-0104 § 11). +/// +/// The labels are closed sets. The offline tool is a short-lived process, so it prints the same classes in its +/// outcome line and exports these only when an OTLP endpoint is configured for it. +/// +public static class IdentityRebindMetrics +{ + /// The meter name. + public const string MeterName = "learnstack.identity.rebind"; + + /// Runs by outcome: applied, already_applied, unknown, or a refusal class. + public const string RunCounterName = "learnstack_identity_rebind_runs_total"; + + /// Continuity counts by class. + public const string ContinuityCounterName = "learnstack_identity_rebind_continuity_total"; + + private static readonly Meter Meter = new(MeterName); + + private static readonly Counter Runs = + Meter.CreateCounter(RunCounterName, description: "Controlled issuer rebind runs by outcome."); + + private static readonly Counter Continuity = + Meter.CreateCounter(ContinuityCounterName, description: "Continuity proof counts by class."); + + /// Records one finished run. + public static void Record(IdentityRebindOutcome outcome) + { + ArgumentNullException.ThrowIfNull(outcome); + Runs.Add(1, new KeyValuePair("outcome", Label(outcome))); + if (outcome.Continuity is { } counts) + { + Add("active", counts.StoredActive); + Add("closing", counts.StoredClosing); + Add("closed", counts.StoredClosed); + Add("reported", counts.Enumerated); + Add("unkeyable", counts.Unkeyable); + Add("missing_active", counts.MissingActive); + Add("reappearing_closed", counts.ReappearingClosed); + Add("unbootstrapped", counts.Unbootstrapped); + } + } + + /// The closed outcome label of a run. + public static string Label(IdentityRebindOutcome outcome) => outcome.Result switch + { + IdentityRebindResult.Applied => "applied", + IdentityRebindResult.AlreadyApplied => "already_applied", + IdentityRebindResult.Unknown => "unknown", + _ => outcome.Refusal switch + { + IdentityRebindRefusal.NotAdmitted => "refused_not_admitted", + IdentityRebindRefusal.RoleInvalid => "refused_role_invalid", + IdentityRebindRefusal.RebindInProgress => "refused_rebind_in_progress", + IdentityRebindRefusal.DatabaseUnavailable => "refused_database_unavailable", + IdentityRebindRefusal.AuthorityMismatch => "refused_authority_mismatch", + IdentityRebindRefusal.LiveSessions => "refused_live_sessions", + IdentityRebindRefusal.NewRealmUnavailable => "refused_new_realm_unavailable", + IdentityRebindRefusal.NewRealmIssuerMismatch => "refused_new_realm_issuer_mismatch", + IdentityRebindRefusal.NewRealmIncomplete => "refused_new_realm_incomplete", + IdentityRebindRefusal.ContinuityBroken => "refused_continuity_broken", + IdentityRebindRefusal.AuditFailed => "refused_audit_failed", + IdentityRebindRefusal.CommitFailed => "refused_commit_failed", + IdentityRebindRefusal.Cancelled => "refused_cancelled", + _ => "refused", + }, + }; + + private static void Add(string name, int count) + { + if (count > 0) + { + Continuity.Add(count, new KeyValuePair("class", name)); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs index 6bb39565..f7269e16 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.Audit; using Microsoft.EntityFrameworkCore.Migrations; namespace LearnStack.Modules.Identity.Infrastructure.Persistence; @@ -10,7 +11,8 @@ namespace LearnStack.Modules.Identity.Infrastructure.Persistence; /// learnstack_identity_rebind is a login role without BYPASSRLS that no runtime host /// holds. It reads identity_authority, may change its issuer column and no other, reads /// the four users columns the continuity proof compares, and inserts audit_log rows that -/// one policy arm limits to the platform sentinel, the identity module and the two rebind operations. +/// one policy arm limits to the platform sentinel, the identity module and the two rebind operations; that +/// grant and arm are installed by . /// /// /// One permissive policy per command: the read policy gains the role, a third policy admits its @@ -22,11 +24,12 @@ namespace LearnStack.Modules.Identity.Infrastructure.Persistence; /// internal static class IdentityAuthorityRebindDdl { - internal static void Add(MigrationBuilder migration) => migration.Sql(""" + internal static void Add(MigrationBuilder migration) + { + migration.Sql(""" GRANT SELECT ON public.identity_authority TO learnstack_identity_rebind; GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind; GRANT SELECT (authority_id, subject_key, provider_subject, status) ON public.users TO learnstack_identity_rebind; - GRANT INSERT ON public.audit_log TO learnstack_identity_rebind; ALTER POLICY identity_authority_read ON public.identity_authority USING (current_user IN ('learnstack_app','learnstack_migration','learnstack_identity_rebind')); @@ -41,29 +44,6 @@ AND encode(subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key', OR current_user='learnstack_migration' OR current_user='learnstack_identity_rebind'); - ALTER POLICY audit_log_isolation ON public.audit_log - WITH CHECK ( - (tenant_id = NULLIF(current_setting('app.tenant_id',true),'')::uuid - AND ((organization_id IS NULL AND NULLIF(current_setting('app.organization_id',true),'') IS NULL) - OR organization_id = NULLIF(current_setting('app.organization_id',true),'')::uuid)) - OR (current_user='learnstack_app' - AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid - AND organization_id IS NULL AND module='identity' AND operation='identity.user.create' - AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='User' - AND outcome IN ('success','failed','indeterminate') - AND metadata->>'identity_source' IN ('identity-bootstrap','identity-seed-adoption') - AND metadata->>'identity_authority_id'=NULLIF(current_setting('app.identity_authority_id',true),'') - AND metadata->>'identity_subject_key'=NULLIF(current_setting('app.identity_subject_key',true),'')) - OR (current_user='learnstack_identity_rebind' - AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid - AND organization_id IS NULL AND module='identity' - AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='IdentityAuthority' - AND reason='issuer_rebind' AND actor_user_id IS NULL - AND actor_email IS NULL AND ip_address IS NULL AND user_agent IS NULL - AND metadata->'operator' IS NOT NULL - AND ((operation='identity.authority.rebind_attempt' AND outcome='indeterminate') - OR (operation='identity.authority.rebind' AND outcome='success')))); - CREATE FUNCTION public.fn_identity_authority_immutable_key() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ BEGIN @@ -76,4 +56,8 @@ IF NEW.id IS DISTINCT FROM OLD.id OR NEW.authority_id IS DISTINCT FROM OLD.autho CREATE TRIGGER tg_identity_authority_immutable_key BEFORE UPDATE ON public.identity_authority FOR EACH ROW EXECUTE FUNCTION public.fn_identity_authority_immutable_key(); """); + + // The audit_log grant and the one policy arm belong to the central audit installer: no module names the table. + IdentityRebindAuditInstaller.Install(migration); + } } diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index e0258d67..b3ecca7a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -516,15 +516,16 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046, ADR-0047, ADR-0072, ADR-0077 and ADR-0101 authorize eleven writes and no update; another method would - // make the port contradict its closed write contract. + // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0101 and ADR-0104 authorize thirteen writes and no update; + // another method would make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) .Should().BeEquivalentTo( "WritePendingAsync", "WriteStandaloneAsync", "WriteBestEffortAsync", "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync", - "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync"); + "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync", + "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 14d4cea8..81d63219 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -358,11 +358,15 @@ private static bool IsClosedInvitationForwarding(Method method, Instruction inst /// /// The operator token profile is its own authority (ADR-0101 § 2, § 3) and reads the validated - /// operator token's claims by design. It is exempt by exact type and method, so a raw read in any - /// other method of that type, or anywhere else, is still an offender. + /// operator token's claims by design; the offline validator that the rebind tool drives validates the same + /// token with the stock handler before it applies the profile (ADR-0101 § 7, ADR-0104 § 3). Both are exempt by + /// exact type and method, so a raw read in any other method of those types, or anywhere else, is still an + /// offender. /// private static bool IsOperatorTokenProfileRead(Call call) => - call.Source.Owner.FullName == Authentication + "PlatformOperatorTokenProfile" && call.Source.Name == "TryRead"; + call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenProfile" && call.Source.Name == "TryRead" + || call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenValidator" + && call.Source.Name is "ValidateAsync" or ".cctor"; private static bool IsClosedRolesAbsenceCheck(Call call) { diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs index 2900ecca..60e4ecbe 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs @@ -11,6 +11,7 @@ namespace LearnStack.Tests.Architecture; public sealed partial class AuthenticationAuthorityTests { private const string Authentication = "LearnStack.Api.Authentication."; + private const string OperatorValidation = "LearnStack.Infrastructure.PlatformOperator."; private const string Identity = Authentication + nameof(ValidatedTenantIdentity); private const string Verified = Authentication + nameof(VerifiedProviderSubject); private const string Feature = Authentication + nameof(TenantCredentialFeature); diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index d094aeb5..7ea5d7a0 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -204,10 +204,12 @@ [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison "JWT bearer metadata and JWKS (ADR-0064): the fixed Authentication:Tenant:Issuer only", ["LearnStack.Api/Authentication/CurrentInvitationRecipientReader.cs"] = "the invitation recipient's UserInfo read (ADR-0093): the fixed tenant-realm issuer only", - ["LearnStack.Api/Authentication/BoundedMetadataReader.cs"] = - "the bounded metadata read both bearer schemes share (ADR-0064, ADR-0101 § 2): the fixed issuer each scheme configures only", - ["LearnStack.Api/Authentication/PlatformOperatorMetadata.cs"] = - "the operator scheme's metadata and JWKS client (ADR-0101 § 2): the one pinned PlatformOperator:Issuer, never a followed redirect", + ["LearnStack.Infrastructure/Identity/BoundedMetadataReader.cs"] = + "the bounded metadata read both bearer schemes and the rebind tool share (ADR-0064, ADR-0101 § 2, ADR-0104): the fixed issuer each caller configures only", + ["LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetadata.cs"] = + "the operator validator's metadata and JWKS client, shared by the API scheme and the offline rebind tool (ADR-0101 § 2, ADR-0104 § 3): the one pinned PlatformOperator:Issuer, never a followed redirect", + ["LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs"] = + "the offline rebind tool's read of the new realm (ADR-0104 § 4, § 6): the one new issuer's own origin with an operator-supplied view-users credential, never a followed redirect", ["LearnStack.Infrastructure/Email/Smtp/SmtpEmailProvider.cs"] = "operator-configured SMTP host for invitation mail; not a tenant URL", }; diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs index 8a434112..938c7c06 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs @@ -18,6 +18,9 @@ public sealed partial class IdentityAuditConventionTests private const string BindingService = "LearnStack.Modules.Identity.Infrastructure.Bindings.GlobalIdentityBindingService"; private const string InitialMigration = "LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.create_identity_schema"; private const string Installer = "LearnStack.Infrastructure.Audit.IdentityCreationWitnessInstaller"; + private const string RebindInstaller = "LearnStack.Infrastructure.Audit.IdentityRebindAuditInstaller"; + private const string RebindDdl = "LearnStack.Modules.Identity.Infrastructure.Persistence.IdentityAuthorityRebindDdl"; + private const string RebindRun = "LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityIssuerRebind"; private const string GlobalSource = "LearnStack.Application.Audit.AuditExecutionCoordinator+GlobalCreationSource"; private const string InvitationJobStore = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailJobStore"; private const string InvitationStager = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailStager"; @@ -47,6 +50,11 @@ public void Global_Identity_Creation_Uses_The_Common_Audit_Owner() .Should().Equal(typeof(TransactionExecutionCoordinator).FullName + ".ExecuteFrameAsync"); Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.ReconcileGlobalIdentityAsync)) .Should().Equal(typeof(AuditExecutionCoordinator).FullName + ".ReconcileAsync"); + // ADR-0104 § 8: the two witness-bound rebind writes have one production caller each, the rebind run itself. + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.WriteIdentityRebindIntentAsync)) + .Should().Equal(RebindRun + ".TryWriteIntentAsync"); + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.WriteIdentityRebindResultAsync)) + .Should().Equal(RebindRun + ".RunCoreAsync"); var audit = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Infrastructure.Audit", "PostgresAuditStore.cs")); @@ -69,6 +77,8 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m Il.MethodsNaming(migration!, Installer).Should().Equal("Down", "Up"); Callers(Installer, "Install").Should().Equal(InitialMigration + ".Up"); Callers(Installer, "Remove").Should().Equal(InitialMigration + ".Down"); + // ADR-0104: the rebind role's audit_log grant and policy arm have one central owner and one caller. + Callers(RebindInstaller, "Install").Should().Equal(RebindDdl + ".Add"); foreach (var owner in new[] { InvitationJobStore, InvitationStager }) { var adapter = module.GetType(owner); @@ -96,6 +106,18 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m finally { definition.Body.Instructions.Remove(extraFrameworkRead); } } + [Fact] + public void Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock() + { + // ADR-0104 § 5: the exclusive form belongs to the rebind run and the shared form to authority qualification and + // the User-creation admission. A fourth taker is a fourth party that can wait on, or hold, the freeze. + Callers(typeof(IdentityAdvisoryLockKey).FullName!, nameof(IdentityAdvisoryLockKey.ForAuthorityRebind)) + .Should().Equal( + "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync", + "LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityAuthorityQualification.QualifyCoreAsync", + RebindRun + ".RunCoreAsync"); + } + [Fact] public void A_new_minter_or_a_borrowed_core_edge_is_rejected() { @@ -140,6 +162,7 @@ private static IEnumerable CoreEdgeViolations(TypeDefinition type) or "LearnStack.Application.Persistence.TransactionExecutionCoordinator" or "LearnStack.Application.Persistence.TransactionExecutionCoordinator/PreparedGlobalIdentityOwner" || type.FullName == InitialMigration && reference.FullName == Installer + || type.FullName == RebindDdl && reference.FullName == RebindInstaller || type.FullName is InvitationJobStore or InvitationStager && reference.FullName is InvitationProducer or InvitationJobOrigin || type.FullName == InvitationRegistration && reference.FullName == FrameworkRequests; diff --git a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj index 73962a6e..78e87008 100644 --- a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj +++ b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj @@ -32,6 +32,7 @@ itself is exactly what these rules exist to see. --> + diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs index 75d1ef83..743c6291 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs @@ -219,6 +219,9 @@ public void Module_DbContexts_Enlist_In_The_Ambient_UnitOfWork() "Persistence/EducationDbContextFactory.cs", "Persistence/IdentityDbContextFactory.cs", "LearnStack.Tools.IdentityAuthorityInstaller/Program.cs", + // ADR-0104's controlled issuer rebind opens its own direct, never-pooled connections as the confined + // sixth role: the exclusive-lock transaction, the intent-row transaction and the commit reconciliation. + "Bindings/IdentityIssuerRebind.cs", // Both runtime hosts delegate application-role construction to this // shared guard; the API retains its separate platform-role builder. diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 00dced9d..6efbe692 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -178,9 +178,9 @@ public void PlatformAdminScope_Entry_Requires_Platform_Permission() ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], "only the gate mints an admission, after it has evaluated a grant"); FullNames(types, typeof(PlatformOperatorWitness.Minter)).Should().BeEquivalentTo( - ["LearnStack.Api.Authentication.PlatformOperatorTokenProfile+WitnessMinter"], - "only the operator token profile mints a witness, through a private nested minter; the rebind " - + "tool joins in Step 3 by an edit to this list, not by accident"); + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenProfile+WitnessMinter"], + "only the operator token profile mints a witness, through a private nested minter; the offline rebind " + + "tool is a second caller of the profile, not a second minter (ADR-0101 § 7, ADR-0104 § 3)"); FullNames(types, typeof(IPlatformOperatorGate)).Should().BeEquivalentTo( ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], "a second gate is how a permissive default ships"); @@ -193,17 +193,60 @@ public void PlatformAdminScope_Entry_Requires_Platform_Permission() public void The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only() { // The witness is evidence that a token passed the profile. TryRead is the only door to the - // minter, so who may call it is the question: the scheme's TokenValidated event, which lives - // beside it, and nothing else in production code. The real-realm test and the offline rebind - // tool (Step 3) are the sanctioned further callers, the latter added here by name. - const string Boundary = "LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs"; + // minter, so who may call it is the question: the scheme's TokenValidated event, and the offline + // validator the rebind tool drives (ADR-0101 § 7: two callers, one validator), and nothing else in + // production code. The profile's own file names it too, because it defines it. + const string Scheme = "LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs"; + const string Offline = "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs"; + const string Profile = "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs"; SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile", except: null) - .Should().Equal([Boundary], "no other source file may name the profile that mints a witness"); + .Should().BeEquivalentTo([Scheme, Offline, Profile], "no other source file may name the profile that mints a witness"); SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile.TryRead(", except: null) - .Should().Equal([Boundary]); + .Should().BeEquivalentTo([Scheme, Offline], "only the two sanctioned callers read a token through the profile"); SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorWitness.Minter", except: null) - .Should().Equal([Boundary], "the witness minter base is named by its one nested subclass"); + .Should().BeEquivalentTo([Profile], "the witness minter base is named by its one nested subclass"); + } + + [Fact] + public void The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool() + { + // ADR-0104 § 2: the sixth role's connection string exists only in the offline tool's environment, so no runtime + // host can change the issuer whatever it does. Every spelling of the key, in code with comments stripped, is + // confined to the one tool file that reads it, and that file must name it, or the scan could pass over nothing. + const string Tool = "LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs"; + string[] spellings = ["ConnectionStrings__IdentityRebind", "ConnectionStrings:IdentityRebind", "GetConnectionString(\"IdentityRebind\")"]; + + foreach (var spelling in spellings) + { + SourceScan.FilesContaining(SourceScan.SourceRoot, spelling, except: Tool) + .Should().BeEmpty($"the rebind credential '{spelling}' is read by the tool alone"); + } + + SourceScan.FilesContaining(SourceScan.SourceRoot, "ConnectionStrings__IdentityRebind", except: null) + .Should().Equal([Tool], "the tool reads the credential from its environment, and the scan matched it"); + + // A planted negative control: a second reader anywhere else is found. + var planted = Directory.CreateTempSubdirectory("rebind-key-"); + try + { + File.WriteAllText( + Path.Combine(planted.FullName, "Leak.cs"), + "class Leak { string S => System.Environment.GetEnvironmentVariable(\"ConnectionStrings__IdentityRebind\"); }"); + SourceScan.FilesContaining(planted.FullName, "ConnectionStrings__IdentityRebind", except: null) + .Should().Equal(["Leak.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + + // No compose service, demo launcher or migration script forwards it to anything else. + foreach (var path in new[] { "scripts/demo.mjs", "scripts/demo-database.mjs", "scripts/migrate.mjs", "infra/compose/dev.yml", "infra/compose/e2e.yml" }) + { + File.ReadAllText(Path.Combine(RepositoryPaths.RepoRoot(), path.Replace('/', Path.DirectorySeparatorChar))) + .Should().NotContain("ConnectionStrings__IdentityRebind", $"{path} never carries the rebind credential"); + } } [Fact] diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs new file mode 100644 index 00000000..6d91739b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs @@ -0,0 +1,574 @@ +using System.Data.Common; +using System.Diagnostics.Metrics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The controlled issuer rebind end to end on real PostgreSQL as the confined role (ADR-0104): the positive run, +/// every refusal class with its state and audit trail, the continuity rules, the freeze, and the failure windows. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindTests(PublicReadFixture parent) +{ + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task A_Rebind_Changes_Only_The_Issuer_And_Records_An_Intent_And_A_Result_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 3); + var before = await proof.UsersAsync(); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting([.. proof.Subjects, "brand-new-person"])); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + outcome.Continuity.Should().BeEquivalentTo(new IdentityRebindContinuityResult(3, 0, 0, 4, 0, 0, 0, 1)); + (await proof.IssuerAsync()).Should().Be(NewIssuer); + (await proof.AuthorityAsync()).Should().Be(proof.Authority); + (await proof.UsersAsync()).Should().Equal(before, "no actor id, key or subject moved"); + + var rows = await proof.AuditRowsAsync(admission); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + ("identity.authority.rebind_attempt", "indeterminate"), ("identity.authority.rebind", "success")); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null + && row.Reason == "issuer_rebind" && row.Entity == proof.Authority.ToString("D")); + rows.Should().OnlyContain(row => row.Operator.GetProperty("ticket").GetString() == "CHG-104" + && row.Operator.GetProperty("subjectDigest").GetString() == admission.Operator.SubjectDigest); + rows[1].Before.GetProperty("issuer").GetString().Should().Be(proof.OldIssuer); + rows[1].After.GetProperty("issuer").GetString().Should().Be(NewIssuer); + rows[1].Continuity.GetProperty("active").GetInt32().Should().Be(3); + rows[1].Continuity.GetProperty("unbootstrapped").GetInt32().Should().Be(1); + rows[1].Raw.Should().NotContain(proof.Subjects[0], "no subject reaches an audit row"); + } + + [Fact] + public async Task A_Run_Whose_Target_Already_Equals_The_Stored_Issuer_Writes_Nothing_Not_Even_A_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var first = RebindProofSupport.Admit(); + (await proof.RunAsync(first, FixedRealm.Reporting(proof.Subjects))).Result.Should().Be(IdentityRebindResult.Applied); + + var again = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + var outcome = await proof.RunAsync(again, realm); + + outcome.Result.Should().Be(IdentityRebindResult.AlreadyApplied); + realm.Reads.Should().Be(0, "the new realm is not even read"); + (await proof.AuditRowsAsync(again)).Should().BeEmpty(); + (await proof.AuditRowsAsync(first)).Should().HaveCount(2); + } + + [Fact] + public async Task An_Admission_For_Another_Operation_Or_A_Stale_Or_A_Reused_One_Is_Refused_Before_Any_Connection() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + + var killswitch = TestPlatformAdmissions.Admission(PlatformOperations.KillswitchToggle, correlationId: "00-x"); + (await proof.RunAsync(killswitch, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted); + + var stale = RebindProofSupport.Admit(issuedAt: DateTimeOffset.UtcNow.AddMinutes(-5)); + (await proof.RunAsync(stale, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted); + + var used = RebindProofSupport.Admit(); + (await proof.RunAsync(used, FixedRealm.Reporting(proof.Subjects))).Result.Should().Be(IdentityRebindResult.Applied); + (await proof.RunAsync(used, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted, + "an admission is spent by its first run"); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_migration")] + [InlineData("learnstack_platform")] + public async Task Any_Role_But_The_Rebind_Role_Is_Refused_Before_Its_First_Statement(string role) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var connection = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Username = role }.ConnectionString; + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: connection); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Theory] + // Role attributes and memberships are cluster-wide and need the superuser; object grants are this database's own. + [InlineData(true, "ALTER ROLE learnstack_identity_rebind CREATEDB", "ALTER ROLE learnstack_identity_rebind NOCREATEDB")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind INHERIT", "ALTER ROLE learnstack_identity_rebind NOINHERIT")] + [InlineData(true, "GRANT learnstack_migration TO learnstack_identity_rebind", "REVOKE learnstack_migration FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT ON public.tenants TO learnstack_identity_rebind", "REVOKE SELECT ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (authority_id) ON public.identity_authority TO learnstack_identity_rebind", "REVOKE UPDATE (authority_id) ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (id) ON public.users TO learnstack_identity_rebind", "REVOKE SELECT (id) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT ON public.audit_log TO learnstack_identity_rebind", "REVOKE SELECT ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT CREATE ON SCHEMA public TO learnstack_identity_rebind", "REVOKE CREATE ON SCHEMA public FROM learnstack_identity_rebind")] + public async Task A_Role_That_Holds_Anything_Beyond_Its_Grants_Is_Refused_Before_The_Lock(bool clusterWide, string escalate, string restore) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // The collection runs serially against its own container, and every escalation is undone in the same test. + await Apply(clusterWide, escalate); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid, escalate); + } + finally + { + await Apply(clusterWide, restore); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + async Task Apply(bool superuser, string sql) + { + if (superuser) + { + await parent.Postgres.ExecuteAsSuperuserAsync(sql); + return; + } + + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.OwnerConnection); + await IdentityMembershipFixture.ExecuteAsync(owner, null, sql); + } + } + + [Fact] + public async Task A_Rebind_That_Is_Already_Running_Makes_The_Second_One_Wait_Then_Refuse_Without_A_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await using var held = await proof.HoldRebindLockAsync(); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), lockWait: TimeSpan.FromSeconds(1)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RebindInProgress); + (await proof.AuditRowsAsync(admission)).Should().BeEmpty("the lock is the first statement, so nothing was decided yet"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task A_Stored_Authority_That_Is_Not_The_Configured_One_Is_Refused_After_The_Intent_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var other = new IdentityAuthorityRegistration(IdentityAuthorityId.From(Guid.CreateVersion7()), NewIssuer); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), target: other); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuthorityMismatch); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuthorityAsync()).Should().Be(proof.Authority, "a changed AuthorityId would re-key every person"); + } + + [Fact] + public async Task The_Same_Issuer_Under_Another_Authority_Is_Not_Already_Applied_It_Is_A_Misconfiguration() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var other = new IdentityAuthorityRegistration(IdentityAuthorityId.From(Guid.CreateVersion7()), proof.OldIssuer); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), target: other); + + outcome.Result.Should().Be(IdentityRebindResult.Refused, "equal issuers do not make the run a no-op when the authority differs"); + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuthorityMismatch); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle(); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_outbox_admin")] + [InlineData("learnstack_identity_ingress")] + [InlineData("learnstack_platform")] + public async Task A_Live_Session_Of_A_Runtime_Role_Freezes_The_Rebind_And_Its_Disappearance_Lifts_It(string role) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + + int? seen; + await using (var session = await proof.OpenSessionAsync(role)) + { + var refused = await proof.RunAsync(admission, realm); + refused.Refusal.Should().Be(IdentityRebindRefusal.LiveSessions); + seen = refused.LiveSessions; + } + + seen.Should().Be(1, "the count is reported, never a session's identity"); + realm.Reads.Should().Be(0, "the freeze is checked before the new realm is read"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + var retry = await proof.RunAsync(RebindProofSupport.Admit(), realm); + retry.Result.Should().Be(IdentityRebindResult.Applied, "a retry repeats the whole proof against the quiet database"); + } + + [Fact] + public async Task The_New_Realm_Must_Be_Readable_Name_Its_Own_Issuer_Publish_Keys_And_Be_Complete() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + + var cases = new (string Why, FixedRealm Realm, IdentityRebindRefusal Expected)[] + { + ("unreadable", FixedRealm.Failing(), IdentityRebindRefusal.NewRealmUnavailable), + ("another discovery issuer", FixedRealm.Reporting(proof.Subjects, "https://elsewhere.example.test/realms/learnstack"), IdentityRebindRefusal.NewRealmIssuerMismatch), + ("no signing keys", FixedRealm.Reporting(proof.Subjects, keys: 0), IdentityRebindRefusal.NewRealmIncomplete), + ("a partial enumeration", FixedRealm.Reporting(proof.Subjects, complete: false), IdentityRebindRefusal.NewRealmIncomplete), + }; + foreach (var (why, realm, expected) in cases) + { + var admission = RebindProofSupport.Admit(); + var outcome = await proof.RunAsync(admission, realm); + + outcome.Refusal.Should().Be(expected, why); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, why); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle(why).Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + } + + [Fact] + public async Task An_Active_User_The_New_Realm_Does_Not_Report_Refuses_And_Names_Only_Counts() + { + await using var proof = await Proof.CreateAsync(parent, active: 3); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects.Take(2))); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken); + outcome.Continuity!.MissingActive.Should().Be(1); + outcome.ToString().Should().NotContain(proof.Subjects[2], "a refusal reports counts and never identifiers"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("only the intent row: no change, no result"); + } + + [Fact] + public async Task A_Subject_That_Differs_In_Case_Or_By_Whitespace_Is_Not_The_Same_Subject() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var changed = new[] { proof.Subjects[0].ToUpperInvariant(), " " + proof.Subjects[0] }; + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(changed)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken, "the exact opaque sub is the identity"); + } + + [Fact] + public async Task A_Closed_Persons_Key_Reappearing_Refuses_And_An_Absent_One_Does_Not() + { + await using var proof = await Proof.CreateAsync(parent, active: 2); + await proof.CloseAsync(proof.Users[1], closed: true); + + var reappears = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + reappears.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken, "a closed person must not reappear"); + reappears.Continuity.Should().BeEquivalentTo(new IdentityRebindContinuityResult(1, 0, 1, 2, 0, 0, 1, 0)); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + var absent = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + absent.Result.Should().Be(IdentityRebindResult.Applied, "the tombstone's subject is simply not in the new realm"); + absent.Continuity!.StoredClosed.Should().Be(1); + } + + [Fact] + public async Task A_Closing_User_Retaining_Its_Subject_Is_Judged_By_Neither_Rule() + { + await using var proof = await Proof.CreateAsync(parent, active: 2); + await proof.CloseAsync(proof.Users[1], closed: false); + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + outcome.Continuity!.StoredClosing.Should().Be(1); + } + + [Fact] + public async Task A_Forced_Audit_Failure_Rolls_The_Issuer_Change_Back() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), configure: store => store.FailResult = true); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuditFailed); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, "the issuer change and its audit row commit together or not at all"); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task A_Run_Killed_Between_The_Intent_Row_And_The_Main_Transaction_Leaves_The_Intent_And_No_Change() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + using var cancellation = new CancellationTokenSource(); + var realm = new FixedRealm(async (_, token) => + { + await cancellation.CancelAsync(); + token.ThrowIfCancellationRequested(); + return null!; + }); + + var outcome = await proof.RunAsync(admission, realm, cancellation: cancellation.Token); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.Cancelled); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task A_Session_Killed_Before_Commit_Is_Reconciled_As_Not_Applied() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), configure: store => + store.AfterResult = async connection => + await parent.Postgres.ExecuteAsSuperuserAsync( + $"SELECT pg_terminate_backend({((NpgsqlConnection)connection).ProcessID})")); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.CommitFailed); + outcome.Result.Should().Be(IdentityRebindResult.Refused); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, "the transaction died with its connection"); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("no result row either").Which.Operation + .Should().Be("identity.authority.rebind_attempt"); + + var retry = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + retry.Result.Should().Be(IdentityRebindResult.Applied); + } + + [Fact] + public async Task A_Commit_Whose_Acknowledgement_Is_Lost_Is_Reconciled_By_Reading_The_Issuer() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await using var proxy = new CommitAckDroppingProxy(proof.RebindConnection); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), connection: proxy.Through(proof.RebindConnection)); + + proxy.Dropped.Should().BeTrue("the server received the COMMIT and its answer never arrived"); + outcome.Result.Should().Be(IdentityRebindResult.Applied, "the issuer read back is the target, so the commit applied"); + (await proof.IssuerAsync()).Should().Be(NewIssuer); + (await proof.AuditRowsAsync(admission)).Select(row => row.Operation).Should().Equal( + "identity.authority.rebind_attempt", "identity.authority.rebind"); + } + + [Fact] + public async Task Runs_Are_Counted_By_Outcome_And_The_Continuity_Counts_By_Class() + { + var outcomes = new System.Collections.Concurrent.ConcurrentBag(); + var classes = new System.Collections.Concurrent.ConcurrentDictionary(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == IdentityRebindMetrics.MeterName) l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + foreach (var tag in tags) + { + if (instrument.Name == IdentityRebindMetrics.RunCounterName && tag.Key == "outcome") outcomes.Add((string)tag.Value!); + if (instrument.Name == IdentityRebindMetrics.ContinuityCounterName && tag.Key == "class") + classes.AddOrUpdate((string)tag.Value!, value, (_, current) => current + value); + } + }); + listener.Start(); + await using var proof = await Proof.CreateAsync(parent, active: 2); + + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcomes.Should().Contain(["refused_continuity_broken", "applied", "already_applied"]); + classes.Should().ContainKey("missing_active").WhoseValue.Should().BeGreaterThanOrEqualTo(1); + classes.Should().ContainKey("active"); + } + + private sealed record AuditRow( + Guid Tenant, string Operation, string Outcome, Guid? Actor, string? Reason, string Entity, + JsonElement Operator, JsonElement Before, JsonElement After, JsonElement Continuity, string Raw); + + private sealed record StoredUser(Guid Id, string KeyHex, string? Subject, string Status); + + private sealed class Proof : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + private readonly PublicReadFixture _parent; + + private Proof(PublicReadFixture parent, IdentityPublicReadFixture database, UserId[] users, string[] subjects) + { + _parent = parent; + _database = database; + Users = users; + Subjects = subjects; + } + + internal string[] Subjects { get; } + + internal UserId[] Users { get; } + + internal Guid Authority => _database.Registration.AuthorityId.Value; + + internal string OldIssuer => _database.Registration.Issuer; + + internal string RebindConnection => _database.IdentityRebindConnectionString; + + internal string OwnerConnection => _database.MigrationConnectionString; + + internal string Database => RebindProofSupport.DatabaseOf(RebindConnection); + + internal static async Task CreateAsync(PublicReadFixture parent, int active) + { + var users = Enumerable.Range(0, active).Select(_ => UserId.From(Guid.CreateVersion7())).ToArray(); + var subjects = users.Select(user => "rebind-proof-" + user.Value.ToString("N")).ToArray(); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", + users.Zip(subjects).ToDictionary(pair => pair.First, pair => pair.Second)); + return new Proof(parent, database, users, subjects); + } + + internal async Task RunAsync( + PlatformAdmission admission, + INewRealmContinuitySource realm, + string? connection = null, + IdentityAuthorityRegistration? target = null, + TimeSpan? lockWait = null, + Action? configure = null, + CancellationToken cancellation = default) + { + await using var scope = RebindProofSupport.Store(); + var store = new FaultingAuditStore(scope.ServiceProvider.GetRequiredService()); + configure?.Invoke(store); + return await new IdentityIssuerRebind(store, new SystemClock()).RunAsync( + connection ?? RebindConnection, + target ?? new IdentityAuthorityRegistration(_database.Registration.AuthorityId, NewIssuer), + admission, realm, lockWait, cancellation); + } + + internal async Task IssuerAsync() => await ReadAsync("SELECT issuer FROM public.identity_authority"); + + internal async Task AuthorityAsync() => await ReadAsync("SELECT authority_id FROM public.identity_authority"); + + private async Task ReadAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var command = new NpgsqlCommand(sql, connection); + return (T)(await command.ExecuteScalarAsync())!; + } + + internal async Task> UsersAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + await using var command = new NpgsqlCommand( + "SELECT id, encode(subject_key, 'hex'), provider_subject, status FROM public.users ORDER BY id", connection); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new StoredUser(reader.GetGuid(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), reader.GetString(3))); + } + + return rows; + } + + internal async Task> AuditRowsAsync(PlatformAdmission admission) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT tenant_id, operation, outcome, actor_user_id, reason, entity_id, metadata::text, + COALESCE(before_state::text, 'null'), COALESCE(after_state::text, 'null') + FROM public.audit_log WHERE correlation_id = @correlation ORDER BY timestamp, operation + """, connection); + command.Parameters.AddWithValue("correlation", admission.Operator.CorrelationId!); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + var metadata = JsonDocument.Parse(reader.GetString(6)).RootElement.Clone(); + rows.Add(new AuditRow(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? null : reader.GetString(4), + reader.GetString(5), metadata.GetProperty("operator"), + JsonDocument.Parse(reader.GetString(7)).RootElement.Clone(), + JsonDocument.Parse(reader.GetString(8)).RootElement.Clone(), + metadata.TryGetProperty("continuity", out var continuity) ? continuity : default, + reader.GetString(6) + reader.GetString(7) + reader.GetString(8))); + } + + return rows; + } + + /// A competing rebind: the exclusive lock held by a rebind-role transaction. + internal async Task HoldRebindLockAsync() + { + var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(RebindConnection); + var transaction = await connection.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + return new Held(connection, transaction); + } + + internal async Task OpenSessionAsync(string role) + { + var template = role switch + { + "learnstack_app" => _database.AppConnectionString, + "learnstack_outbox_admin" => _database.OutboxConnectionString, + "learnstack_platform" => _database.PlatformConnectionString, + _ => RebindProofSupport.In(IngressConnection, Database), + }; + // Unpooled: a disposed pooled connection stays a live session of its role, which is what the freeze sees. + return new Session(await PostgresFixture.OpenAsync( + new NpgsqlConnectionStringBuilder(template) { Pooling = false }.ConnectionString)); + } + + private string IngressConnection => _parent.Postgres.IdentityIngressConnectionString; + + /// The fixture's one corruption: a user closed (or closing) the way closure will, then the controls restored. + internal async Task CloseAsync(UserId user, bool closed) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + var status = closed ? "Closed" : "Closing"; + var subject = closed ? ", provider_subject=NULL" : string.Empty; + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{user.Value:D}'::uuid AND status='{status}' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='{status}'{subject} WHERE id='{user.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + public ValueTask DisposeAsync() => _database.DisposeAsync(); + + private sealed class Held(NpgsqlConnection connection, NpgsqlTransaction transaction) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await transaction.RollbackAsync(); + await transaction.DisposeAsync(); + await connection.DisposeAsync(); + } + } + + private sealed class Session(DbConnection connection) : IAsyncDisposable + { + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs new file mode 100644 index 00000000..3b780f69 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs @@ -0,0 +1,325 @@ +using System.Diagnostics; +using System.Reflection; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The offline tool as an operator runs it (ADR-0104 § 3): a child process, every value from its environment and one +/// line of standard input, a real operator issuer, a real database and a loopback new realm. +/// +/// +/// What an operator sees is one fixed line of classes and counts, so every case also asserts that no credential, +/// token, issuer, authority or subject reached the output, and that a refusal left the issuer where it was. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindToolTests(PublicReadFixture parent) +{ + private const string OperatorSubject = "operator-sub-9"; + private const string Grant = "platform.identity_authority.admin"; + + [Fact] + public async Task The_Tool_Rebinds_With_A_Token_On_Standard_Input_And_Prints_One_Line_Without_Identifiers() + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: true); + + result.Code.Should().Be(0, result.Text); + result.Out.Should().StartWith("rebind: outcome=applied correlation=rebind-") + .And.Contain("active=2").And.Contain("unbootstrapped=0"); + result.Out.Trim().Split('\n').Should().ContainSingle("one fixed line"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.NewIssuer); + + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal( + "identity.authority.rebind_attempt", "identity.authority.rebind"); + } + + [Fact] + public async Task The_Tool_Rebinds_With_A_Token_In_The_Environment_And_A_Repeat_Is_Already_Applied() + { + await using var run = await Run.StartAsync(parent); + + (await run.ExecuteAsync(token: run.Token(), tokenOnInput: false)).Code.Should().Be(0); + var repeat = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + repeat.Code.Should().Be(0); + repeat.Out.Should().StartWith("rebind: outcome=already_applied"); + } + + [Theory] + [InlineData("no-token", "refused_input")] + [InlineData("argument", "refused_input")] + [InlineData("no-realm-credential", "refused_input")] + [InlineData("no-mode", "refused_input")] + [InlineData("wrong-audience", "refused_operator_token_token_audience")] + [InlineData("wrong-issuer", "refused_operator_token_token_issuer")] + [InlineData("expired", "refused_operator_token_token_expired")] + [InlineData("stale-authentication", "refused_operator_token_profile_auth_age")] + [InlineData("single-factor", "refused_operator_token_profile_acr")] + [InlineData("other-client", "refused_operator_token_profile_azp")] + [InlineData("no-grant", "refused_operator_missing_permission")] + [InlineData("another-grant", "refused_operator_missing_permission")] + [InlineData("no-operator-issuer", "refused_operator_issuer_not_configured")] + public async Task A_Refusal_Before_The_Database_Leaves_The_Issuer_And_Writes_No_Row(string scenario, string expected) + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(scenario); + + result.Code.Should().Be(2); + (result.Out + result.Error).Should().Contain(expected); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + (await run.RebindRowsAsync()).Should().Be(0, "a refusal at the gate is a counter and a log, never a durable row"); + } + + [Fact] + public async Task A_Database_Role_That_Is_Not_The_Rebind_Role_Is_Refused() + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, connection: run.AppConnection); + + result.Code.Should().Be(2); + (result.Out + result.Error).Should().Contain("refused_input", "the connection string is not the rebind role's"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + [Fact] + public async Task A_New_Realm_Missing_An_Active_User_Refuses_With_Counts_And_Keeps_The_Intent_Row() + { + await using var run = await Run.StartAsync(parent, reportedUsers: 1); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_continuity_broken").And.Contain("missing_active=1"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task A_Rebind_Role_Session_Beside_A_Live_Application_Session_Is_Frozen_With_A_Count() + { + await using var run = await Run.StartAsync(parent); + await using var application = (NpgsqlConnection)await PostgresFixture.OpenAsync(run.AppConnection); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_live_sessions").And.Contain("sessions=1"); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + private sealed record Result(int Code, string Out, string Error) + { + internal string Text => Out + Error; + } + + private sealed class Run : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + private readonly TenantAuthenticationIssuer _operator; + private readonly FakeKeycloakRealm _realm; + private readonly string[] _subjects; + + private Run(IdentityPublicReadFixture database, TenantAuthenticationIssuer @operator, FakeKeycloakRealm realm, string[] subjects) + { + _database = database; + _operator = @operator; + _realm = realm; + _subjects = subjects; + } + + internal string OldIssuer => _database.Registration.Issuer; + + internal string NewIssuer => _realm.Issuer; + + internal string AppConnection => _database.AppConnectionString; + + internal static async Task StartAsync(PublicReadFixture parent, int reportedUsers = 2) + { + var users = new[] { UserId.From(Guid.CreateVersion7()), UserId.From(Guid.CreateVersion7()) }; + var subjects = users.Select(user => "tool-proof-" + user.Value.ToString("N")).ToArray(); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", users.Zip(subjects).ToDictionary(pair => pair.First, pair => pair.Second)); + var @operator = await TenantAuthenticationIssuer.StartAsync(); + var realm = await FakeKeycloakRealm.StartAsync(subjects.Take(reportedUsers)); + return new Run(database, @operator, realm, subjects); + } + + internal string Token(params (string Name, object? Value)[] replacements) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = _operator.Issuer, + ["sub"] = OperatorSubject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) claims[name] = value; + return _operator.Token(JsonSerializer.Serialize(claims)); + } + + internal Task ExecuteAsync(string scenario) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + return scenario switch + { + "no-token" => ExecuteAsync(token: null, tokenOnInput: false), + "argument" => ExecuteAsync(token: Token(), tokenOnInput: false, argument: "--force"), + "no-realm-credential" => ExecuteAsync(token: Token(), tokenOnInput: false, realmCredential: false), + "no-mode" => ExecuteAsync(token: Token(), tokenOnInput: false, mode: null), + "wrong-audience" => ExecuteAsync(token: Token(("aud", "learnstack-api")), tokenOnInput: false), + "wrong-issuer" => ExecuteAsync(token: Token(("iss", "https://elsewhere.example.test/realms/x")), tokenOnInput: false), + "expired" => ExecuteAsync(token: Token(("exp", now - 3600), ("iat", now - 3700), ("auth_time", now - 3700)), tokenOnInput: false), + "stale-authentication" => ExecuteAsync(token: Token(("auth_time", now - 7200)), tokenOnInput: false), + "single-factor" => ExecuteAsync(token: Token(("acr", "pwd")), tokenOnInput: false), + "other-client" => ExecuteAsync(token: Token(("azp", "learnstack-web")), tokenOnInput: false), + "no-grant" => ExecuteAsync(token: Token(), tokenOnInput: false, grant: null), + "another-grant" => ExecuteAsync(token: Token(), tokenOnInput: false, grant: "platform.killswitch.write"), + "no-operator-issuer" => ExecuteAsync(token: Token(), tokenOnInput: false, operatorIssuer: false), + _ => throw new ArgumentOutOfRangeException(nameof(scenario)), + }; + } + + internal async Task ExecuteAsync( + string? token, bool tokenOnInput, string? argument = null, bool realmCredential = true, string? mode = "Development", + string? grant = Grant, bool operatorIssuer = true, string? connection = null) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = AppContext.BaseDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + UseShellExecute = false, + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.deps.json")); + start.ArgumentList.Add(Assembly.Load("LearnStack.Tools.IdentityAuthorityRebind").Location); + if (argument is not null) start.ArgumentList.Add(argument); + start.Environment.Clear(); + foreach (var key in new[] { "PATH", "SystemRoot", "DOTNET_ROOT", "HOME" }) + if (Environment.GetEnvironmentVariable(key) is { } value) start.Environment[key] = value; + start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + start.Environment["ConnectionStrings__IdentityRebind"] = connection ?? _database.IdentityRebindConnectionString; + start.Environment["Identity__AuthorityId"] = _database.Registration.AuthorityId.Value.ToString("D"); + start.Environment["Authentication__Tenant__Issuer"] = _realm.Issuer; + if (mode is not null) start.Environment["Deployment__Mode"] = mode; + if (operatorIssuer) + { + start.Environment["PlatformOperator__Issuer"] = _operator.Issuer; + start.Environment["PlatformOperator__AuthorizedParties__0"] = "learnstack-operator"; + start.Environment["PlatformOperator__AcceptedAcr__0"] = "mfa"; + if (grant is not null) + { + start.Environment["PlatformOperator__Grants__0__Subject"] = OperatorSubject; + start.Environment["PlatformOperator__Grants__0__Permissions__0"] = grant; + } + } + + if (realmCredential) + { + start.Environment["LEARNSTACK_REBIND_REALM_CLIENT_ID"] = FakeKeycloakRealm.ClientId; + start.Environment["LEARNSTACK_REBIND_REALM_CLIENT_SECRET"] = FakeKeycloakRealm.ClientSecret; + } + + start.Environment["LEARNSTACK_REBIND_TICKET"] = "CHG-104"; + if (token is not null && !tokenOnInput) start.Environment["LEARNSTACK_OPERATOR_TOKEN"] = token; + _token = token; + + using var child = new Process { StartInfo = start }; + child.Start().Should().BeTrue(); + var output = child.StandardOutput.ReadToEndAsync(); + var errors = child.StandardError.ReadToEndAsync(); + if (token is not null && tokenOnInput) await child.StandardInput.WriteLineAsync(token); + child.StandardInput.Close(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(90)); + try { await child.WaitForExitAsync(deadline.Token); } + finally + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + await child.WaitForExitAsync(CancellationToken.None); + } + } + + return new Result(child.ExitCode, await output, await errors); + } + + private string? _token; + + internal void AssertNoValueLeaked(Result result) + { + var forbidden = new List + { + FakeKeycloakRealm.ClientSecret, _database.IdentityRebindConnectionString, _database.AppConnectionString, + OldIssuer, NewIssuer, _operator.Issuer, _database.Registration.AuthorityId.Value.ToString("D"), OperatorSubject, + }; + forbidden.AddRange(_subjects); + if (_token is not null) forbidden.Add(_token); + foreach (var value in forbidden) + { + result.Text.Should().NotContain(value); + } + + result.Text.Length.Should().BeLessThan(1024); + } + + internal async Task IssuerAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var command = new NpgsqlCommand("SELECT issuer FROM public.identity_authority", connection); + return (string)(await command.ExecuteScalarAsync())!; + } + + internal async Task RebindRowsAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT count(*) FROM public.audit_log WHERE operation LIKE 'identity.authority.rebind%'", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + internal async Task> OperationsAsync(string correlation) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT operation FROM public.audit_log WHERE correlation_id = @c ORDER BY timestamp", connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) rows.Add(reader.GetString(0)); + return rows; + } + + public async ValueTask DisposeAsync() + { + await _realm.DisposeAsync(); + await _operator.DisposeAsync(); + await _database.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs index e1142452..a07b8a52 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs @@ -26,7 +26,7 @@ public sealed class IdentityRebindAuditStoreTests(PublicReadFixture parent) [Fact] public async Task The_Intent_And_The_Result_Rows_Are_Written_Bound_To_The_Admission_And_Carry_The_Ticket() { - await using var scope = Store(); + await using var scope = RebindProofSupport.Store(); var audit = scope.ServiceProvider.GetRequiredService(); var admission = Admit(ticket: "CHG-104"); var authority = Guid.CreateVersion7(); @@ -59,7 +59,7 @@ public async Task The_Intent_And_The_Result_Rows_Are_Written_Bound_To_The_Admiss [Fact] public async Task The_Result_Row_Commits_With_The_Transaction_Or_Not_At_All() { - await using var scope = Store(); + await using var scope = RebindProofSupport.Store(); var audit = scope.ServiceProvider.GetRequiredService(); var admission = Admit(); @@ -76,7 +76,7 @@ public async Task The_Result_Row_Commits_With_The_Transaction_Or_Not_At_All() [Fact] public async Task A_Row_That_Differs_From_Its_Admission_Or_Its_Declaration_Is_Refused_Before_The_Database() { - await using var scope = Store(); + await using var scope = RebindProofSupport.Store(); var audit = scope.ServiceProvider.GetRequiredService(); var admission = Admit(ticket: "CHG-104"); var authority = Guid.CreateVersion7(); @@ -136,7 +136,7 @@ public async Task A_Row_That_Differs_From_Its_Admission_Or_Its_Declaration_Is_Re [Fact] public async Task A_Database_Refusal_Is_An_Audit_Write_Failure_So_The_Rebind_Cannot_Commit() { - await using var scope = Store(); + await using var scope = RebindProofSupport.Store(); var audit = scope.ServiceProvider.GetRequiredService(); var admission = Admit(); @@ -213,22 +213,6 @@ private static AuditEntryDraft Result(PlatformAdmission admission, Guid authorit Metadata = "{\"operator\":" + PlatformOperatorAttribution.From(admission).ToOperatorJson(admission.Ticket) + "}", }; - private AsyncServiceScope Store() => - new ServiceCollection() - .AddMetrics() - .AddLogging() - .AddScoped() - .AddSingleton() - .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) - .AddSingleton(StaticTenantContextAccessor.Unresolved) - .AddScoped() - .AddSingleton(new Lazy( - () => throw new InvalidOperationException("The rebind rows are written on the caller's own connection."))) - .AddScoped() - .BuildServiceProvider() - .GetRequiredService() - .CreateAsyncScope(); - private sealed record Row(Guid Tenant, string Operation, string Outcome, Guid? Actor, string? Reason, string Module, string Entity, string Metadata); private async Task> ReadAsync(string correlationId) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs new file mode 100644 index 00000000..af64039d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs @@ -0,0 +1,224 @@ +using System.Data.Common; +using System.Net; +using System.Net.Sockets; +using System.Text; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; + +namespace LearnStack.Tests.Integration.Database; + +/// The pieces the controlled-rebind proofs share: the real audit store, admissions and fault injection. +internal static class RebindProofSupport +{ + internal static PlatformAdmission Admit(string? ticket = "CHG-104", DateTimeOffset? issuedAt = null) => + TestPlatformAdmissions.Admission( + PlatformOperations.IdentityAuthorityRebind, ticket, + correlationId: "00-rebind-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt); + + /// The real store over the real Identity catalogue; rows go through the connection the caller passes. + internal static AsyncServiceScope Store() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The rebind rows are written on the caller's own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService() + .CreateAsyncScope(); + + internal static string DatabaseOf(string connectionString) => new NpgsqlConnectionStringBuilder(connectionString).Database!; + + internal static string In(string connectionString, string database) => + new NpgsqlConnectionStringBuilder(connectionString) { Database = database }.ConnectionString; +} + +/// A new realm that reports what the test says, or fails the way the test says. +internal sealed class FixedRealm(Func> read) : INewRealmContinuitySource +{ + internal int Reads { get; private set; } + + public Task ReadAsync(string issuer, CancellationToken cancellationToken = default) + { + Reads++; + return read(issuer, cancellationToken); + } + + internal static FixedRealm Reporting(IEnumerable subjects, string? discoveredIssuer = null, + int keys = 2, bool complete = true) => + new((issuer, _) => Task.FromResult(new NewRealmSnapshot(discoveredIssuer ?? issuer, keys, complete, subjects.ToArray()))); + + internal static FixedRealm Failing() => + new((_, _) => throw new NewRealmUnavailableException()); +} + +/// The real store, with seams at the two points a crash or an outage would strike. +internal sealed class FaultingAuditStore(IAuditStore inner) : IAuditStore +{ + internal Func? AfterIntent { get; set; } + internal Func? AfterResult { get; set; } + internal bool FailResult { get; set; } + + public async Task WriteIdentityRebindIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) + { + await inner.WriteIdentityRebindIntentAsync(entry, admission, connection, transaction, cancellationToken); + if (AfterIntent is not null) await AfterIntent(connection); + } + + public async Task WriteIdentityRebindResultAsync(AuditEntryDraft entry, PlatformAdmission admission, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) + { + if (FailResult) throw new AuditWriteFailedException("forced result failure"); + await inner.WriteIdentityRebindResultAsync(entry, admission, connection, transaction, cancellationToken); + if (AfterResult is not null) await AfterResult(connection); + } + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePlatformScopeAsync(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => throw new NotSupportedException(); +} + +/// +/// A loopback TCP relay in front of PostgreSQL that lets the first COMMIT that follows the issuer UPDATE reach the +/// server and then drops the answer and the connection, which is exactly the commit whose outcome the client cannot +/// know. +/// +internal sealed class CommitAckDroppingProxy : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly string _host; + private readonly int _port; + private readonly CancellationTokenSource _stop = new(); + private readonly List _pumps = []; + private int _dropped; + + internal CommitAckDroppingProxy(string upstreamConnectionString) + { + var upstream = new NpgsqlConnectionStringBuilder(upstreamConnectionString); + _host = upstream.Host!; + _port = upstream.Port; + _listener.Start(); + _pumps.Add(Task.Run(AcceptAsync)); + } + + internal int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + internal bool Dropped => Volatile.Read(ref _dropped) > 0; + + internal string Through(string connectionString) => new NpgsqlConnectionStringBuilder(connectionString) + { + Host = "127.0.0.1", + Port = Port, + SslMode = SslMode.Disable, + }.ConnectionString; + + private async Task AcceptAsync() + { + try + { + while (!_stop.IsCancellationRequested) + { + var client = await _listener.AcceptTcpClientAsync(_stop.Token); + lock (_pumps) _pumps.Add(Task.Run(() => RelayAsync(client))); + } + } + catch (OperationCanceledException) { } + catch (ObjectDisposedException) { } + } + + private async Task RelayAsync(TcpClient client) + { + using var clientSide = client; + using var upstream = new TcpClient(); + try + { + await upstream.ConnectAsync(_host, _port, _stop.Token); + var armed = false; + var dropAnswer = false; + var toServer = Task.Run(async () => + { + var buffer = new byte[16 * 1024]; + var fromClient = clientSide.GetStream(); + var toUpstream = upstream.GetStream(); + int read; + while ((read = await fromClient.ReadAsync(buffer, _stop.Token)) > 0) + { + var text = Encoding.ASCII.GetString(buffer, 0, read); + armed |= text.Contains("SET issuer", StringComparison.Ordinal); + if (armed && buffer[0] == (byte)'Q' && text.Contains("COMMIT", StringComparison.Ordinal)) + { + // The server will get this COMMIT; whatever it answers is discarded and the connection cut. + Volatile.Write(ref dropAnswer, true); + } + + await toUpstream.WriteAsync(buffer.AsMemory(0, read), _stop.Token); + } + }, _stop.Token); + var toClient = Task.Run(async () => + { + var buffer = new byte[16 * 1024]; + var fromUpstream = upstream.GetStream(); + var toClientStream = clientSide.GetStream(); + int read; + while ((read = await fromUpstream.ReadAsync(buffer, _stop.Token)) > 0) + { + if (Volatile.Read(ref dropAnswer)) + { + Interlocked.Increment(ref _dropped); + clientSide.Close(); + upstream.Close(); + return; + } + + await toClientStream.WriteAsync(buffer.AsMemory(0, read), _stop.Token); + } + }, _stop.Token); + await Task.WhenAny(toServer, toClient); + } + catch (Exception failure) when (failure is IOException or SocketException or OperationCanceledException or ObjectDisposedException or InvalidOperationException) { } + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + Task[] pumps; + lock (_pumps) pumps = [.. _pumps]; + try { await Task.WhenAll(pumps); } catch (Exception failure) when (failure is OperationCanceledException or IOException or ObjectDisposedException) { } + _stop.Dispose(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs new file mode 100644 index 00000000..0b0b114c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -0,0 +1,161 @@ +using System.Net; +using System.Text.Json; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Tests.Integration; + +/// A loopback realm that answers like Keycloak's discovery, key set, token and administration endpoints. +internal sealed class FakeKeycloakRealm : IAsyncDisposable +{ + internal const string ClientId = "rebind-reader"; + internal const string ClientSecret = "reader-secret-value"; + + private readonly WebApplication _app; + private readonly HttpClient _client; + private string? _failure; + private int _pages; + + private FakeKeycloakRealm(WebApplication app, List users) + { + _app = app; + Users = users; + _client = KeycloakRealmContinuitySource.CreateClient(); + } + + internal List Users { get; } + + internal string Issuer { get; private set; } = ""; + + internal string? DiscoveryIssuer { get; set; } + + internal int? ReportedCount { get; set; } + + internal int? CountAfterRead { get; set; } + + internal int Pages => Volatile.Read(ref _pages); + + internal List> TokenRequests { get; } = []; + + internal List AdminAuthorization { get; } = []; + + internal static Task StartAsync(int users) => + StartAsync(Enumerable.Range(0, users).Select(_ => Guid.NewGuid().ToString("D"))); + + internal static async Task StartAsync(IEnumerable users) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseKestrel(options => options.Listen(IPAddress.Loopback, 0)); + var app = builder.Build(); + var realm = new FakeKeycloakRealm(app, users.ToList()); + realm.Map(app); + await app.StartAsync(); + var origin = app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); + realm.Issuer = origin + "/realms/learnstack"; + return realm; + } + + internal void Fail(string failure) => _failure = failure; + + internal Task ReadAsync() => + new KeycloakRealmContinuitySource(_client, ClientId, ClientSecret).ReadAsync(Issuer); + + private void Map(WebApplication app) + { + app.MapGet("/realms/learnstack/.well-known/openid-configuration", context => + { + if (_failure == "discovery-redirect") + { + context.Response.StatusCode = StatusCodes.Status302Found; + context.Response.Headers.Location = "https://elsewhere.example.test/"; + return Task.CompletedTask; + } + + var jwks = _failure == "jwks-other-origin" ? "http://127.0.0.1:1/keys" : Issuer + "/keys"; + var token = _failure == "token-other-origin" ? "http://127.0.0.1:1/token" : Issuer + "/protocol/openid-connect/token"; + context.Response.ContentType = "application/json"; + return context.Response.WriteAsync(JsonSerializer.Serialize(new + { + issuer = DiscoveryIssuer ?? Issuer, + jwks_uri = jwks, + token_endpoint = token, + })); + }); + app.MapGet("/realms/learnstack/keys", context => + { + context.Response.ContentType = "application/json"; + return context.Response.WriteAsync( + """{"keys":[{"kty":"RSA","kid":"a","use":"sig"},{"kty":"RSA","kid":"b"},{"kty":"RSA","kid":"c","use":"enc"}]}"""); + }); + app.MapPost("/realms/learnstack/protocol/openid-connect/token", async context => + { + var form = await context.Request.ReadFormAsync(); + TokenRequests.Add(form.ToDictionary(pair => pair.Key, pair => pair.Value.ToString())); + if (_failure == "token-denied") + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return; + } + + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(_failure == "oversized-token-answer" + ? "{\"access_token\":\"" + new string('x', 300 * 1024) + "\"}" + : """{"access_token":"realm-token"}"""); + }); + app.MapGet("/admin/realms/learnstack/users/count", context => + { + AdminAuthorization.Add(context.Request.Headers.Authorization); + if (_failure == "admin-denied") + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + return Task.CompletedTask; + } + + if (_failure == "count-not-a-number") + { + return context.Response.WriteAsync("\"many\""); + } + + var count = Pages > 0 && CountAfterRead is { } later ? later : ReportedCount ?? Users.Count; + return context.Response.WriteAsync(count.ToString(System.Globalization.CultureInfo.InvariantCulture)); + }); + app.MapGet("/admin/realms/learnstack/users", context => + { + AdminAuthorization.Add(context.Request.Headers.Authorization); + Interlocked.Increment(ref _pages); + if (_failure == "users-redirect") + { + context.Response.StatusCode = StatusCodes.Status302Found; + context.Response.Headers.Location = "https://elsewhere.example.test/"; + return Task.CompletedTask; + } + + context.Response.ContentType = "application/json"; + if (_failure == "users-not-an-array") + { + return context.Response.WriteAsync("{}"); + } + + var first = int.Parse(context.Request.Query["first"]!, System.Globalization.CultureInfo.InvariantCulture); + var max = int.Parse(context.Request.Query["max"]!, System.Globalization.CultureInfo.InvariantCulture); + var page = Users.Skip(first).Take(max).Select(id => _failure == "user-without-id" + ? (object)new { username = id } + : new { id, username = "user-" + id }); + return context.Response.WriteAsync(JsonSerializer.Serialize(page)); + }); + } + + public async ValueTask DisposeAsync() + { + _client.Dispose(); + await _app.DisposeAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs new file mode 100644 index 00000000..b3bd1af2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs @@ -0,0 +1,124 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The tool's reader of the new realm (ADR-0104 § 4, § 6) against a loopback realm that behaves like Keycloak's +/// administration API: bounded, same-origin, paged, and complete or refused. +/// +/// +/// A real Keycloak answers the same questions in ; here the +/// failure modes a real one cannot be made to produce are driven on purpose. +/// +public sealed class KeycloakRealmContinuitySourceTests +{ + private const string ClientId = FakeKeycloakRealm.ClientId; + private const string ClientSecret = FakeKeycloakRealm.ClientSecret; + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(99)] + [InlineData(100)] + [InlineData(101)] + [InlineData(250)] + public async Task Every_User_Of_Every_Page_Is_Reported_And_The_Snapshot_Is_Complete(int users) + { + await using var realm = await FakeKeycloakRealm.StartAsync(users); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + snapshot.DiscoveredIssuer.Should().Be(realm.Issuer); + snapshot.SigningKeyCount.Should().Be(2, "only signature keys count, an encryption key does not"); + snapshot.Subjects.Should().BeEquivalentTo(realm.Users); + realm.Pages.Should().Be(users / KeycloakRealmContinuitySource.PageSize + 1, + "a page shorter than the page size ends the enumeration, and an exact multiple needs one empty page"); + } + + [Fact] + public async Task The_Realm_Credential_Is_Sent_Only_As_A_Client_Credentials_Grant_And_The_Token_Only_As_A_Bearer() + { + await using var realm = await FakeKeycloakRealm.StartAsync(3); + + await realm.ReadAsync(); + + realm.TokenRequests.Should().ContainSingle().Which.Should().BeEquivalentTo(new Dictionary + { + ["grant_type"] = "client_credentials", + ["client_id"] = ClientId, + ["client_secret"] = ClientSecret, + }); + realm.AdminAuthorization.Should().OnlyContain(header => header == "Bearer realm-token"); + } + + [Fact] + public async Task A_Realm_That_Changes_While_It_Is_Read_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.CountAfterRead = 6; + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeFalse("the count before and after the pages differ"); + } + + [Fact] + public async Task A_Reported_Count_That_The_Pages_Do_Not_Add_Up_To_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.ReportedCount = 7; + + (await realm.ReadAsync()).Complete.Should().BeFalse(); + } + + [Fact] + public async Task A_Discovery_Issuer_That_Differs_Is_Reported_As_It_Is_For_The_Proof_To_Refuse() + { + await using var realm = await FakeKeycloakRealm.StartAsync(1); + realm.DiscoveryIssuer = "https://elsewhere.example.test/realms/learnstack"; + + (await realm.ReadAsync()).DiscoveredIssuer.Should().Be("https://elsewhere.example.test/realms/learnstack"); + } + + [Theory] + [InlineData("jwks-other-origin")] + [InlineData("token-other-origin")] + [InlineData("token-denied")] + [InlineData("admin-denied")] + [InlineData("users-redirect")] + [InlineData("discovery-redirect")] + [InlineData("users-not-an-array")] + [InlineData("user-without-id")] + [InlineData("count-not-a-number")] + [InlineData("oversized-token-answer")] + public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names_Nothing(string failure) + { + await using var realm = await FakeKeycloakRealm.StartAsync(3); + realm.Fail(failure); + + var act = async () => await realm.ReadAsync(); + + var thrown = (await act.Should().ThrowAsync()).Which; + thrown.Message.Should().Be("The new realm could not be read completely."); + thrown.Message.Should().NotContain(ClientSecret).And.NotContain("127.0.0.1").And.NotContain("realm-token"); + thrown.InnerException.Should().BeNull("no transport exception is carried out"); + } + + [Fact] + public async Task A_Credential_Replacing_The_Certificate_Check_Is_Refused() + { + var handler = new SocketsHttpHandler(); +#pragma warning disable CA5359 // The case proves that a replaced certificate check is refused; it is never used. + handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; +#pragma warning restore CA5359 + + var act = () => KeycloakRealmContinuitySource.CreateClient(handler); + + act.Should().Throw(); + await Task.CompletedTask; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj index ad5ae13a..dd58d635 100644 --- a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj +++ b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj @@ -19,6 +19,7 @@ to be asserted against the real schema rather than taken on trust. --> + +/// The offline caller of the operator validator (ADR-0104 § 3) against a real loopback issuer: the same +/// cryptographic parameters, bounded metadata manager and closed profile the API scheme applies. +/// +/// +/// proves the same refusals through the HTTP scheme; here they are proved for +/// the second caller, so the two cannot drift. A refusal is one closed label and never a value the token carried. +/// +[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", + Justification = "xUnit disposes the fields through IAsyncLifetime.DisposeAsync.")] +public sealed class PlatformOperatorTokenValidatorTests : IAsyncLifetime +{ + private const string Subject = "operator-sub-7"; + private const string Correlation = "00-rebind-tool-01"; + + private TenantAuthenticationIssuer _issuer = null!; + private PlatformOperatorBackchannel _backchannel = null!; + private PlatformOperatorTokenValidator _validator = null!; + + public async Task InitializeAsync() + { + _issuer = await TenantAuthenticationIssuer.StartAsync(); + _backchannel = new PlatformOperatorBackchannel(); + _validator = ValidatorFor(_issuer); + } + + public async Task DisposeAsync() + { + _backchannel.Dispose(); + await _issuer.DisposeAsync(); + } + + [Fact] + public async Task A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Tool_Executor() + { + var result = await Validate(Sign()); + + result.IsValid.Should().BeTrue(); + result.Cause.Should().BeNull(); + var witness = result.Witness!; + witness.Issuer.Should().Be(_issuer.Issuer); + witness.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_issuer.Issuer, Subject)); + witness.Acr.Should().Be("mfa"); + witness.Executor.Should().Be(PlatformOperatorSettings.RebindToolExecutor); + witness.CorrelationId.Should().Be(Correlation); + } + + [Theory] + [InlineData(null, "token_missing")] + [InlineData("", "token_missing")] + [InlineData(" ", "token_missing")] + [InlineData("not-a-token", "token_invalid")] + [InlineData("a.b.c", "token_invalid")] + public async Task A_Missing_Or_Malformed_Token_Is_Refused_With_One_Closed_Label(string? token, string cause) + { + var result = await _validator.ValidateAsync(token, PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + result.Cause.Should().Be(cause); + } + + [Fact] + public async Task A_Token_Over_The_Length_Bound_Is_Refused_Without_Being_Parsed() + { + var result = await _validator.ValidateAsync( + new string('a', PlatformOperatorTokenValidator.MaximumTokenCharacters + 1), + PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.Cause.Should().Be("token_invalid"); + } + + [Fact] + public async Task Each_Cryptographic_Failure_Has_Its_Own_Closed_Label() + { + (await Validate(Sign(("aud", "learnstack-api")))).Cause.Should().Be("token_audience", "the wrong audience"); + (await Validate(Sign(("iss", "https://elsewhere.example.test/realms/x")))).Cause.Should().Be("token_issuer", "another issuer"); + (await Validate(Sign(("exp", DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeSeconds())))).Cause.Should().Be("token_expired", "an expired token"); + (await Validate(_issuer.Token(Payload([]), key: _issuer.NewKey()))).Cause.Should().Be("token_signature", "a key the issuer never published"); + (await Validate(_issuer.Token(Payload([]), header: Header("at+jwt")))).Cause.Should().Be("token_type", "another token type"); + } + + [Fact] + public async Task Each_Profile_Failure_Has_Its_Own_Closed_Label() + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + (await Validate(Sign(("azp", "learnstack-web")))).Cause.Should().Be("profile_azp", "a client the profile does not allow"); + (await Validate(Sign(("acr", "pwd")))).Cause.Should().Be("profile_acr", "an assurance the profile does not accept"); + (await Validate(SignWithout("acr"))).Cause.Should().Be("profile_acr", "no assurance claim"); + (await Validate(SignWithout("auth_time"))).Cause.Should().Be("profile_auth_time", "no authentication time"); + (await Validate(Sign(("auth_time", now - 7200)))).Cause.Should().Be("profile_auth_age", "an authentication older than the configured age"); + (await Validate(Sign(("exp", now + 7200)))).Cause.Should().Be("profile_lifetime", "a lifetime above fifteen minutes"); + (await Validate(Sign(("sub", "")))).Cause.Should().Be("profile_subject", "a blank subject"); + } + + [Fact] + public async Task An_Unreachable_Issuer_Refuses_The_Operator_Rather_Than_Trusting_A_Key_It_Never_Read() + { + await using var down = await TenantAuthenticationIssuer.StartAsync(); + down.DiscoveryStatusCode = 500; + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(down, backchannel); + + var result = await validator.ValidateAsync( + down.Token(Payload([], down)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + result.Cause.Should().Be("metadata_unavailable"); + } + + [Fact] + public async Task A_Discovery_Document_That_Names_Another_Issuer_Is_Refused() + { + await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( + misbehaving.Issuer, "https://elsewhere.example.test/realms/x", StringComparison.Ordinal); + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(misbehaving, backchannel); + + var result = await validator.ValidateAsync( + misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse("a discovery issuer other than the pinned one is never trusted"); + } + + [Fact] + public async Task A_Key_Set_At_Another_Origin_Is_Refused() + { + await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( + misbehaving.Issuer + "/keys", "http://127.0.0.1:1/keys", StringComparison.Ordinal); + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(misbehaving, backchannel); + + var result = await validator.ValidateAsync( + misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + } + + [Fact] + public void The_Tenant_Issuer_Key_The_Settings_Refuse_Is_The_Key_The_Tenant_Scheme_Reads() + { + PlatformOperatorSettings.TenantIssuerConfigurationKey.Should().Be( + LearnStack.Api.Authentication.TenantAuthenticationOptions.IssuerConfigurationKey); + } + + private Task Validate(string token) => + _validator.ValidateAsync(token, PlatformOperatorSettings.RebindToolExecutor, Correlation); + + private PlatformOperatorTokenValidator ValidatorFor(TenantAuthenticationIssuer issuer, PlatformOperatorBackchannel? backchannel = null) + { + var settings = PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["PlatformOperator:Issuer"] = issuer.Issuer, + ["PlatformOperator:AuthorizedParties:0"] = "learnstack-operator", + ["PlatformOperator:AcceptedAcr:0"] = "mfa", + }).Build(), + DeploymentMode.Development)!; + var health = new PlatformOperatorMetadataHealth(new SystemClock()); + var manager = PlatformOperatorValidation.CreateConfigurationManager( + settings, backchannel ?? _backchannel, health, NullLogger.Instance); + return new PlatformOperatorTokenValidator(settings, manager, health, new SystemClock()); + } + + private string Sign(params (string Name, object? Value)[] replacements) => _issuer.Token(Payload(replacements)); + + private string SignWithout(string name) + { + using var baseline = JsonDocument.Parse(Payload([])); + return _issuer.Token("{" + string.Join(",", baseline.RootElement.EnumerateObject() + .Where(property => property.Name != name) + .Select(property => JsonSerializer.Serialize(property.Name) + ":" + property.Value.GetRawText())) + "}"); + } + + private string Payload((string Name, object? Value)[] replacements, TenantAuthenticationIssuer? issuer = null) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = (issuer ?? _issuer).Issuer, + ["sub"] = Subject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) + { + claims[name] = value; + } + + return JsonSerializer.Serialize(claims); + } + + private string Header(string type) => + JsonSerializer.Serialize(new { alg = "RS256", typ = type, kid = _issuer.CurrentKey.Kid }); +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs new file mode 100644 index 00000000..26b5b590 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs @@ -0,0 +1,137 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tests.Integration.Database; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.IdentityModel.JsonWebTokens; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// The tool's reader of the new realm against the pinned Keycloak (ADR-0104 § 6): its discovery issuer, its key set, +/// the user count, the paging past one page, and that a user's id is the sub its tokens carry. +/// +/// +/// drives the failure modes on purpose; this is the other half, the +/// shape and the arithmetic of the real administration API, which a fake only imitates. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class KeycloakEnumerationTests : IAsyncLifetime +{ + private const string ReaderClient = "rebind-view-users-reader"; + private const string ReaderSecret = "view-users-reader-secret-of-the-test"; + private const int ExtraUsers = 130; + + private KeycloakFixture _keycloak = null!; + + public async Task InitializeAsync() => _keycloak = await KeycloakFixture.StartAsync(); + + public async Task DisposeAsync() => await _keycloak.DisposeAsync(); + + [Fact] + public async Task The_Pinned_Realm_Is_Enumerated_Completely_Across_Pages_And_Its_Ids_Are_The_Token_Subjects() + { + using var admin = await _keycloak.CreateAdminClientAsync(); + var readerAccount = await CreateViewUsersReaderAsync(admin); + var created = await CreateUsersAsync(admin, ExtraUsers); + + using var client = KeycloakRealmContinuitySource.CreateClient(KeycloakHttp.CreateHandler(_keycloak.RootCertificate)); + var snapshot = await new KeycloakRealmContinuitySource(client, ReaderClient, ReaderSecret).ReadAsync(_keycloak.Issuer); + + snapshot.DiscoveredIssuer.Should().Be(_keycloak.Issuer, "the realm names its own issuer, which the proof requires to equal the target"); + snapshot.SigningKeyCount.Should().BeGreaterThan(0); + snapshot.Complete.Should().BeTrue("the pages add up to the count, and the count did not move while they were read"); + + // The independent read: every account the administration API lists in one request, by the test's own admin client. + var listed = await admin.GetAsync("users?first=0&max=1000&briefRepresentation=true"); + var expected = listed.EnumerateArray().Select(user => user.GetProperty("id").GetString()!).ToList(); + expected.Count.Should().BeGreaterThan(ExtraUsers, "the shipped realm's own users and the created ones"); + snapshot.Subjects.Should().BeEquivalentTo(expected); + snapshot.Subjects.Count.Should().BeGreaterThan(KeycloakRealmContinuitySource.PageSize, + "the enumeration crossed at least one page boundary"); + snapshot.Subjects.Should().Contain(created); + snapshot.Subjects.Should().NotContain(readerAccount, "a service account is not a person of the realm"); + + // The id is the sub: the service account's own token carries its user id as the subject. + var token = await AccessTokenAsync(client); + new JsonWebToken(token).Subject.Should().Be(readerAccount); + + // A credential without the role cannot read the realm: the administration API refuses it. + await CreateReaderClientAsync(admin, "rebind-no-role-reader", assignRole: false); + var refused = async () => await new KeycloakRealmContinuitySource(client, "rebind-no-role-reader", ReaderSecret) + .ReadAsync(_keycloak.Issuer); + await refused.Should().ThrowAsync(); + } + + /// The credential the runbook has the operator create: a confidential client with the one view-users role. + private static async Task CreateViewUsersReaderAsync(KeycloakAdminClient admin) => + await CreateReaderClientAsync(admin, ReaderClient, assignRole: true); + + private static async Task CreateReaderClientAsync(KeycloakAdminClient admin, string clientId, bool assignRole) + { + (await admin.PostAsync("clients", new + { + clientId, + protocol = "openid-connect", + publicClient = false, + serviceAccountsEnabled = true, + standardFlowEnabled = false, + directAccessGrantsEnabled = false, + secret = ReaderSecret, + })).Should().Be(HttpStatusCode.Created); + + var client = await admin.ClientAsync(clientId); + var account = (await admin.GetAsync("clients/" + client.GetProperty("id").GetString() + "/service-account-user")) + .GetProperty("id").GetString()!; + if (assignRole) + { + var management = await admin.ClientAsync("realm-management"); + var role = await admin.GetAsync("clients/" + management.GetProperty("id").GetString() + "/roles/view-users"); + (await admin.PostAsync( + "users/" + account + "/role-mappings/clients/" + management.GetProperty("id").GetString(), + new[] { role })).Should().Be(HttpStatusCode.NoContent); + } + + return account; + } + + private static async Task> CreateUsersAsync(KeycloakAdminClient admin, int count) + { + for (var index = 0; index < count; index++) + { + (await admin.PostAsync("users", new + { + username = $"enumeration-user-{index:D3}", + enabled = true, + email = $"enumeration-user-{index:D3}@example.test", + firstName = "Enumeration", + lastName = $"User{index:D3}", + })) + .Should().Be(HttpStatusCode.Created); + } + + // The realm may use the e-mail address as the username, so the created accounts are found by search. + var found = await admin.GetAsync("users?search=Enumeration&first=0&max=1000&briefRepresentation=true"); + var ids = found.EnumerateArray().Select(user => user.GetProperty("id").GetString()!).ToList(); + ids.Count.Should().Be(count, "every created account is found"); + return ids; + } + + private async Task AccessTokenAsync(HttpClient client) + { + using var response = await client.PostAsync( + new Uri(_keycloak.BaseAddress, "realms/learnstack/protocol/openid-connect/token"), + new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "client_credentials", + ["client_id"] = ReaderClient, + ["client_secret"] = ReaderSecret, + })); + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("access_token").GetString()!; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs index 96e39522..f6e43007 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs @@ -3,6 +3,7 @@ using System.Text.Json.Nodes; using FluentAssertions; using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Hosting; using LearnStack.Tests.Integration.Database; using LearnStack.SharedKernel.Platform; @@ -80,7 +81,7 @@ public async Task The_Operator_Client_Issues_A_Token_That_Meets_The_Operator_Pro .Should().BeLessThanOrEqualTo(TimeSpan.FromMinutes(15), "the realm caps the operator client's access token"); var settings = Settings(token.GetPayloadValue("acr")); - PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, null, out var witness, out _) + PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, PlatformOperatorSettings.Executor, null, out var witness, out _) .Should().BeTrue("the token the realm issues is the token the scheme accepts"); witness!.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_keycloak.IssuerFor("learnstack-hub"), token.Subject)); } @@ -116,7 +117,7 @@ public async Task A_Token_From_The_Portal_Client_Does_Not_Meet_The_Operator_Prof var token = new JsonWebToken(exchange.AccessToken); token.Audiences.Should().NotContain("learnstack-platform"); - PlatformOperatorTokenProfile.TryRead(token, Settings("mfa"), DateTimeOffset.UtcNow, null, out _, out _) + PlatformOperatorTokenProfile.TryRead(token, Settings("mfa"), DateTimeOffset.UtcNow, PlatformOperatorSettings.Executor, null, out _, out _) .Should().BeFalse("a portal token carries neither the operator client nor the platform audience"); } diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs index 4c7d2784..7b912df6 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs @@ -2,6 +2,7 @@ using System.Text.Json; using FluentAssertions; using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Hosting; using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Platform; @@ -31,7 +32,7 @@ public sealed class PlatformOperatorAuthenticationTests public void A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Pinned_Issuer() { var read = PlatformOperatorTokenProfile.TryRead( - Token(), Settings(), Now, "00-trace-01", out var witness, out var cause); + Token(), Settings(), Now, PlatformOperatorSettings.Executor, "00-trace-01", out var witness, out var cause); read.Should().BeTrue(); witness!.Issuer.Should().Be(Issuer); @@ -90,7 +91,7 @@ public void Each_Profile_Defect_Is_Refused_With_Its_Own_Closed_Cause(string defe default: throw new ArgumentOutOfRangeException(nameof(defect)); } - PlatformOperatorTokenProfile.TryRead(Token(claims), Settings(), Now, null, out var witness, out var cause) + PlatformOperatorTokenProfile.TryRead(Token(claims), Settings(), Now, PlatformOperatorSettings.Executor, null, out var witness, out var cause) .Should().BeFalse(); witness.Should().BeNull(); cause.Should().Be(expected); diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs index 49ded95f..75cd9213 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs @@ -1,5 +1,6 @@ using FluentAssertions; using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Time; using Xunit; diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs new file mode 100644 index 00000000..14a57f03 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs @@ -0,0 +1,144 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// The continuity proof of a controlled issuer rebind as a pure function (ADR-0104 § 6). +public sealed class IdentityRebindContinuityTests +{ + private static readonly IdentityAuthorityId Authority = + IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501")); + + private static IdentityRebindStoredUser Active(string subject) => + new(IdentitySubjectKey.Compute(Authority, subject), subject, UserStatus.Active); + + private static IdentityRebindStoredUser Closed(string subject) => + new(IdentitySubjectKey.Compute(Authority, subject), null, UserStatus.Closed); + + private static IdentityRebindStoredUser Closing(string subject, bool retained) => + new(IdentitySubjectKey.Compute(Authority, subject), retained ? subject : null, UserStatus.Closing); + + [Fact] + public void A_Realm_That_Reports_Every_Active_Subject_Holds_And_Counts_The_Population() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Active("b")], ["a", "b"]); + + result.Should().Be(new IdentityRebindContinuityResult(2, 0, 0, 2, 0, 0, 0, 0)); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void An_Active_Subject_The_Realm_Does_Not_Report_Is_Counted_And_Fails_The_Proof() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Active("b")], ["a"]); + + result.MissingActive.Should().Be(1); + result.Holds.Should().BeFalse(); + } + + [Theory] + [InlineData("A")] + [InlineData(" a")] + [InlineData("a ")] + [InlineData("á")] + public void Presence_Is_The_Exact_Ordinal_Subject_Not_A_Normalized_One(string reported) + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], [reported]).MissingActive.Should().Be(1); + } + + [Fact] + public void A_Reported_User_With_No_Stored_Key_Is_A_Person_Who_Has_Not_Signed_In_And_Is_Allowed() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "new-1", "new-2"]); + + result.Unbootstrapped.Should().Be(2); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void A_Closed_Persons_Key_That_A_Reported_Subject_Would_Claim_Fails_The_Proof() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Closed("gone")], ["a", "gone"]); + + result.ReappearingClosed.Should().Be(1); + result.StoredClosed.Should().Be(1); + result.Holds.Should().BeFalse(); + } + + [Fact] + public void A_Closed_Persons_Absence_Holds_And_Never_Counts_Against_The_Active_Rule() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Closed("gone")], ["a"]); + + result.ReappearingClosed.Should().Be(0); + result.MissingActive.Should().Be(0); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void A_Closing_User_That_Retains_Its_Subject_Is_Judged_By_Neither_Rule() + { + var absent = IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: true)], []); + var present = IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: true)], ["leaving"]); + + absent.Holds.Should().BeTrue("closure owns the transition, so its absence is not a lost person"); + present.Holds.Should().BeTrue("and its presence is not a reappearance"); + absent.StoredClosing.Should().Be(1); + } + + [Fact] + public void A_Closing_User_That_Retains_Only_Its_Key_Is_Judged_Like_A_Closed_One() + { + IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: false)], ["leaving"]) + .ReappearingClosed.Should().Be(1); + IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: false)], []) + .ReappearingClosed.Should().Be(0); + } + + [Fact] + public void A_Subject_That_Cannot_Be_A_LearnStack_Subject_Is_Counted_And_Matches_Nothing() + { + var overlong = new string('x', 256); + + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "", overlong, "ok"]); + + result.Unkeyable.Should().Be(2); + result.Unbootstrapped.Should().Be(1, "only the one reported subject that could be one and matches nothing stored"); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void Duplicate_Reported_Subjects_Are_One_Subject() + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "a", "a"]).Enumerated.Should().Be(1); + } + + [Fact] + public void An_Empty_Realm_Fails_Any_Active_Population_And_Holds_An_Empty_One() + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], []).Holds.Should().BeFalse(); + IdentityRebindContinuity.Evaluate(Authority, [], []).Holds.Should().BeTrue(); + } + + [Fact] + public void A_Stored_Active_Row_Without_A_Subject_Cannot_Be_Present_And_Is_Counted_Missing() + { + var corrupt = new IdentityRebindStoredUser(IdentitySubjectKey.Compute(Authority, "a"), null, UserStatus.Active); + + IdentityRebindContinuity.Evaluate(Authority, [corrupt], ["a"]).MissingActive.Should().Be(1); + } + + [Fact] + public void The_Key_Of_A_Reported_Subject_Is_Computed_Under_The_Stored_Authority_Only() + { + var other = IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502")); + var foreignClosed = new IdentityRebindStoredUser(IdentitySubjectKey.Compute(other, "gone"), null, UserStatus.Closed); + + IdentityRebindContinuity.Evaluate(Authority, [foreignClosed], ["gone"]).ReappearingClosed + .Should().Be(0, "a key under another authority is not the same person"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs index 36bf31fe..47cfe8ce 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs @@ -60,7 +60,7 @@ public async Task An_Admitted_Act_Runs_On_A_Resolved_Ambient_Context_Of_The_Tena seen.Context.HostScope.Should().BeNull(); seen.Descriptor.Should().NotBeNull(); seen.Descriptor!.SourceKind.Should().Be(AuthorizationSourceKind.PlatformOperator); - seen.Descriptor.RequestType.Should().Be(typeof(OperatorProvisionTenantCommand)); + seen.Descriptor.RequestType.Should().Be(); seen.Descriptor.Operator!.ReasonSlug.Should().Be("tenant_provision"); seen.Descriptor.Operator.Issuer.Should().Be(TestPlatformAdmissions.Issuer); seen.MatchedWhileLive.Should().BeTrue("the descriptor answers for its request in its context while the act is in flight"); diff --git a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md index 15af69d3..9275d098 100644 --- a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md +++ b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md @@ -418,3 +418,16 @@ fixed seed capability grants no operator or system bypass stands. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 9 — Controlled issuer rebind (2026-11-20) + +Accepted [ADR-0104](0104-controlled-issuer-rebind.md) is the only path that changes +`identity_authority.issuer`, and it changes nothing else. It preserves `AuthorityId`, +the subject keys, the actor ids and the closed tombstones that this record's identity +foundation fixes, and it reads `users` through four columns of a confined sixth role +without adding an update or a delete owner for `users`. A trigger refuses any change +of the authority's `id` or `authority_id` for every role. The statements that the +anchor is installed once and that no runtime process rebinds it stand. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0104-controlled-issuer-rebind.md b/docs/decisions/0104-controlled-issuer-rebind.md index 622ad6e5..d2af3f9f 100644 --- a/docs/decisions/0104-controlled-issuer-rebind.md +++ b/docs/decisions/0104-controlled-issuer-rebind.md @@ -183,3 +183,67 @@ and the runbook follow. [ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md) - [Database Standards](../standards/05-database.md) - [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 + +## Amendment 1 — Implementation contract of the rebind tool (2026-11-20) + +Step 3 of the platform-authority packet implements the decision. Each item below fixes +something the Decision left open or states where the code meets it; none changes the +Decision, the role's grants or the proof's rules. + +1. **Where the code lives.** The database half, `IdentityIssuerRebind`, lives in the + Identity module's Infrastructure `Bindings` namespace so unit and integration + tests reach it, beside the install-once installer. The tool project holds + configuration, the operator token, the new-realm reader and exit codes. The operator + validator moved from the API project into Infrastructure, so the API's bearer scheme + and the tool take one definition of the parameters, the bounded metadata manager and + the closed profile. The witness minter stays one class; the tool is a second caller + of the profile, with the executor `operator.rebind`, which is the "second sanctioned + caller" of § 3. +2. **The order.** The exclusive lock is the first statement of the transaction, held + by a server-side `lock_timeout` of 30 seconds, so the tool waits for another rebind + and refuses with a class. Under the lock it reads the stored authority. A run whose + target already equals the stored issuer ends there, with no row. Otherwise the intent + row commits on a second connection before the freeze check, the proof or the change. + An authority that is not the configured one is a continuity refusal, so it follows + the intent row. +3. **The audit rows.** The two operations are `identity.authority.rebind_attempt`, + outcome `indeterminate`, and `identity.authority.rebind`, outcome `success`, with the + reason slug `issuer_rebind`, the entity type `IdentityAuthority` and the authority + id as the entity. The policy arm admits exactly those two operation-and-outcome pairs + and no other row, and the central audit installer owns the `audit_log` SQL, as it + does for the creation witness. The result row carries counts and no subject. +4. **The freeze check counts the platform role too.** The platform role runs in the same + hosts as the application role, and an idle pooled connection of any of the four is + still a session. The check reports a count and never a session's identity. A pooled + connection stays a session until its idle lifetime ends, so the runbook's stop step + includes waiting for it. +5. **"Reads the new value" needs a comparison.** A lock alone only makes a creation + wait. Authority qualification takes the shared lock and then reads under a fresh + snapshot, and the User-creation admission takes the shared lock, reads the stored + authority and issuer, and refuses the creation when they are not the facts its process + qualified with. The two auxiliary read sources of the authorization and evidence + lanes take no lock: they run under a five-second total startup deadline, and a start + that straddles the change already fails at the locking read or at their own + comparison. +6. **The role is checked before it is used.** The tool refuses unless the session is the + rebind role, it holds no inherited, bypass, superuser, creation or replication + attribute and no membership, no privilege on any other table, and exactly the + declared column grants. +7. **Continuity details the Decision left open.** A Closing user that still holds its + subject is judged by neither rule, because closure owns that transition; a Closing + user that holds only its key is judged like a Closed one. A reported subject that + cannot be a LearnStack subject is counted and cannot equal any stored one. Presence is + the exact ordinal subject. +8. **Inputs and exit codes.** The operator token comes from the environment or one line of + standard input and the ticket, the realm client and its secret from the environment; + an argument is refused. The deployment mode is explicit, because it decides whether + a loopback operator issuer and the demo operator's grant are admitted. The tool + prints one line of classes and counts, with the correlation id that finds the rows, + and exits `0` for applied or already applied, `2` for a refusal that left the state + unchanged and `3` when the commit's outcome could not be read back. +9. **Signals in a short-lived process.** The counters are defined in the library and + exported by the tool only when an OTLP endpoint is configured in its environment; + the printed line and the audit rows are the record otherwise. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/glossary.md b/docs/glossary.md index 53abe4c9..fb892757 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -29,9 +29,10 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Provider event target** | Immutable tenant projection of one provider-global fact, with its own stable outbox event identity. It describes provider history rather than a tenant-authorized action; [ADR-0097](decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) owns the attribution contract. | | **ProviderEventRecipient** | Single-use machine execution witness for one claimed provider event target, separate from a human Membership or a generic integration-event envelope. [ADR-0097](decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) owns its scope boundary. | | **User** | A global application binding identified by the existing strongly typed `UserId`, separate from contextual Memberships. The permanent authority/subject-key mapping and lifecycle follow Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). | -| **Identity authority** | Stable provider namespace identified by a UUID and anchored to one current exact issuer URI in a deployment-installed, application-read-only singleton. Issuer drift cannot replace it. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns installation to P03-1 and controlled rebind to P03-9/G13. | +| **Identity authority** | Stable provider namespace identified by a UUID and anchored to one current exact issuer URI in a deployment-installed, application-read-only singleton. Issuer drift cannot replace it. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns installation to P03-1; only the controlled issuer rebind of [ADR-0104](decisions/0104-controlled-issuer-rebind.md) changes the issuer. | | **Identity subject binding** | Permanent mapping from stable identity authority and exact opaque subject, through the subject key, to one application actor. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) / [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md) contract. | | **Identity subject key** | Nonsecret SHA-256 equality and audit-linkage key derived from stable authority UUID and exact opaque subject under Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). It remains personal data, including for low-entropy subjects vulnerable to guessing. The [Database standard](standards/05-database.md#proposed-p03-1-identity-storage-annex) owns canonical encoding; [Data Protection](architecture/23-data-protection.md#proposed-identity-foundation-and-classification-ownership) owns retention purpose. | +| **Issuer rebind** | The controlled change of the one current issuer URI of the identity authority, under the same realm path, that preserves the stable `AuthorityId`, every subject key, actor id and closed tombstone. Run only by an offline tool on the confined `learnstack_identity_rebind` role, after the operator's token and `platform.identity_authority.admin` grant are admitted, a freeze (an exclusive advisory lock, with no session of a runtime role open) and a continuity proof against the new realm: every Active subject is still reported, and no closed person's key reappears. Writes an intent row and a result row under the platform sentinel. [ADR-0104](decisions/0104-controlled-issuer-rebind.md), [runbook](runbooks/identity-issuer-rebind.md). | | **Global-self bootstrap** | Admitted creation of only the verified provider subject's application binding, with no tenant Membership or permission. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) supplies the common internal owner; Accepted [ADR-0078](decisions/0078-native-session-scope-and-self-entry.md) defines bounded opt-in new-user HTTP/BFF entry. Implementation and qualification live in the [Phase 03 Status block](roadmap/phase-03-identity-admin.md). | | **Bootstrap admission** | Eligibility of a verified provider subject to attempt binding creation under independently admitted operation, authority, lifecycle, source and allocation-budget checks. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) and [ADR-0078](decisions/0078-native-session-scope-and-self-entry.md) establish no tenant Membership, invitation acceptance or ordinary BFF session merely by creating the actor. | | **Closure tombstone** | Retained Closed binding preserving subject key and actor indefinitely to refuse recreation, with raw subject removed by separately authorized closure. It remains linkable personal data, not anonymisation or a reusable actor reservation. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) defines the foundation; [Data Protection](architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites) assigns actual closure/retained-copy fulfillment to P03-10. | diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index fcf78194..9cb680ab 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -74,15 +74,22 @@ serving only anonymous reads, requires both runtime configuration keys and the matching installed authority. Startup qualification rejects missing, unavailable or mismatched registration before accepting HTTP requests. Direct `dotnet run` reads process/.NET configuration, not the root `.env`. Restore the intended -configuration when it differs from the selected database; an issuer rebind remains -P03-9/G13 and is not an automatic repair. +configuration when it differs from the selected database; an issuer change is never an +automatic repair. It is the controlled rebind of +[ADR-0104](../../decisions/0104-controlled-issuer-rebind.md), an offline tool on a +confined sixth database role ([runbook](../../runbooks/identity-issuer-rebind.md)): +it proves each Active person's subject is still reported by the new realm and no +closed person's key reappears, preserves `AuthorityId`, keys and actors, and writes an +intent row and a result row with the change. Authority qualification and the +User-creation admission wait for it behind a shared advisory lock and then read the +value it left. The internal binding service uses explicit startup qualification and fresh, physically read-only existing-binding transactions; it never creates a missing binding. Fixed seed adoption separately requires its confined admission port. Real provider/app-role, schema/body/ACL/caller and physical outcome controls are -implemented. The directory contract appears below; closure and issuer rebind -retain their named later owners. Production first-admin, Role-template initialization +implemented. The directory contract appears below; closure retains its named later +owner. Production first-admin, Role-template initialization and recovery are the operator acts of [ADR-0102](../../decisions/0102-production-tenant-onboarding.md) ([runbook](../../runbooks/tenant-onboarding.md)). diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 5445c74a..8d743a61 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -34,6 +34,8 @@ the request exists, and off-path events register by slug when their writer lands | Membership including Profile/Assignments | `identity.membership.create_first_admin` | **MUST** (`security-event`) | `OperatorCreateFirstAdminCommand`, the operator's production first administrator ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)); one Membership transaction on the operator source, `metadata.operator` and the reason slug on the row, refused once the tenant has had any member. | | Membership including Profile/Assignments | `identity.membership.recover_admin` | **MUST** (`security-event`) | `OperatorRecoverAdminCommand`, the operator's replacement administrator for a tenant with none active; one Membership transaction on the operator source, refused while any administrator is active. | | MembershipProfile, captured under Membership | `identity.membership_profile.set_seed_profile` | **MUST** (`update`) | `SetSeedMembershipProfile`; same Membership transaction. The slug matches the gated sub-resource while the row's subject remains its owning aggregate. | +| Identity authority | `identity.authority.rebind_attempt` `(off-path)` | **MUST** (`security-event`) | The controlled issuer rebind's intent row ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)): committed on the offline tool's own short transaction, by the confined `learnstack_identity_rebind` role, before the main transaction begins, so an aborted attempt is on record. Platform sentinel tenant, outcome `indeterminate`, no actor, `metadata.operator` with the ticket. Written through the witness-bound `WriteIdentityRebindIntentAsync`, never the pipeline. | +| Identity authority | `identity.authority.rebind` `(off-path)` | **MUST** (`security-event`) | The rebind's result row: written on the same transaction as the one-column issuer change, so it commits with the change or not at all, and a forced audit failure rolls the change back. Outcome `success`, before and after issuer, continuity counts and no subject in `metadata`. Written through the witness-bound `WriteIdentityRebindResultAsync`. | | Authorization decision | `identity.authorization.deny` `(off-path)` | **MUST** (`security-event`) | Central HTTP/application/resource denial owner; one decided invocation event, separate from ordinary plural resource intents. No tenant override or host suppression budget. | | Membership directory | `identity.membership.list` | **MUST** (`read-sensitive`) | Internal `ListMembershipsQuery` under existing Tenant `identity.membership.admin`; ordinary ReadWrite owner commits its row before disclosure. No HTTP activation follows from its catalogue entry. | | Role including grants | `identity.role.change_grants` | **MUST** (`security-event`) | `ChangeRoleGrantsCommand`; one Role root and contained grant diff, expected row version and fresh post-lock authority recheck; success/audit share the transaction. | diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index bf5ae187..6b574aee 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -11,3 +11,4 @@ begins this directory with the platform operator runbooks; | [Platform operator access](operator-access.md) | An operator needs a token, a grant, or an answer to a 401, 403 or 503 | | [Killswitch](killswitch.md) | A capability must be switched off for every tenant during an incident | | [Tenant onboarding](tenant-onboarding.md) | A production tenant must be provisioned, mapped to a host and given its first administrator, or an administrator must be recovered | +| [Identity issuer rebind](identity-issuer-rebind.md) | The tenant identity provider keeps its realm and users but changes address, and the stored issuer must follow without re-keying anyone | diff --git a/docs/runbooks/identity-issuer-rebind.md b/docs/runbooks/identity-issuer-rebind.md new file mode 100644 index 00000000..19bf8227 --- /dev/null +++ b/docs/runbooks/identity-issuer-rebind.md @@ -0,0 +1,202 @@ +# Identity issuer rebind + +Moving the identity authority from one issuer origin to another, under the same realm +path, without re-keying a single person. Decided in +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md); the storage contract of the +confined role is in +[Database Standards](../standards/05-database.md#controlled-issuer-rebind-storage). +This is a planned, rare act with a downtime window. A development environment never +needs it. + +## When to use it, and when not to + +Use it when the deployment's tenant identity provider keeps its realm and its users but +changes address: a new host name, a new load balancer origin, a migration to another +cluster that preserved every user's `sub` (a realm export and import does). + +It does **not** change the stable authority identifier, and it refuses a new realm that +would lose or resurrect a person. It cannot rename the realm path (the issuer must keep +ending in `/realms/learnstack`), re-key users, merge two providers or move a tenant +between authorities. A new realm whose users have new `sub` values is a different +authority and is not reachable here: escalate before doing anything. + +## What it needs + +| Needed | Why | +|---|---| +| An operator with a current token and the grant `platform.identity_authority.admin` | The same operator token and grant model as the other [operator acts](operator-access.md). The grant is read from configuration when the tool runs, never from a claim | +| The sixth database role's connection string | `ConnectionStrings__IdentityRebind` for `learnstack_identity_rebind`. It exists only in the tool's environment for the minutes it runs: never in an API, worker, seeder or web configuration, and never in a file under version control | +| A read-only credential for the **new** realm | A confidential client with the single role `realm-management/view-users`, created for this run and deleted after it. It is not a LearnStack credential and is not in the realm export | +| The stable `Identity__AuthorityId` and the new `Authentication__Tenant__Issuer` | The same two values the deployment is about to run with. The authority must equal the stored one; the issuer is the target | +| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance | + +## Before you start: freeze + +The tool takes a database lock that makes every API start and every new user binding +wait, and it refuses to run while any session of the application, outbox, ingress or +platform role is open on the database. It cannot see a process that holds no database +connection, so the stop step below is the control for that case. + +1. Announce the window and **stop every API and worker process** of the deployment, + including the Hangfire server, the outbox dispatcher and the provider-event poller. +2. Wait for their connections to close. A pooled connection stays a session until its + idle lifetime ends (about five minutes by default), so the tool will refuse with + `refused_live_sessions` and a count until the pools have drained. A count is all it + reports; to see which role, read `pg_stat_activity` yourself. +3. Keep the **old** configuration out of every restart script. A process that is started + with the old issuer after the change fails its start on the mismatch, which is the + safe outcome; a process that was running and idle is the one the tool cannot see. + +## Get the access token + +Follow [Getting a token](operator-access.md#getting-a-token) for the operator issuer. The +token lasts at most 15 minutes and its `auth_time` must be recent, so sign in just +before the run. Give it to the tool in `LEARNSTACK_OPERATOR_TOKEN`, or pipe it on +standard input so it does not sit in the environment. **Never pass it as an argument**: +the tool refuses any argument. + +## Create the read-only realm credential + +In the **new** realm's administration console create a client with *Client +authentication* on, only *Service accounts roles* enabled, and give its service account +the single client role `realm-management` / `view-users`. Copy its id and secret into +`LEARNSTACK_REBIND_REALM_CLIENT_ID` and `LEARNSTACK_REBIND_REALM_CLIENT_SECRET`. Delete +the client when the run is over, whatever the outcome. + +## Run it + +From a host that can reach the database and both issuers, with the stopped deployment's +settings in the environment: + +```sh +export Deployment__Mode= +export ConnectionStrings__IdentityRebind="Host=$DB_HOST;Database=$DB_NAME;Username=learnstack_identity_rebind;Password=$REBIND_PASSWORD" # leakwatch:ignore:database-connection-string +export Identity__AuthorityId= +export Authentication__Tenant__Issuer= +export PlatformOperator__Issuer=... PlatformOperator__AuthorizedParties__0=... PlatformOperator__AcceptedAcr__0=... +export PlatformOperator__Grants__0__Subject= +export PlatformOperator__Grants__0__Permissions__0=platform.identity_authority.admin +export LEARNSTACK_REBIND_REALM_CLIENT_ID=... LEARNSTACK_REBIND_REALM_CLIENT_SECRET=... +export LEARNSTACK_REBIND_TICKET=CHG-123 # optional, 1 to 64 characters +printf %s "$TOKEN" | dotnet LearnStack.Tools.IdentityAuthorityRebind.dll +``` + +It prints exactly one line and exits: + +| Exit | Meaning | +|---|---| +| `0` | The issuer was changed (`outcome=applied`), or already equalled the target (`outcome=already_applied`, nothing written) | +| `2` | Refused. **The state is unchanged**; fix the cause and run it again | +| `3` | `outcome=unknown`: the commit's answer was lost and the stored issuer could not be read back. Read `identity_authority.issuer` before anything else | + +Every line carries `correlation=`, which finds the audit rows, and counts where the +proof ran: `active`, `closing`, `closed`, `reported`, `unkeyable`, `missing_active`, +`reappearing_closed` and `unbootstrapped`. It never prints a subject, a key, an issuer, +an address or a credential. + +## What the tool does, in order + +1. Validates the token with the operator validator and admits the act against the + grant. A refusal here (`refused_operator_...`) writes nothing, not even a row. +2. Opens one direct, never-pooled connection as the rebind role, checks that the role is + exactly what it was granted, and takes the exclusive rebind lock as its first + statement. If another rebind holds it, the tool waits up to 30 seconds and refuses + with `refused_rebind_in_progress`. +3. Reads the stored authority. If the stored issuer already equals the target it ends + with `already_applied` and **writes nothing**. +4. Otherwise commits an **intent** audit row on its own short transaction. From here on an + aborted attempt is on record. +5. Refuses while a session of a runtime role is open (`refused_live_sessions`). +6. Reads the new realm's discovery document, key set and users, and requires the realm's + own `issuer` to equal the target, at least one signing key and a complete enumeration. +7. Proves continuity (below), changes the one column, writes the **result** row on the + same transaction and commits. + +## The continuity proof + +- Every **Active** user's exact stored subject must be among the new realm's `sub` + values. A missing one is `missing_active`. +- No reported `sub` may produce the key of a **Closed** user, whose subject is gone and + only its key kept, so a closed person cannot reappear. That is `reappearing_closed`. +- A user in the new realm that matches no stored key is allowed: that person has not + signed in yet. +- A user that is **Closing** and still holds its subject is judged by neither rule, + because closure owns that transition. +- A `sub` that could not be a LearnStack subject (blank, over 255 characters) is counted as + `unkeyable` and cannot equal a stored one. + +`refused_continuity_broken` means the new realm is not the same population. Do not +force it: find out why the users differ. The usual cause is an import that generated new +ids. + +## When it refuses + +| Outcome | What it means and what to do | +|---|---| +| `refused_input` | A required value is missing, malformed, or an argument was given. The tool says no more, so that a mistake cannot echo a secret. Check `Deployment__Mode`, the connection string's role, the authority id, the issuer, the token and the realm credential | +| `refused_operator_token_` | The token failed validation: `token_missing`, `token_expired`, `token_audience`, `token_issuer`, `token_signature`, `token_algorithm`, `token_type`, `token_lifetime`, `metadata_unavailable`, `metadata_stale` or a `profile_*` cause. [The profile](operator-access.md#the-token-profile) says what each requires. Get a fresh token | +| `refused_operator_missing_permission` | The token is good and the operator holds no `platform.identity_authority.admin` grant | +| `refused_operator_issuer_not_configured` / `..._configuration_invalid` | The `PlatformOperator__*` settings are absent or unsafe | +| `refused_role_invalid` | The connection string is not the rebind role's, or the role holds something beyond its grants. Re-run the roles script | +| `refused_rebind_in_progress` | Another rebind holds the lock, or a previous run is still open. Wait and retry | +| `refused_database_unavailable` | The database could not be reached or answered a failure. Nothing changed | +| `refused_authority_mismatch` | The stored authority is not `Identity__AuthorityId`. A different authority would re-key every person: stop and escalate | +| `refused_live_sessions` | A session of a runtime role is open (the count is printed). Stop what holds it and retry | +| `refused_new_realm_unavailable` / `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm could not be read completely, published no signing key, changed while it was read, or names another issuer. Check the credential's role and the realm's address | +| `refused_continuity_broken` | See above | +| `refused_audit_failed` | The audit row could not be written, so the change was rolled back | +| `refused_commit_failed` | The commit failed and the stored issuer was read back unchanged. Retry | +| `refused_cancelled` | The ten-minute deadline or an interrupt ended the run | + +Every refusal leaves the stored issuer where it was and the next run repeats the whole +proof. The intent row stays, so the trail shows each attempt. + +## After it + +The change is done when the tool prints `applied`. **Deploying the new issuer +configuration is the unfreeze.** + +1. Set `Authentication__Tenant__Issuer` to the new value in every API and worker + configuration, and start them. A process that still holds the old value fails its + start with the fixed qualification error: that is the guard, not a bug. +2. Delete the read-only realm client and remove `ConnectionStrings__IdentityRebind` + from the tool's host. +3. Confirm one sign-in per tenant host and look at the audit rows: + + ```sql + -- as a role that can read audit_log, not the rebind role + SELECT timestamp, operation, outcome, reason, entity_id, before_state, after_state, + metadata->'operator' AS operator, metadata->'continuity' AS continuity + FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; + ``` + + The two rows are `identity.authority.rebind_attempt` (`indeterminate`) and + `identity.authority.rebind` (`success`), under the platform sentinel tenant, with no + actor. The ticket is in `metadata.operator`, because no tenant can read these rows. + +## Signals + +`learnstack_identity_rebind_runs_total{outcome}` counts each run and +`learnstack_identity_rebind_continuity_total{class}` counts the proof by class. The tool +is a short-lived process: it exports them only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set +in its environment, and the printed line and the audit rows are the record otherwise. +`learnstack_identity_lock_refusals_total{lock_kind="authority"}` counts a user creation +that waited out a rebind and found the issuer changed. + +## Not recoverable here + +- **A change of the stable authority identifier.** It re-keys every person and can + resurrect a closed tombstone. There is no tool for it; escalate. +- **A realm rename or a different realm path.** +- **A running process that held no database connection** when the tool ran. It keeps the + old issuer until it restarts, and then fails its start on the mismatch. The stop step + is the control for it, not the database. +- **A wrong rebind that was applied.** Run the tool again with the old issuer as the + target; the same proof and the same rows apply. + +## What this does not do + +It does not stop or start any process, deploy configuration, create or delete the +realm client, verify DNS or certificates, or move any tenant data. Moving a tenant +between identity authorities is out of scope for the whole platform until a decision +says otherwise. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index e75f8709..8079a3e3 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -36,6 +36,14 @@ PlatformOperator__Grants__0__Subject= PlatformOperator__Grants__0__Permissions__0=platform.killswitch.write ``` +The registered permissions are `platform.killswitch.write` +([killswitch](killswitch.md)), `platform.tenant.write` and +`platform.tenant_bootstrap.write` ([tenant onboarding](tenant-onboarding.md)), and +`platform.identity_authority.admin`, which the offline +[issuer rebind](identity-issuer-rebind.md) tool checks against the same grants. That +tool reads the same `PlatformOperator__*` settings from its own environment and is not +an API route. + A Self-Hosted issuer other than the shipped realm must issue access tokens that meet the profile below. If it cannot, no operator can act, by design. diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 65192621..0ff42d6e 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -969,8 +969,10 @@ is touched on a cache miss rather than on every request The original four roles retain separate login credentials and connection strings. [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) -adds only the [confined fifth machine role](#provider-event-intake-storage); the -role model remains closed. +adds only the [confined fifth machine role](#provider-event-intake-storage), and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) adds only the +[confined sixth rebind role](#controlled-issuer-rebind-storage); the role model remains +closed. | Role | Connection string | Present in | Used by | RLS posture | |------|---|---|---------|-------------| @@ -979,6 +981,7 @@ role model remains closed. | `learnstack_platform` | `ConnectionStrings:PlatformAdmin` | API host, worker host | `EnterPlatformAdminScope(reason)` and nothing else | `BYPASSRLS` | | `learnstack_outbox_admin` | `ConnectionStrings:OutboxDispatcher` | API host only; never Seeder or web | confined dispatcher infrastructure only | `BYPASSRLS` | | `learnstack_identity_ingress` | `ConnectionStrings:IdentityIngress` | API provider-ingress lane only | fixed minimized intake/claim/retire and scan/problem progress; no business/Audit/outbox grants | `NOINHERIT`, `NOBYPASSRLS` | +| `learnstack_identity_rebind` | `ConnectionStrings:IdentityRebind` | the offline rebind tool's environment only — **never** an API, worker, seeder or web host | `UPDATE (issuer)` on `identity_authority`, four `users` columns read, two audit rows inserted | `NOINHERIT`, `NOBYPASSRLS` | Migration **credentials** remain deploy-only. The five [enumerated Identity SECURITY DEFINER contracts](#confined-owner-functions) deliberately add runtime @@ -1023,6 +1026,13 @@ the fence omits and without which the grants add nothing: measured, an **unset** variable leaves the placeholder unbound and aborts init rather than creating a passwordless superuser-adjacent role — failing loud is the point. +The shipped script also creates the two confined roles after the four, with the same +shape and `NOINHERIT NOBYPASSRLS` (`ingress_pw` and `rebind_pw`), converges their +attributes, revokes every membership either holds or is granted, and adds both to the +`CONNECT` and schema `USAGE` grants. A missing password variable aborts initdb for them +as for the others. `DatabaseRoleTests` proves both log in, hold the declared attributes +and are taken back from an escalation. The fence below is the abridged baseline. + ```sql -- One-time provisioning, run once per database before the first migration. Ships as -- infra/compose/postgres-init/02-create-roles.sql in Phase 02a Packet 6. @@ -2144,6 +2154,12 @@ owns current review and qualification state. These limits add at most six retained connectors, not six per job or borrower; tests may reduce caps, deployment settings cannot widen them. They are bounded local concurrency choices, not throughput or fairness guarantees. +- Neither auxiliary source takes the shared rebind lock that authority qualification + and the User-creation admission take + ([§ Controlled issuer rebind storage](#controlled-issuer-rebind-storage)): they run + under the five-second startup deadline and no business advisory lock, and a start + that straddles a rebind already fails at the locking qualification or at their own + comparison of the stored issuer. - Both auxiliary sources use the same guarded `learnstack_app` role, actual database, installed identity authority and tenant/org RLS as business work. Neither has a raw general-DI datasource alias, generic SQL/callback API or @@ -4719,8 +4735,10 @@ Qualify the anchor/configuration pair before enabling identity admission; the request path uses that immutable admitted configuration and performs no anchor lookup before the subject quota. A changed pair requires requalification, not live replacement of a request's verified authority. -P03-9/G13 owns a future controlled issuer rebind with verified continuity and a -freeze boundary; no runtime rebind owner is admitted here. +Only the controlled issuer rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) changes `issuer`, through the +[confined sixth role](#controlled-issuer-rebind-storage) used by one offline tool, +with verified continuity and a freeze boundary; no runtime role has a path to it. **Canonical subject-key encoding.** Compute SHA-256 over three concatenated length-prefixed byte strings: UTF-8 `learnstack.identity.subject.v1`, the stable @@ -6296,3 +6314,106 @@ hash that supplies neither secrecy nor admission authority discloses that a person exists, not who they are or what they may do. The handlers check that the act is live before they call it; no SQL-level binding is added. +## Controlled issuer rebind storage + +**Derives from:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) and its +Amendment 1. The rebind changes one column of the one `identity_authority` row, from a +sixth login role used by an offline tool. It adds a role, exact column grants, three +policy changes, one trigger and one advisory-lock key, and **no** definer: the definer +census stays at sixteen. + +### The role + +`learnstack_identity_rebind` is `LOGIN NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB +NOCREATEROLE NOREPLICATION`, a member of nothing and with no member. Its credential is +`ConnectionStrings__IdentityRebind`, read by the tool from its own environment with +`Environment.GetEnvironmentVariable`, never by `GetConnectionString`, and confined to the +one tool file that reads it by +[`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool). +No API, worker, seeder, web or compose service receives it. + +### Grants, read from the column view + +Table-level views do not show column grants, so the census reads +`information_schema.column_privileges`, and the table-level census lists only the two +table-wide grants. + +| Object | Privilege | +|---|---| +| `identity_authority` | `SELECT`, and `UPDATE (issuer)` only | +| `users` | `SELECT (authority_id, subject_key, provider_subject, status)` only | +| `audit_log` | `INSERT` only, on every column; the policy bounds the row | + +It holds no function `EXECUTE` of its own, no sequence, no schema `CREATE` and no +database `CREATE`. `IdentityAuthorityRebindStorageTests` asserts the exact column set, +the absence of the rest, and each refusal as the role itself. + +### Policies + +One permissive policy per command is kept. `identity_authority_read` gains the role +beside the application role and the owner; a third policy, `identity_authority_rebind`, +admits `UPDATE` of the `id = 1` row to the role and nothing else; `users_isolation` +gains the role in its `USING` and keeps its `WITH CHECK`, so the role sees every user and +may write none. The `audit_log_isolation` policy gains one arm in its `WITH CHECK`, +installed by the central audit installer because no module names the table: platform +sentinel tenant, identity module, no organization, `Must` and `SecurityEvent`, entity +type `IdentityAuthority`, reason `issuer_rebind`, no actor, mail, address or agent, an +operator attribution in `metadata`, and exactly `identity.authority.rebind_attempt` with +outcome `indeterminate` or `identity.authority.rebind` with outcome `success`. The role +has no `SELECT` on the table, so it cannot read its own rows back. + +### The key trigger + +`fn_identity_authority_immutable_key()` is a `SECURITY INVOKER` trigger function, owner +`learnstack_migration`, `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, on `BEFORE +UPDATE` of `identity_authority`. It raises `23514` when `id` or `authority_id` changes, +for every role, so the stable key the subject keys hash cannot move even where a grant +would allow it. It is the thirtieth function and thirtieth trigger of the Identity chain +census. The issuer grammar stays in the tool and in qualification, not in SQL. + +### The lock + +One bigint advisory key, `IdentityAdvisoryLockKey.ForAuthorityRebind()`, SHA-256 over the +length-prefixed strings `learnstack.identity.lock.v1` and `authority-rebind`, the first +eight bytes as a big-endian signed integer, with an independently computed vector pinned +in `GlobalIdentityKeyTests`. The tool takes it **exclusive** (`pg_advisory_xact_lock`) as +the first statement of one direct, never-pooled transaction. Authority qualification and +the User-creation admission take the **shared** form first and always before the subject +lock, so the order is fixed and the tool, which takes only this key, cannot form a cycle. + +- **Qualification** takes it after `SET TRANSACTION READ ONLY` and before its read; under + `READ COMMITTED` the next statement sees the rebind it waited for and compares against + the new issuer. +- **The creation admission** takes it under its two-second `lock_timeout` and then reads the + stored authority and issuer, refusing with `IdentityAuthorityChangedException` when they + are not the facts the process qualified with. A lock alone would only delay a + creation from a process that qualified before the rebind; the comparison is what + refuses it. The refusal answers as the sibling storage failures do and is counted in + `learnstack_identity_lock_refusals_total{lock_kind="authority",reason="mismatch"}`. +- [`Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock`](21-architecture-tests-catalogue.md#only_the_rebind_run_and_the_two_freeze_readers_take_the_rebind_lock) + pins the three takers. + +### What the tool checks before it uses the role + +Server-side, as the role: `session_user` and `current_user` are the role; it is not +`INHERIT`, `BYPASSRLS`, superuser, `CREATEDB`, `CREATEROLE` or `REPLICATION`; it has no +membership either way and no schema or database `CREATE`; it holds no privilege on any +other table; and it holds exactly the declared grants on the three it uses. Any other +posture refuses the run before the lock. The freeze check counts sessions of the +application, outbox, ingress and platform roles in the database other than its own, from +`pg_stat_activity`, which shows another role's session with its role and database even +where the statement is hidden. + +### Proof + +Real PostgreSQL as the role itself and as each other role: +`IdentityAuthorityRebindStorageTests` (column privileges, the one admitted `UPDATE`, the +key trigger with the grant present, the `users` read, the two audit rows and every +refused variant), `IdentityAuthorityRebindLockTests` (a start that waits for a rebind and +then fails or passes on the value it left, a creation refused within its timeout, a +straggler refused after the change), `IdentityAuthorityRebindTests` (the run end to end, +every refusal class, the continuity rules, an audit failure rolling the change back, a +killed session and a lost commit acknowledgement) and `IdentityAuthorityRebindToolTests` +(the offline tool as a child process). The census counts are in +`GlobalIdentitySchemaTests` (thirty functions, sixteen definers, thirty triggers) and +the head pin in `MigrationRollbackTests`. diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index cf266e1c..b3d589a3 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -480,6 +480,8 @@ backend treat business rejections as system failures. | `learnstack_platform_operator_results_total` | counter | operation | | `learnstack_platform_operator_audit_failures_total` | counter | operation | | `learnstack_platform_operator_metadata_failures_total` | counter | none | +| `learnstack_identity_rebind_runs_total` | counter | outcome (`applied`, `already_applied`, `unknown`, or a `refused_` class; [runbook](../runbooks/identity-issuer-rebind.md#when-it-refuses)) | +| `learnstack_identity_rebind_continuity_total` | counter | class (`active`, `closing`, `closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed`, `unbootstrapped`) | | `learnstack_db_query_duration_seconds` | histogram | module, operation | | `learnstack_outbox_pending_count` | gauge | — | | `learnstack_outbox_dispatch_duration_seconds` | histogram | event_type | diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 1fee1403..69189189 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -171,7 +171,16 @@ LearnStack runs **two Keycloak realms** per the operator surface remains the killswitch writer. The executor that installs an act's tenant context accepts only an admission the gate minted for that act within the last 30 seconds and spends it once, and the seeder refuses to run outside a - Development deployment. + Development deployment. The controlled issuer rebind + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)) is not an HTTP route at + all: an offline tool validates the same operator token with the same validator, admits + the act against the same per-act grant (`platform.identity_authority.admin`) and then + uses a sixth, confined database role whose credential exists only in the tool's + environment ([Database Standards](05-database.md#controlled-issuer-rebind-storage)). + Its realm credential is an operator-supplied `view-users` client for the new realm, + created for the run and deleted after it; it is not a LearnStack runtime or federation + credential, and [ADR-0099](../decisions/0099-confined-tenant-federation.md)'s refusal + of user-level authority for LearnStack is unaffected. General rules: @@ -573,6 +582,18 @@ for the full strategy. Standards-side: `SET LOCAL` inside the ambient transaction — see § Tenant Context immediately below, which is the single authority for that placement. +### Confined identity-rebind role + +`learnstack_identity_rebind` is the sixth login role and the only credential that can +change `identity_authority.issuer`. It is `NOINHERIT` and `NOBYPASSRLS`, holds a handful +of column grants and one policy arm, and is configured on no API, worker, seeder, web or +compose service: [`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool) +confines the key to the one tool file that reads it, and the tool refuses to use a role +whose posture is not exactly the declared one. A column grant to a runtime role guarded +by a transaction setting was rejected, because any session can set the setting. +[Database Standards](05-database.md#controlled-issuer-rebind-storage) owns the grants, +policies, trigger and lock. + ### Confined event dispatcher ADR-0046 accepts this P02b-2 boundary. Step 1 implements source/role guards; diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 22331a51..386e6fae 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -228,7 +228,11 @@ will raise them — which this standard requires it to do. shipped its writer ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)); it keeps `(off-path)` because the write runs inside the platform scope rather than through the - pipeline. + pipeline. The controlled issuer rebind's two rows, `identity.authority.rebind_attempt` + and `identity.authority.rebind` ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) + § 8), are `(off-path)` for the same reason one step further: they are written by an + offline tool on its own role through two witness-bound methods, under the platform + sentinel, with no actor and the ticket in `metadata.operator`. ## Baseline Coverage (LearnStack Core Modules) diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 6ffd1431..b130598e 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write`, `platform.tenant.write` and `platform.tenant_bootstrap.write` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write` and `platform.identity_authority.admin` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | @@ -106,13 +106,18 @@ not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authori | `platform.killswitch.write` | `tenancy.killswitch.toggle` | P03-9 Step 1 | | `platform.tenant.write` | `tenancy.tenant.create` (tenant provisioning), `tenancy.hostmapping.write` (host mapping) | P03-9 Step 2 | | `platform.tenant_bootstrap.write` | `identity.role.initialize`, `identity.membership.create_first_admin`, `identity.membership.recover_admin` | P03-9 Step 2 | +| `platform.identity_authority.admin` | `identity.authority.rebind` (the controlled issuer rebind, an offline tool and not a route) | P03-9 Step 3 | The five onboarding acts of [ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the `PlatformOperator` authorization source, which is not a Membership candidate: their policies are `FiniteTrusted` with that single source, the business actor of every row they write is `UserId.SystemActor`, and the operator is recorded in audit only. The -grant is evaluated by the gate on every act, never cached across acts. +grant is evaluated by the gate on every act, never cached across acts. The rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) is not an act of that +executor and not a route: its registered operation needs neither the platform role nor +the pipeline, so neither the scope nor the executor can spend its admission, and the +offline tool that consumes it validates the same token and evaluates the same grant. Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 0842b044..cb2b81d8 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**383 test methods run in +**385 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**287 rules in this catalogue are Implemented, and 169 of them are in that assembly.** +**289 rules in this catalogue are Implemented, and 171 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -1877,13 +1877,15 @@ catalogue as the carrier of their status — so all three are Packet 10's. and every `DbContext` service in it is one `AddModuleDbContext` registered — scoped, from an implementation factory, never a type registration EF could give its own connection. Under `backend/src`, the configuration/construction scan - admits exactly **thirteen** files: six design-time factories, one per migration + admits exactly **sixteen** files: six design-time factories, one per migration chain; `ModuleDbContextRegistration`, which passes a *connection*; `PersistenceCompositionExtensions`, with the guarded platform-role builder; `ApplicationDataSource`, shared by the API and one-shot Seeder; - ADR-0046's confined `OutboxDispatcherDataSource`; and ADR-0072's deployment-only - `LearnStack.Tools.IdentityAuthorityInstaller/Program.cs`; and ADR-0076/0077's - private authorization and evidence source builders. Another construction + ADR-0046's confined `OutboxDispatcherDataSource`; ADR-0072's deployment-only + `LearnStack.Tools.IdentityAuthorityInstaller/Program.cs`; ADR-0076/0077's + private authorization and evidence source builders; the invitation SMTP and + provider-event intake sources; and ADR-0104's `IdentityIssuerRebind`, which opens + the rebind role's own direct connections. Another construction site requires its owning decision and an explicit allow-list change. A context on its own connection never saw the announcement, so every read through it returns zero rows under the corrected policy — silently. @@ -3779,9 +3781,11 @@ which decides identity, multiplicity, capture and classification; `The_AppendOnly_Sweep_Can_Actually_Fail`, that checks the pattern against the shapes it must catch and the shapes it must not, because with no offending statement anywhere the sweep passes whether it works or matches nothing; and a reflection check, - `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly eight - write methods and no update: the event/job seams ship in Phase 02b, and - ADR-0072's two global seams ship in P03-1 Step 3. None + `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly thirteen + write methods and no update: the event/job seams ship in Phase 02b, ADR-0072's two + global seams in P03-1 Step 3, the two trusted authorization seams in P03-2, the + operator result seam of ADR-0101 in P03-9 Step 1 and the two controlled-rebind seams + of ADR-0104 in P03-9 Step 3. None of the three sanctioned redaction sites exists yet — they land in Phase 03 and Phase 11 — so the exemption set ships with the rule **empty**, as exact paths: the first site to land adds its own path, so it is exempted by name rather than the pattern @@ -5911,16 +5915,51 @@ structural test proves — and what it does not. #### `The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only` -- **Asserts:** the only source file that names `PlatformOperatorTokenProfile`, calls its - `TryRead` or names `PlatformOperatorWitness.Minter` is - `LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs`. A further caller - joins by an edit here: the offline rebind tool, in P03-9 Step 3. +- **Asserts:** the source files that name `PlatformOperatorTokenProfile` are exactly the + profile's own file, the API scheme's boundary + (`LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs`) and the offline + validator (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs`); + the files that call its `TryRead` are exactly the scheme boundary and the offline + validator, the two callers of ADR-0101 § 7 through one validator; and the only file + that names `PlatformOperatorWitness.Minter` is the profile's own, where the one + private nested minter lives. A further caller joins by an edit here. - **Why it matters:** the witness is evidence that a token passed the closed profile, and `TryRead` is the only door to the minter that makes one. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7. - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1 - review). + review; widened to the second caller by P03-9 Step 3). +- **Phase:** P03-9. + +#### `The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool` + +- **Asserts:** in code under `backend/src`, comments stripped, none of the spellings + `ConnectionStrings__IdentityRebind`, `ConnectionStrings:IdentityRebind` or + `GetConnectionString("IdentityRebind")` appears outside + `LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs`, which must itself name + the first. A planted source file in a temporary directory is found by the same scan, + and none of the demo launcher, the migration script or the two compose files carries + the key. +- **Why it matters:** the sixth role is the only credential that can change the issuer, + and the claim that no runtime host can change it is exactly the claim that no runtime + configuration names it + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 2). +- **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 2. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 3). +- **Phase:** P03-9. + +#### `Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock` + +- **Asserts:** by IL, the callers of `IdentityAdvisoryLockKey.ForAuthorityRebind` in every + production assembly are exactly `NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync`, + `IdentityAuthorityQualification.QualifyCoreAsync` and + `IdentityIssuerRebind.RunCoreAsync`. +- **Why it matters:** the exclusive form is the freeze and the shared form is what a start or a + creation waits behind; a fourth taker is a fourth party that can hold or wait on it. +- **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 5. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3). - **Phase:** P03-9. #### `Only_The_Operator_Services_Hold_The_Platform_Scope` diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index a24edd64..55cdd47d 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -107,6 +107,10 @@ "LearnStack.Tests.Integration.Database.HangfireStorageTests", "LearnStack.Tests.Integration.Database.HostResolutionTests", "LearnStack.Tests.Integration.Database.IdentityAdministrationReadTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindLockTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindStorageTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindToolTests", "LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpTests", "LearnStack.Tests.Integration.Database.IdentityAuthorizationReaderTests", "LearnStack.Tests.Integration.Database.IdentityCommandQualificationTests", @@ -115,6 +119,7 @@ "LearnStack.Tests.Integration.Database.IdentityMutationLockTests", "LearnStack.Tests.Integration.Database.IdentityOwnNavigationTests", "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests", + "LearnStack.Tests.Integration.Database.IdentityRebindAuditStoreTests", "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests", "LearnStack.Tests.Integration.Database.IdentitySeederTests", "LearnStack.Tests.Integration.Database.IdentitySelfDiscoveryOwnerTests", @@ -142,6 +147,7 @@ "LearnStack.Tests.Integration.Database.ModuleReceiptDisclosureTests", "LearnStack.Tests.Integration.Database.NativeScopeAdmissionDurabilityHttpTests", "LearnStack.Tests.Integration.Database.OperationReadScopeTests", + "LearnStack.Tests.Integration.Database.OperatorSubjectResolverTests", "LearnStack.Tests.Integration.Database.OrgScopeMigrationTests", "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests", "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests", @@ -152,6 +158,7 @@ "LearnStack.Tests.Integration.Database.OutboxProducerTests", "LearnStack.Tests.Integration.Database.P02d2FoundationTests", "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests", + "LearnStack.Tests.Integration.Database.PlatformOperatorOnboardingTests", "LearnStack.Tests.Integration.Database.PlatformSchemaTests", "LearnStack.Tests.Integration.Database.PoolHangfireStorageParityTests", "LearnStack.Tests.Integration.Database.PostgresIdempotencyStoreTests", From 5bbba1d7dba966932e0325058ae3a834224c5cd0 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 01:19:28 +0300 Subject: [PATCH 14/28] test(identity): close the step 3 mutation gaps Mutation checks of the rebind guards found four survivors: the audit store's tenant rule was masked by the ticket check, the realm reader's origin rule was exercised only against a closed port, the page loop was untested past a first page boundary by one mutant, and the sign-in creation path's mapping of a changed authority had no case. Each now has a test that kills its mutant. Two survivors are equivalent and recorded: the store's operation-identity check is redundant with its off-path catalogue lookup, and ValidateIssuerSigningKey governs the key's own validity, not signature verification. Co-Authored-By: Claude Sonnet 5.5 --- ...dentityBootstrapTests.CreationAdmission.cs | 19 +++++++++++++++++++ .../Database/IdentityRebindAuditStoreTests.cs | 13 +++++++++++++ .../FakeKeycloakRealm.cs | 13 +++++++++++-- .../KeycloakRealmContinuitySourceTests.cs | 17 +++++++++++++++++ docs/runbooks/tenant-onboarding.md | 5 +++-- 5 files changed, 63 insertions(+), 4 deletions(-) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs index f5a46f1a..2b98a6c1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs @@ -32,6 +32,25 @@ public async Task Self_bootstrap_uses_the_production_common_owner_and_repeat_con row.Outcome.Should().Be("success"); } + [Fact] + public async Task A_self_bootstrap_from_a_process_that_qualified_before_a_rebind_is_refused_and_creates_nothing() + { + // ADR-0104 § 5: the process qualified against the old issuer and kept running; the issuer then changed. + await using var provider = SelfProvider(); + await QualifyAsync(provider); + await using (var rebind = await OpenConnectionAsync(_database.IdentityRebindConnectionString)) + await using (var change = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = 'https://after-the-rebind.example.test/realms/learnstack' WHERE id = 1", rebind)) + { + (await change.ExecuteNonQueryAsync()).Should().Be(1); + } + + var result = await BootstrapAsync(provider, Subject); + + result.Refusal.Should().Be(IdentityCreationRefusal.Unavailable, "the debit transaction reads the issuer after the rebind lock"); + (await CountsAsync()).Should().Be((0L, 0L)); + } + [Fact] public async Task Unadmitted_self_bootstrap_is_denied_before_any_creation_owner() { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs index a07b8a52..fedf92e7 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs @@ -120,6 +120,19 @@ public async Task A_Row_That_Differs_From_Its_Admission_Or_Its_Declaration_Is_Re (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); } + // Without a ticket the metadata check is silent about the tenant, so the tenant rule must stand on its own. + var untickedAdmission = Admit(); + var unticked = Result(untickedAdmission, authority); + foreach (var (attribute, draft) in new Dictionary + { + ["a real tenant, no ticket"] = unticked with { TenantId = TenantId.From(Guid.CreateVersion7()) }, + ["the nil tenant, no ticket"] = unticked with { TenantId = TenantId.From(Guid.Empty) }, + }) + { + var act = async () => await audit.WriteIdentityRebindResultAsync(draft, untickedAdmission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + // The intent method refuses the result's slug and outcome in turn. var intentOfResult = async () => await audit.WriteIdentityRebindIntentAsync(good, admission, connection, transaction); await intentOfResult.Should().ThrowAsync("the result slug is not the attempt slug"); diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs index 0b0b114c..31748dcd 100644 --- a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -36,6 +36,12 @@ private FakeKeycloakRealm(WebApplication app, List users) internal string? DiscoveryIssuer { get; set; } + /// + /// A reachable origin other than the issuer's: when set, the discovery document names its key set and token endpoint + /// there, so a reader that followed them would send the credential to a host that is up. + /// + internal string? ForeignOrigin { get; set; } + internal int? ReportedCount { get; set; } internal int? CountAfterRead { get; set; } @@ -79,8 +85,11 @@ private void Map(WebApplication app) return Task.CompletedTask; } - var jwks = _failure == "jwks-other-origin" ? "http://127.0.0.1:1/keys" : Issuer + "/keys"; - var token = _failure == "token-other-origin" ? "http://127.0.0.1:1/token" : Issuer + "/protocol/openid-connect/token"; + var foreign = ForeignOrigin ?? "http://127.0.0.1:1"; + var jwks = _failure == "jwks-other-origin" ? foreign + "/realms/learnstack/keys" : Issuer + "/keys"; + var token = _failure == "token-other-origin" + ? foreign + "/realms/learnstack/protocol/openid-connect/token" + : Issuer + "/protocol/openid-connect/token"; context.Response.ContentType = "application/json"; return context.Response.WriteAsync(JsonSerializer.Serialize(new { diff --git a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs index b3bd1af2..7095d4a3 100644 --- a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs @@ -108,6 +108,23 @@ public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names thrown.InnerException.Should().BeNull("no transport exception is carried out"); } + [Theory] + [InlineData("token-other-origin")] + [InlineData("jwks-other-origin")] + public async Task A_Reachable_Foreign_Origin_Named_By_Discovery_Is_Never_Called_And_Never_Gets_The_Credential(string failure) + { + await using var foreign = await FakeKeycloakRealm.StartAsync(3); + await using var realm = await FakeKeycloakRealm.StartAsync(3); + realm.ForeignOrigin = foreign.Issuer[..foreign.Issuer.IndexOf("/realms/", StringComparison.Ordinal)]; + realm.Fail(failure); + + var act = async () => await realm.ReadAsync(); + + await act.Should().ThrowAsync(); + foreign.TokenRequests.Should().BeEmpty("the client secret never leaves the issuer's own origin"); + foreign.AdminAuthorization.Should().BeEmpty(); + } + [Fact] public async Task A_Credential_Replacing_The_Certificate_Check_Is_Refused() { diff --git a/docs/runbooks/tenant-onboarding.md b/docs/runbooks/tenant-onboarding.md index 16221c39..113a85b0 100644 --- a/docs/runbooks/tenant-onboarding.md +++ b/docs/runbooks/tenant-onboarding.md @@ -191,5 +191,6 @@ no audit row. The gate's counters and events 7101 to 7103, 7105 and 7106 are in It does not verify DNS, issue TLS, send an invitation, set a plan or an entitlement, create a Hub record, or deprovision a tenant. A tenant that needs an entitlement before it serves is waiting on the Hub's push or the operator-configured default, which is the -Hub's runbook. Nothing here moves a tenant between identity issuers; that is a separate -act ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). +Hub's runbook. Nothing here moves the deployment between identity issuers; that is a +separate offline act ([runbook](identity-issuer-rebind.md), +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). From cde9a4b1c7593a149f49b9f005ba33842c2457c9 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 01:55:07 +0300 Subject: [PATCH 15/28] fix(identity): close P03-9 step 3 review round 1 findings Three independent reviews found two regressions and a set of gaps; each was checked against the code before it was fixed. The creation admission's issuer comparison broke two existing integration tests that used an authority other than the installed one, and the lock signal assertion did not know the new authority kind. The rebind role's audit_log access was open to any tenant it announced through the tenant setting, because the ordinary arm named no role; the arm now excludes the role. The role posture check compared table grants only; it now compares the three tables column by column in both directions and sweeps every other relation for any privilege. The reconciliation of an unknown COMMIT now waits for the original transaction behind the shared lock, the freeze is asked again before the change, disposal no longer replaces an outcome, and the target issuer and deployment mode follow the API's rules. The new-realm reader reads the realm twice and compares, refuses repeats, renews an expired token once, sends the credential only to the target realm, and bounds the realm size to what the deadline allows. The tool handles interrupts, bounds the stdin wait, prints every outcome on standard output and correlates every refusal. The validator and profile callers are pinned and the executor set is closed. The runbook, Amendment 1 and Standards 05, 10, 11, 19 and 21 are corrected to what the code does. Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorAuthentication.cs | 2 +- .../IdentityRebindAuditInstaller.cs | 7 +- .../PlatformOperatorActCatalog.cs | 8 +- .../PlatformOperatorTokenProfile.cs | 6 + .../PlatformOperatorTokenValidator.cs | 5 + .../KeycloakRealmContinuitySource.cs | 96 +++++++++--- .../Program.cs | 48 +++++- .../RebindTool.cs | 27 +++- .../RebindToolInput.cs | 17 +- .../Bindings/IdentityIssuerRebind.cs | 128 ++++++++++----- .../Persistence/IdentityAuthorityRebindDdl.cs | 6 + .../AuthenticationAuthorityTests.Shapes.cs | 7 +- .../IdentityAuditConventionTests.cs | 22 ++- .../Database/GlobalIdentityUnitOfWorkTests.cs | 5 +- .../IdentityAuthorityRebindStorageTests.cs | 49 +++++- .../Database/IdentityAuthorityRebindTests.cs | 101 +++++++++++- .../IdentityMutationLockTests.Controls.cs | 8 +- .../Database/RebindProofSupport.cs | 4 +- .../FakeKeycloakRealm.cs | 68 ++++++-- .../KeycloakRealmContinuitySourceTests.cs | 69 ++++++++- .../PlatformOperatorTokenValidatorTests.cs | 27 +++- .../RebindToolInputTests.cs | 146 ++++++++++++++++++ .../KeycloakEnumerationTests.cs | 1 - .../PlatformOperatorAuthenticationTests.cs | 21 +++ .../Identity/IdentityRebindContinuityTests.cs | 23 +++ .../PlatformOperatorActCatalogTests.cs | 34 ++++ docs/architecture/23-data-protection.md | 9 +- .../0104-controlled-issuer-rebind.md | 76 ++++++--- docs/runbooks/identity-issuer-rebind.md | 124 ++++++++++----- docs/standards/05-database.md | 109 +++++++------ docs/standards/10-observability.md | 6 +- docs/standards/11-security.md | 21 ++- docs/standards/19-permissions.md | 7 +- .../21-architecture-tests-catalogue.md | 29 +++- infra/compose/README.md | 4 +- 35 files changed, 1067 insertions(+), 253 deletions(-) create mode 100644 backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs index 063e3a8e..0dea199e 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs @@ -86,7 +86,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( options.AutomaticRefreshInterval = PlatformOperatorValidation.AutomaticRefreshInterval; options.RefreshInterval = PlatformOperatorValidation.RefreshInterval; options.ConfigurationManager = PlatformOperatorValidation.CreateConfigurationManager( - settings, backchannel, health, loggerFactory.CreateLogger()); + settings, backchannel, health, loggerFactory.CreateLogger("LearnStack.Infrastructure.PlatformOperator.PlatformOperatorDocumentRetriever")); options.TokenValidationParameters = PlatformOperatorValidation.CreateParameters(settings); options.Events = new PlatformOperatorEvents(settings, clock, health, logger); }); diff --git a/backend/src/LearnStack.Infrastructure.Audit/IdentityRebindAuditInstaller.cs b/backend/src/LearnStack.Infrastructure.Audit/IdentityRebindAuditInstaller.cs index 31e03df1..dfa8314b 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/IdentityRebindAuditInstaller.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/IdentityRebindAuditInstaller.cs @@ -14,7 +14,9 @@ namespace LearnStack.Infrastructure.Audit; /// them, because a second permissive policy would combine with OR and widen every row. /// /// -/// The arm admits exactly the two rebind operations with their one outcome each, the platform sentinel tenant, the +/// The existing tenant arm is restated with the rebind role excluded from it: that arm admits whatever tenant a +/// session announces, any session can announce one, and a role whose row the policy is meant to bound must not be able +/// to widen it. The rebind arm admits exactly the two rebind operations with their one outcome each, the platform sentinel tenant, the /// identity module, no organization, no actor and no network or mail attribution, and an operator attribution in /// metadata. The role holds no SELECT, UPDATE or DELETE on the table, and the append-only /// guards are unchanged. @@ -40,7 +42,8 @@ public static void Install(MigrationBuilder migrationBuilder) ALTER POLICY audit_log_isolation ON public.audit_log WITH CHECK ( - (tenant_id = NULLIF(current_setting('app.tenant_id',true),'')::uuid + (current_user <> 'learnstack_identity_rebind' + AND tenant_id = NULLIF(current_setting('app.tenant_id',true),'')::uuid AND ((organization_id IS NULL AND NULLIF(current_setting('app.organization_id',true),'') IS NULL) OR organization_id = NULLIF(current_setting('app.organization_id',true),'')::uuid)) OR (current_user='learnstack_app' diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs index cfc7eda0..d702796b 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs @@ -18,14 +18,18 @@ public sealed class PlatformOperatorActCatalog { private readonly FrozenDictionary _acts; - /// Builds the catalog; every operation must be a registered one that needs no platform role. + /// + /// Builds the catalog; every operation must be a registered one that needs no platform role, and none may be the + /// controlled issuer rebind, which is an offline act on its own role and never a pipeline act (ADR-0104). + /// public PlatformOperatorActCatalog(IEnumerable> acts) { ArgumentNullException.ThrowIfNull(acts); var list = acts.ToList(); if (list.Count == 0 || list.Any(pair => pair.Key.IsAbstract || !PlatformOperations.IsRegistered(pair.Value.Operation) - || pair.Value.Operation.NeedsPlatformRole)) + || pair.Value.Operation.NeedsPlatformRole + || ReferenceEquals(pair.Value.Operation, PlatformOperations.IdentityAuthorityRebind))) { throw new ArgumentException("The operator act catalog needs registered operations that use the application role."); } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs index 98a3d2b3..5cc7b447 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs @@ -106,6 +106,12 @@ public static bool TryRead( witness = null; cause = default; + // Two executors exist and each is a constant: a caller cannot name another in an audit row's attribution. + if (executor is not (PlatformOperatorSettings.Executor or PlatformOperatorSettings.RebindToolExecutor)) + { + throw new ArgumentException("The executor is not a registered operator executor.", nameof(executor)); + } + // Stock validation already pinned the issuer; this restates it so the profile is // correct for any caller, including one that validated with other parameters. if (!string.Equals(token.Issuer, settings.Issuer, StringComparison.Ordinal)) diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs index 7e908972..8fead8da 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs @@ -126,6 +126,11 @@ public async Task ValidateAsync( { ArgumentException.ThrowIfNullOrWhiteSpace(executor); ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); + if (executor is not (PlatformOperatorSettings.Executor or PlatformOperatorSettings.RebindToolExecutor)) + { + throw new ArgumentException("The executor is not a registered operator executor.", nameof(executor)); + } + if (string.IsNullOrWhiteSpace(token)) { return PlatformOperatorValidationResult.Refused("token_missing"); diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs index be30fd07..96c2bf40 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs @@ -1,3 +1,4 @@ +using System.Net; using System.Net.Http.Headers; using System.Text; using System.Text.Json; @@ -17,15 +18,18 @@ namespace LearnStack.Tools.IdentityAuthorityRebind; /// followed, and a refusal is one fixed exception that names no address, credential or body. /// /// -/// The enumeration is complete or it is refused: the pages must add up to the reported count, and the count must be -/// the same before and after the pages were read, so a realm that changed while it was read is not a proof. +/// The enumeration is complete or it is refused: the pages must add up to the reported count with no repeated +/// subject, the count must be the same before and after, and a second full pass must report the same set, so a realm +/// that changed while it was read is not a proof. A token that expires mid-enumeration is acquired again once per +/// request, and a realm above is refused because its proof cannot finish in the tool's +/// deadline. /// /// internal sealed class KeycloakRealmContinuitySource(HttpClient client, string clientId, string clientSecret) : INewRealmContinuitySource { internal const int PageSize = 100; - internal const int MaximumUsers = 2_000_000; + internal const int MaximumUsers = 200_000; private const int MaximumDocumentBytes = 256 * 1024; private const int MaximumPageBytes = 4 * 1024 * 1024; private const int MaximumKeys = 1024; @@ -55,18 +59,34 @@ public async Task ReadAsync(string issuer, CancellationToken c var origin = new Uri(issuer); var realm = RealmOf(origin); var discovery = await ReadDiscoveryAsync(origin, cancellationToken); + if (!string.Equals(discovery.Issuer, issuer, StringComparison.Ordinal)) + { + // The realm names another issuer: the proof refuses on it, so neither the credential nor a user list + // is sent for or read from a realm that is not the target. + return new NewRealmSnapshot(discovery.Issuer, 0, false, []); + } + var keys = await CountKeysAsync(discovery.KeySet, cancellationToken); - var token = await ObtainTokenAsync(discovery.TokenEndpoint, cancellationToken); + var session = new AdminSession(discovery.TokenEndpoint); + session.Token = await ObtainTokenAsync(session.TokenEndpoint, cancellationToken); var admin = new Uri(origin, realm.AdminPath); - var before = await ReadCountAsync(admin, token, cancellationToken); - var subjects = await EnumerateAsync(admin, token, cancellationToken); - var after = await ReadCountAsync(admin, token, cancellationToken); - var complete = before == after && subjects.Count == before; - return new NewRealmSnapshot(discovery.Issuer, keys, complete, subjects); + var before = await ReadCountAsync(admin, session, cancellationToken); + var first = await EnumerateAsync(admin, session, cancellationToken); + var second = await EnumerateAsync(admin, session, cancellationToken); + var after = await ReadCountAsync(admin, session, cancellationToken); + var complete = before == after && first.Count == before && second.Count == before + && first.Distinct(StringComparer.Ordinal).Count() == first.Count + && first.Order(StringComparer.Ordinal).SequenceEqual(second.Order(StringComparer.Ordinal), StringComparer.Ordinal); + return new NewRealmSnapshot(discovery.Issuer, keys, complete, first); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // A request that timed out: refused like any transport failure. The run's own deadline propagates. + throw new NewRealmUnavailableException(); } catch (Exception failure) when (failure is HttpRequestException or IOException or JsonException - or InvalidOperationException or UriFormatException or TaskCanceledException or FormatException or ArgumentException + or InvalidOperationException or UriFormatException or FormatException or ArgumentException or KeyNotFoundException) { // One fixed refusal: no address, credential or body is carried out of the transport. @@ -118,24 +138,23 @@ private async Task ObtainTokenAsync(Uri endpoint, CancellationToken canc return string.IsNullOrEmpty(token) ? throw new InvalidOperationException() : token; } - private async Task ReadCountAsync(Uri admin, string token, CancellationToken cancellationToken) + private async Task ReadCountAsync(Uri admin, AdminSession session, CancellationToken cancellationToken) { - using var request = Authorized(new Uri(admin.AbsoluteUri + "/users/count"), token); - using var json = await SendAsync(request, 64, cancellationToken); + using var json = await SendAuthorizedAsync(new Uri(admin.AbsoluteUri + "/users/count"), 64, session, cancellationToken); return json.RootElement.ValueKind == JsonValueKind.Number && json.RootElement.TryGetInt32(out var count) && count is >= 0 and <= MaximumUsers ? count : throw new InvalidOperationException(); } - private async Task> EnumerateAsync(Uri admin, string token, CancellationToken cancellationToken) + private async Task> EnumerateAsync(Uri admin, AdminSession session, CancellationToken cancellationToken) { var subjects = new List(); for (var first = 0; first <= MaximumUsers; first += PageSize) { - using var request = Authorized( - new Uri(admin.AbsoluteUri + $"/users?first={first}&max={PageSize}&briefRepresentation=true"), token); - using var page = await SendAsync(request, MaximumPageBytes, cancellationToken); + using var page = await SendAuthorizedAsync( + new Uri(admin.AbsoluteUri + $"/users?first={first}&max={PageSize}&briefRepresentation=true"), + MaximumPageBytes, session, cancellationToken); if (page.RootElement.ValueKind != JsonValueKind.Array) { throw new InvalidOperationException(); @@ -158,19 +177,49 @@ private async Task> EnumerateAsync(Uri admin, string token, Cancell throw new InvalidOperationException(); } - private static HttpRequestMessage Authorized(Uri uri, string token) + /// + /// One administration read. A 401 means the token expired during a long enumeration, so a new one is + /// obtained and the same read is repeated once; a second 401 is a refusal. + /// + private async Task SendAuthorizedAsync( + Uri uri, int maximumBytes, AdminSession session, CancellationToken cancellationToken) { - var request = new HttpRequestMessage(HttpMethod.Get, uri); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return request; + for (var attempt = 0; ; attempt++) + { + using var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", session.Token); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + try + { + return await SendAsync(request, maximumBytes, cancellationToken); + } + catch (RealmUnauthorizedException) when (attempt == 0) + { + session.Token = await ObtainTokenAsync(session.TokenEndpoint, cancellationToken); + } + } + } + + private sealed class AdminSession(Uri tokenEndpoint) + { + internal Uri TokenEndpoint { get; } = tokenEndpoint; + + internal string Token { get; set; } = string.Empty; } + /// The administration API answered 401: the credential's token is no longer accepted. + private sealed class RealmUnauthorizedException() : IOException("Realm answer refused."); + private async Task SendAsync(HttpRequestMessage request, int maximumBytes, CancellationToken cancellationToken) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(Timeout); using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + throw new RealmUnauthorizedException(); + } + if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength > maximumBytes) { throw new IOException("Realm answer refused."); @@ -218,6 +267,7 @@ private static (string Name, string AdminPath) RealmOf(Uri issuer) throw new InvalidOperationException(); } - return (name, path[..at] + "/admin/realms/" + Uri.EscapeDataString(name)); + // The path of a Uri is already escaped, so the segment is used as it is and never escaped twice. + return (name, path[..at] + "/admin/realms/" + name); } } diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs index 95ff0126..10583420 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs @@ -1,38 +1,56 @@ +using System.Runtime.InteropServices; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Identity.Infrastructure.Bindings; using Microsoft.Extensions.Configuration; using OpenTelemetry; using OpenTelemetry.Metrics; -using LearnStack.Infrastructure.PlatformOperator; namespace LearnStack.Tools.IdentityAuthorityRebind; /// /// The controlled issuer rebind tool (ADR-0104). It takes every value from its environment and one line of standard -/// input, never an argument, and prints one fixed line. See docs/runbooks/identity-issuer-rebind.md. +/// input, never an argument, and prints one fixed line to standard output. See +/// docs/runbooks/identity-issuer-rebind.md. /// internal static class Program { - private const string UsageRefusal = "rebind: outcome=refused_input"; + private const string InputRefusal = "rebind: outcome=refused_input"; private static readonly TimeSpan Deadline = TimeSpan.FromMinutes(10); + private static readonly TimeSpan StandardInputWait = TimeSpan.FromSeconds(30); public static async Task Main(string[] args) { if (args.Length != 0) { - Console.Error.WriteLine(UsageRefusal); + Console.Out.WriteLine(InputRefusal); return RebindTool.Refused; } try { + using var deadline = new CancellationTokenSource(Deadline); + + // An interrupt ends the run the way the deadline does: through the token, so the run rolls back, the + // commit's outcome is still reconciled, and the one line is still printed. + Console.CancelKeyPress += (_, signal) => + { + signal.Cancel = true; + deadline.Cancel(); + }; + using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context => + { + context.Cancel = true; + deadline.Cancel(); + }); + var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); if (!RebindToolInput.TryRead( name => Environment.GetEnvironmentVariable(name), - () => Console.IsInputRedirected ? Console.In.ReadLine() : null, + ReadStandardInputLine, configuration, out var input)) { - Console.Error.WriteLine(UsageRefusal); + Console.Out.WriteLine(InputRefusal); return RebindTool.Refused; } @@ -42,7 +60,6 @@ public static async Task Main(string[] args) .AddMeter(IdentityRebindMetrics.MeterName, PlatformOperatorMetrics.MeterName) .AddOtlpExporter() .Build(); - using var deadline = new CancellationTokenSource(Deadline); using var client = KeycloakRealmContinuitySource.CreateClient(); var realm = new KeycloakRealmContinuitySource(client, input.RealmClientId, input.RealmClientSecret); var exit = await RebindTool.RunAsync(input, realm, Console.Out, deadline.Token); @@ -53,8 +70,23 @@ public static async Task Main(string[] args) catch (Exception) #pragma warning restore CA1031 { - Console.Error.WriteLine("rebind: outcome=refused_unexpected"); + Console.Out.WriteLine("rebind: outcome=refused_unexpected"); return RebindTool.Refused; } } + + /// + /// The operator token's line when it is piped: bounded in time, so a pipe that is never closed refuses the run + /// instead of holding it before its deadline exists. + /// + private static string? ReadStandardInputLine() + { + if (!Console.IsInputRedirected) + { + return null; + } + + var read = Task.Run(Console.In.ReadLine); + return read.Wait(StandardInputWait) ? read.Result : null; + } } diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs index 2b1ac075..cfbcc5c2 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs @@ -42,6 +42,8 @@ internal static class RebindTool internal static async Task RunAsync( RebindToolInput input, INewRealmContinuitySource realm, TextWriter output, CancellationToken cancellationToken) { + // One handle for every outcome from here on, so an operator can quote it whatever the run answered. + var correlation = "rebind-" + Guid.NewGuid().ToString("N"); PlatformOperatorSettings? settings; try { @@ -49,16 +51,35 @@ internal static async Task RunAsync( } catch (InvalidOperationException) { - return Refuse(output, "operator_configuration_invalid"); + return Refuse(output, "operator_configuration_invalid", correlation); } if (settings is null) { - return Refuse(output, "operator_issuer_not_configured"); + return Refuse(output, "operator_issuer_not_configured", correlation); + } + + try + { + return await RunAdmittedAsync(input, realm, output, settings, correlation, cancellationToken); } + catch (OperationCanceledException) + { + // The deadline or an interrupt ended the run before the database was touched, or the database half has + // already rolled back and reported it. + return Refuse(output, "cancelled", correlation); + } + } + private static async Task RunAdmittedAsync( + RebindToolInput input, + INewRealmContinuitySource realm, + TextWriter output, + PlatformOperatorSettings settings, + string correlation, + CancellationToken cancellationToken) + { var clock = new SystemClock(); - var correlation = "rebind-" + Guid.NewGuid().ToString("N"); using var backchannel = new PlatformOperatorBackchannel(); var health = new PlatformOperatorMetadataHealth(clock); var manager = PlatformOperatorValidation.CreateConfigurationManager(settings, backchannel, health, NullLogger.Instance); diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs index a832489a..9b12b71e 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs @@ -55,9 +55,11 @@ internal static bool TryRead( // The mode is explicit, as it is for the API: it decides whether a loopback operator issuer and the demo // operator's grant are admitted, so a tool that guessed it could admit what the API refuses. - if (!Enum.TryParse(environment("Deployment__Mode"), ignoreCase: false, out var mode) - || !Enum.IsDefined(mode)) + var modeText = environment("Deployment__Mode"); + if (string.IsNullOrEmpty(modeText) || !Enum.GetNames().Contains(modeText, StringComparer.Ordinal) + || !Enum.TryParse(modeText, ignoreCase: false, out var mode)) { + // Declared names only: an ordinal ("0") or a list would parse to a mode the API itself refuses. return false; } @@ -68,8 +70,15 @@ internal static bool TryRead( return false; } - var target = new IdentityAuthorityRegistration( - IdentityAuthorityId.From(authority), environment("Authentication__Tenant__Issuer")!); + var newIssuer = environment("Authentication__Tenant__Issuer")!; + var target = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authority), newIssuer); + if (mode != DeploymentMode.Development && new Uri(newIssuer).Scheme != Uri.UriSchemeHttps) + { + // Loopback HTTP is a Development transport only: a stored issuer no other mode's API accepts would be + // an outage, and the realm credential would travel in clear. + return false; + } + input = new RebindToolInput( connection, target, token.Trim(), string.IsNullOrWhiteSpace(ticket) ? null : ticket, clientId, clientSecret, mode, configuration, environment("OTEL_EXPORTER_OTLP_ENDPOINT")); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs index a34da74d..3bafe22d 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs @@ -86,7 +86,7 @@ private async Task RunCoreAsync( return Refused(IdentityRebindRefusal.NotAdmitted); } - var connection = Normalize(connectionString, lockWait); + var connection = TryNormalize(connectionString, lockWait); if (connection is null) { return Refused(IdentityRebindRefusal.RoleInvalid); @@ -154,6 +154,14 @@ await ExecuteAsync(main, transaction, AdvisoryLock, cancellationToken, IdentityRebindResult.Refused, IdentityRebindRefusal.ContinuityBroken, continuity, sessions); } + // The freeze is asked again at the last moment: the proof may have run for minutes. + var late = await CountRuntimeSessionsAsync(main, transaction, cancellationToken); + if (late > 0) + { + return new IdentityRebindOutcome( + IdentityRebindResult.Refused, IdentityRebindRefusal.LiveSessions, continuity, late); + } + await ChangeIssuerAsync(main, transaction, storedIssuer, target.Issuer, cancellationToken); await audit.WriteIdentityRebindResultAsync( Draft(admission, admission.Operation.AuditSlug, AuditOutcome.Success, storedAuthority, @@ -180,16 +188,28 @@ await audit.WriteIdentityRebindResultAsync( } finally { - // An uncommitted transaction rolls back here, and with it the lock. - if (transaction is not null) - { - await transaction.DisposeAsync(); - } + // An uncommitted transaction rolls back here, and with it the lock. A failure to dispose never replaces + // the outcome of the run: an applied rebind must not be reported as an exception. + await DisposeQuietlyAsync(transaction); + await DisposeQuietlyAsync(main); + } + } - if (main is not null) - { - await main.DisposeAsync(); - } + private static async ValueTask DisposeQuietlyAsync(IAsyncDisposable? resource) + { + if (resource is null) + { + return; + } + + try + { + await resource.DisposeAsync(); + } +#pragma warning disable CA1031 // Cleanup never replaces the outcome of the run. + catch (Exception) +#pragma warning restore CA1031 + { } } @@ -212,8 +232,14 @@ private static async Task CommitAsync( // the target means it applied, the old value means it did not, and anything else is not guessed at. try { + // The shared form of the lock, under the connection's own lock_timeout: it is granted only once the + // original transaction has ended, so the read cannot see the issuer before an in-flight COMMIT lands. await using var reader = await OpenAsync(connection, CancellationToken.None); - await using var command = new NpgsqlCommand("SELECT issuer FROM public.identity_authority WHERE id = 1", reader); + await using var check = await reader.BeginTransactionAsync(IsolationLevel.ReadCommitted, CancellationToken.None); + await ExecuteAsync(reader, check, "SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", CancellationToken.None, + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + await using var command = new NpgsqlCommand( + "SELECT issuer FROM public.identity_authority WHERE id = 1", reader, check); var current = (string?)await command.ExecuteScalarAsync(CancellationToken.None); if (string.Equals(current, newIssuer, StringComparison.Ordinal)) { @@ -231,10 +257,19 @@ private static async Task CommitAsync( } } - /// Normalizes the connection string, or null when it is not the rebind role's. - private static string? Normalize(string connectionString, TimeSpan lockWait) + /// Normalizes the connection string, or null when it is malformed or not the rebind role's. + private static string? TryNormalize(string connectionString, TimeSpan lockWait) { - var builder = new NpgsqlConnectionStringBuilder(connectionString); + NpgsqlConnectionStringBuilder builder; + try + { + builder = new NpgsqlConnectionStringBuilder(connectionString); + } + catch (ArgumentException) + { + return null; + } + if (!string.Equals(builder.Username, RoleName, StringComparison.Ordinal)) { return null; @@ -251,6 +286,11 @@ private static async Task CommitAsync( builder.Timeout = 15; builder.CommandTimeout = 120; builder.ApplicationName = "learnstack-identity-rebind"; + + // The main connection sits idle in its transaction while the new realm is read, so keep it alive through + // middleboxes that cut a quiet connection. + builder.TcpKeepAlive = true; + builder.KeepAlive = 30; builder.Options = FormattableString.Invariant( $"-c lock_timeout={(int)Math.Max(1, lockWait.TotalMilliseconds)} -c statement_timeout=120000 -c idle_in_transaction_session_timeout=900000"); return builder.ConnectionString; @@ -273,31 +313,45 @@ private static async Task OpenAsync(string connectionString, C /// /// The role is exactly what the migration granted: itself, no attribute that escalates, no membership either way, - /// no privilege on any other table, and the one column it may change. + /// no privilege on any other relation, and on the three it uses exactly the declared table and column grants. /// private static async Task HasExactPostureAsync(NpgsqlConnection connection, CancellationToken cancellationToken) { await using var command = new NpgsqlCommand( """ - SELECT session_user::text, current_user::text, r.rolcanlogin, r.rolinherit, r.rolbypassrls, r.rolsuper, - r.rolcreatedb, r.rolcreaterole, r.rolreplication, - EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR m.roleid = r.oid), - has_schema_privilege(r.oid, 'public', 'CREATE'), - has_database_privilege(r.oid, current_database(), 'CREATE'), + SELECT (session_user::text = current_user::text AND current_user::text = @role) AS session_ok, + (r.rolcanlogin AND NOT r.rolinherit AND NOT r.rolbypassrls AND NOT r.rolsuper + AND NOT r.rolcreatedb AND NOT r.rolcreaterole AND NOT r.rolreplication) AS attributes_ok, + NOT EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR m.roleid = r.oid) AS no_membership, + NOT (has_schema_privilege(r.oid, 'public', 'CREATE') + OR has_database_privilege(r.oid, current_database(), 'CREATE')) AS no_creation, (SELECT count(*) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'f') AND c.relname NOT IN ('identity_authority', 'users', @audit) - AND has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES')), - has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES'), - has_column_privilege(r.oid, 'public.users', 'id', 'SELECT,UPDATE,REFERENCES'), - has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,DELETE,TRUNCATE,TRIGGER,REFERENCES'), - has_column_privilege(r.oid, 'public.identity_authority', 'authority_id', 'UPDATE,INSERT,REFERENCES'), - has_column_privilege(r.oid, 'public.identity_authority', 'id', 'UPDATE,INSERT,REFERENCES'), - has_column_privilege(r.oid, 'public.identity_authority', 'issuer', 'UPDATE'), - has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES'), - has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), 'INSERT') + AND (has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') + OR has_table_privilege(r.oid, c.oid, 'DELETE,TRUNCATE,TRIGGER'))) AS stray_relations, + (SELECT count(*) FROM pg_catalog.pg_attribute a + JOIN pg_catalog.pg_class c ON c.oid = a.attrelid + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND a.attnum > 0 AND NOT a.attisdropped AND ( + (c.relname = 'users' + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT,UPDATE,REFERENCES') + OR has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT') + <> (a.attname IN ('authority_id', 'subject_key', 'provider_subject', 'status')))) + OR (c.relname = 'identity_authority' + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT,REFERENCES') + OR NOT has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT') + OR has_column_privilege(r.oid, c.oid, a.attnum, 'UPDATE') <> (a.attname = 'issuer'))) + OR (c.relname = @audit + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT,UPDATE,REFERENCES') + OR NOT has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT'))))) AS column_drift, + NOT (has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES') + OR has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES') + OR has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), + 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES')) AS no_table_grants FROM pg_catalog.pg_roles r WHERE r.rolname = current_user """, connection); + command.Parameters.AddWithValue("role", RoleName); command.Parameters.AddWithValue("audit", IdentityRebindAuditInstaller.Table); await using var reader = await command.ExecuteReaderAsync(cancellationToken); if (!await reader.ReadAsync(cancellationToken)) @@ -305,16 +359,10 @@ AND has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES')), return false; } - return reader.GetString(0) == RoleName && reader.GetString(1) == RoleName - && reader.GetBoolean(2) - && !reader.GetBoolean(3) && !reader.GetBoolean(4) && !reader.GetBoolean(5) - && !reader.GetBoolean(6) && !reader.GetBoolean(7) && !reader.GetBoolean(8) - && !reader.GetBoolean(9) && !reader.GetBoolean(10) && !reader.GetBoolean(11) - && reader.GetInt64(12) == 0 - && !reader.GetBoolean(13) && !reader.GetBoolean(14) - && !reader.GetBoolean(15) && !reader.GetBoolean(16) && !reader.GetBoolean(17) - && reader.GetBoolean(18) - && !reader.GetBoolean(19) && reader.GetBoolean(20); + bool Flag(string column) => reader.GetBoolean(reader.GetOrdinal(column)); + long Count(string column) => reader.GetInt64(reader.GetOrdinal(column)); + return Flag("session_ok") && Flag("attributes_ok") && Flag("no_membership") && Flag("no_creation") + && Count("stray_relations") == 0 && Count("column_drift") == 0 && Flag("no_table_grants"); } private static async Task<(Guid Authority, string Issuer)> ReadAuthorityAsync( @@ -400,7 +448,7 @@ private static async Task> ReadUsersAsync( var users = new List(); while (await reader.ReadAsync(cancellationToken)) { - if (!Enum.TryParse(reader.GetString(2), ignoreCase: false, out var status)) + if (!Enum.TryParse(reader.GetString(2), ignoreCase: false, out var status) || !Enum.IsDefined(status)) { throw new InvalidOperationException("A stored user has a status this rebind does not know."); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs index f7269e16..08d70d60 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs @@ -27,6 +27,12 @@ internal static class IdentityAuthorityRebindDdl internal static void Add(MigrationBuilder migration) { migration.Sql(""" + DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'learnstack_identity_rebind') THEN + RAISE EXCEPTION 'The issuer-rebind storage requires the learnstack_identity_rebind role; apply infra/compose/postgres-init/02-create-roles.sql with LEARNSTACK_IDENTITY_REBIND_PW set, then migrate again.' USING ERRCODE='23514'; + END IF; + END $$; + GRANT SELECT ON public.identity_authority TO learnstack_identity_rebind; GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind; GRANT SELECT (authority_id, subject_key, provider_subject, status) ON public.users TO learnstack_identity_rebind; diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 81d63219..7ee15dbd 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -365,8 +365,13 @@ private static bool IsClosedInvitationForwarding(Method method, Instruction inst /// private static bool IsOperatorTokenProfileRead(Call call) => call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenProfile" && call.Source.Name == "TryRead" + // Exact members, so a later edit that reads a claim, a role or an identity in the validator is still flagged: + // the stock handler's validation call and the three members of its result the decision needs. || call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenValidator" - && call.Source.Name is "ValidateAsync" or ".cctor"; + && (call.Source.Name == "ValidateAsync" + && call.Target.Name is "ValidateTokenAsync" or "get_IsValid" or "get_Exception" or "get_SecurityToken" + || call.Source.Name == ".cctor" + && call.Target.Name is ".ctor" or "set_MapInboundClaims"); private static bool IsClosedRolesAbsenceCheck(Call call) { diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs index 938c7c06..85caaf69 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs @@ -106,15 +106,33 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m finally { definition.Body.Instructions.Remove(extraFrameworkRead); } } + [Fact] + public void The_Operator_Token_Validator_Has_Two_Callers_Of_The_Profile_And_One_Of_Its_Own() + { + // ADR-0101 § 7: the witness comes from one validator with two callers. The API scheme reads a token through the + // profile from its validated event; the offline validator reads one through the stock handler and then the + // profile; and the offline validator is constructed and called by the rebind tool alone, so no endpoint, job or + // module adapter can mint a witness by borrowing it. + const string Profile = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenProfile"; + const string Validator = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenValidator"; + Callers(Profile, "TryRead").Should().Equal( + "LearnStack.Api.Authentication.PlatformOperatorEvents.TokenValidated", + Validator + ".ValidateAsync"); + Callers(Validator, "ValidateAsync").Should().Equal("LearnStack.Tools.IdentityAuthorityRebind.RebindTool.RunAdmittedAsync"); + Callers(Validator, ".ctor").Should().Equal("LearnStack.Tools.IdentityAuthorityRebind.RebindTool.RunAdmittedAsync"); + } + [Fact] public void Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock() { - // ADR-0104 § 5: the exclusive form belongs to the rebind run and the shared form to authority qualification and - // the User-creation admission. A fourth taker is a fourth party that can wait on, or hold, the freeze. + // ADR-0104 § 5: the exclusive form belongs to the rebind run, and the shared form to authority qualification, the + // User-creation admission and the run's own reconciliation of an unknown COMMIT, which waits for the original + // transaction behind it. A further taker is a further party that can wait on, or hold, the freeze. Callers(typeof(IdentityAdvisoryLockKey).FullName!, nameof(IdentityAdvisoryLockKey.ForAuthorityRebind)) .Should().Equal( "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync", "LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityAuthorityQualification.QualifyCoreAsync", + RebindRun + ".CommitAsync", RebindRun + ".RunCoreAsync"); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs index 29dae3ef..5d9f02c1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs @@ -17,9 +17,10 @@ namespace LearnStack.Tests.Integration.Database; [Collection(SharedSchema.Name)] public sealed class GlobalIdentityUnitOfWorkTests(SchemaFixture schema) { + // The authority the shared schema fixture installed: a creation owner reads the stored authority and issuer after the + // rebind lock (ADR-0104 § 5), so a subject under any other pair is a process that qualified against other facts. private static readonly GlobalIdentitySubject Subject = new( - IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501")), - "https://identity.example/realms/learnstack", "unit-owner-proof-subject"); + IdentityMembershipFixture.Authority.AuthorityId, IdentityMembershipFixture.Authority.Issuer, "unit-owner-proof-subject"); [Fact] public async Task Read_only_global_owner_announces_only_self_authority_and_clears_unrelated_session_values() diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs index 499a4260..be3efd5b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs @@ -207,6 +207,8 @@ public async Task The_Role_Inserts_The_Two_Rebind_Rows_And_Nothing_Else_Into_The ("another reason", AuditInsert(Row(reason: "host_map"))), ("an actor", AuditInsert(Row(actor: Guid.CreateVersion7().ToString("D")))), ("a mail address", AuditInsert(Row(email: "operator@example.test"))), + ("a network address", AuditInsert(Row(ip: "203.0.113.7"))), + ("a user agent", AuditInsert(Row(agent: "rebind-tool"))), ("no operator attribution", AuditInsert(Row(metadata: "{}"))), }; foreach (var (why, insert) in refused) @@ -232,6 +234,42 @@ public async Task The_Role_Inserts_The_Two_Rebind_Rows_And_Nothing_Else_Into_The } } + [Fact] + public async Task The_Role_Cannot_Widen_Its_Row_By_Announcing_A_Tenant_Of_Its_Own_Choosing() + { + // Any session can set the tenant setting the ordinary arm reads, so the arm must not admit this role at all: + // otherwise the policy that is meant to bound the role's rows would be whatever the role announced. + await using var proof = await Proof.CreateAsync(parent); + var victim = Guid.CreateVersion7().ToString("D"); + + foreach (var (why, tenant, operation, module) in new[] + { + ("a tenant's own trail", victim, "tenancy.tenant.suspend", "tenancy"), + ("the sentinel under another operation", Sentinel, "platform.killswitch.toggle", "platform"), + ("the sentinel under an identity operation", Sentinel, "identity.role.initialize", "identity"), + }) + { + var announce = $"SELECT set_config('app.tenant_id', '{tenant}', true); "; + var insert = AuditInsert(Row(tenant: tenant, module: module, operation: operation, outcome: "success")); + (await proof.Rebind.RefusalAsync(announce + insert)).Should().Be("42501", why); + } + } + + [Fact] + public async Task The_Rebind_Arm_Admits_The_Rebind_Role_And_No_Other_Role() + { + // The owner holds the privilege and no tenant or application arm applies to it, so only the role predicate of + // the rebind arm stands between it and a platform-sentinel row of exactly the admitted shape. + await using var proof = await Proof.CreateAsync(parent); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await using var command = new NpgsqlCommand(AuditInsert(Row()), owner, transaction); + + var act = async () => await command.ExecuteNonQueryAsync(); + + (await act.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + } + [Fact] public async Task The_Application_And_Ingress_Roles_Cannot_Write_The_Rebind_Rows() { @@ -271,9 +309,11 @@ private static string Row( string operation = "identity.authority.rebind_attempt", string operationType = "SecurityEvent", string operationClass = "Must", string entityType = "IdentityAuthority", string outcome = "indeterminate", string reason = "issuer_rebind", string? actor = null, string? email = null, - string metadata = """{"operator":{"issuer":"https://operator.example.test/realms/learnstack-hub"}}""") => + string metadata = """{"operator":{"issuer":"https://operator.example.test/realms/learnstack-hub"}}""", + string? ip = null, string? agent = null) => string.Join('\u001f', tenant, organization ?? string.Empty, module, operation, operationType, operationClass, - entityType, outcome, reason, actor ?? string.Empty, email ?? string.Empty, metadata); + entityType, outcome, reason, actor ?? string.Empty, email ?? string.Empty, metadata, ip ?? string.Empty, + agent ?? string.Empty); private static string AuditInsert(string row) { @@ -282,9 +322,10 @@ private static string AuditInsert(string row) return $""" INSERT INTO public.audit_log (id, tenant_id, organization_id, actor_user_id, actor_email, module, operation, operation_type, - operation_class, entity_type, entity_id, outcome, reason, metadata, timestamp) + operation_class, entity_type, entity_id, outcome, reason, metadata, ip_address, user_agent, timestamp) VALUES (uuidv7(), '{f[0]}', {Nullable(f[1])}, {Nullable(f[9])}, {Nullable(f[10])}, '{f[2]}', '{f[3]}', '{f[4]}', - '{f[5]}', '{f[6]}', 'authority', '{f[7]}', '{f[8]}', '{f[11]}'::jsonb, now()) + '{f[5]}', '{f[6]}', 'authority', '{f[7]}', '{f[8]}', '{f[11]}'::jsonb, + {(f[12].Length == 0 ? "NULL" : $"'{f[12]}'::inet")}, {Nullable(f[13])}, now()) """; } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs index 6d91739b..f9070b36 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs @@ -114,6 +114,23 @@ public async Task Any_Role_But_The_Rebind_Role_Is_Refused_Before_Its_First_State [InlineData(false, "GRANT SELECT (id) ON public.users TO learnstack_identity_rebind", "REVOKE SELECT (id) ON public.users FROM learnstack_identity_rebind")] [InlineData(false, "GRANT SELECT ON public.audit_log TO learnstack_identity_rebind", "REVOKE SELECT ON public.audit_log FROM learnstack_identity_rebind")] [InlineData(false, "GRANT CREATE ON SCHEMA public TO learnstack_identity_rebind", "REVOKE CREATE ON SCHEMA public FROM learnstack_identity_rebind")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind CREATEROLE", "ALTER ROLE learnstack_identity_rebind NOCREATEROLE")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind REPLICATION", "ALTER ROLE learnstack_identity_rebind NOREPLICATION")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind BYPASSRLS", "ALTER ROLE learnstack_identity_rebind NOBYPASSRLS")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind SUPERUSER", "ALTER ROLE learnstack_identity_rebind NOSUPERUSER")] + [InlineData(true, "GRANT learnstack_identity_rebind TO learnstack_app", "REVOKE learnstack_identity_rebind FROM learnstack_app")] + [InlineData(false, "GRANT UPDATE (status) ON public.users TO learnstack_identity_rebind", "REVOKE UPDATE (status) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (deleted_by) ON public.users TO learnstack_identity_rebind", "REVOKE SELECT (deleted_by) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (id) ON public.identity_authority TO learnstack_identity_rebind", "REVOKE UPDATE (id) ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT INSERT ON public.identity_authority TO learnstack_identity_rebind", "REVOKE INSERT ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (before_state) ON public.audit_log TO learnstack_identity_rebind", "REVOKE SELECT (before_state) ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (outcome) ON public.audit_log TO learnstack_identity_rebind", "REVOKE UPDATE (outcome) ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT DELETE ON public.tenants TO learnstack_identity_rebind", "REVOKE DELETE ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT TRUNCATE ON public.tenants TO learnstack_identity_rebind", "REVOKE TRUNCATE ON public.tenants FROM learnstack_identity_rebind")] + // A declared grant that is missing is drift too: the proof reads users through four columns and changes one. + [InlineData(false, "REVOKE UPDATE (issuer) ON public.identity_authority FROM learnstack_identity_rebind", "GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind")] + [InlineData(false, "REVOKE INSERT ON public.audit_log FROM learnstack_identity_rebind", "GRANT INSERT ON public.audit_log TO learnstack_identity_rebind")] + [InlineData(false, "REVOKE SELECT (status) ON public.users FROM learnstack_identity_rebind", "GRANT SELECT (status) ON public.users TO learnstack_identity_rebind")] public async Task A_Role_That_Holds_Anything_Beyond_Its_Grants_Is_Refused_Before_The_Lock(bool clusterWide, string escalate, string restore) { await using var proof = await Proof.CreateAsync(parent, active: 1); @@ -202,7 +219,7 @@ public async Task A_Live_Session_Of_A_Runtime_Role_Freezes_The_Rebind_And_Its_Di int? seen; await using (var session = await proof.OpenSessionAsync(role)) { - var refused = await proof.RunAsync(admission, realm); + var refused = await proof.RunAsync(admission, realm, settle: false); refused.Refusal.Should().Be(IdentityRebindRefusal.LiveSessions); seen = refused.LiveSessions; } @@ -306,7 +323,7 @@ public async Task A_Forced_Audit_Failure_Rolls_The_Issuer_Change_Back() } [Fact] - public async Task A_Run_Killed_Between_The_Intent_Row_And_The_Main_Transaction_Leaves_The_Intent_And_No_Change() + public async Task A_Run_Cancelled_During_The_Realm_Read_Leaves_The_Intent_Row_And_No_Change() { await using var proof = await Proof.CreateAsync(parent, active: 1); var admission = RebindProofSupport.Admit(); @@ -325,6 +342,61 @@ public async Task A_Run_Killed_Between_The_Intent_Row_And_The_Main_Transaction_L (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); } + [Fact] + public async Task An_Intent_Row_That_Cannot_Be_Written_Refuses_The_Run_Before_Any_Proof() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + + var outcome = await proof.RunAsync(admission, realm, configure: store => store.FailIntent = true); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuditFailed); + realm.Reads.Should().Be(0, "an attempt that cannot be recorded is not made"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().BeEmpty(); + } + + [Fact] + public async Task A_Database_That_Cannot_Be_Reached_And_A_Malformed_Connection_String_Are_Refused_Without_A_Throw() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var closedPort = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Host = "127.0.0.1", Port = 1, Timeout = 2 }.ConnectionString; + + (await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: closedPort)) + .Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); + (await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: "Host=;;=Username")) + .Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + } + + [Fact] + public async Task A_Commit_Reconciliation_Waits_For_The_Original_Transaction_And_Never_Reports_A_False_Unchanged() + { + // The session dies at COMMIT and something still holds the rebind lock when the run asks what became of it: the + // answer is not knowable yet, so the run says so instead of reading the old issuer and claiming "unchanged". + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + IAsyncDisposable? held = null; + try + { + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), lockWait: TimeSpan.FromSeconds(1), + configure: store => store.AfterResult = async connection => + { + await parent.Postgres.ExecuteAsSuperuserAsync( + $"SELECT pg_terminate_backend({((NpgsqlConnection)connection).ProcessID})"); + held = await proof.HoldRebindLockAsync(); + }); + + outcome.Result.Should().Be(IdentityRebindResult.Unknown); + } + finally + { + if (held is not null) await held.DisposeAsync(); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + [Fact] public async Task A_Session_Killed_Before_Commit_Is_Reconciled_As_Not_Applied() { @@ -443,8 +515,12 @@ internal async Task RunAsync( IdentityAuthorityRegistration? target = null, TimeSpan? lockWait = null, Action? configure = null, + bool settle = true, CancellationToken cancellation = default) { + // A session this test's own reads opened is gone before the next run asks the freeze question, unless the + // test keeps one open on purpose and says so. + if (settle) await SettleAsync(); await using var scope = RebindProofSupport.Store(); var store = new FaultingAuditStore(scope.ServiceProvider.GetRequiredService()); configure?.Invoke(store); @@ -458,13 +534,32 @@ internal async Task RunAsync( internal async Task AuthorityAsync() => await ReadAsync("SELECT authority_id FROM public.identity_authority"); + // Read as the owner: the owner is not a runtime role, so a read between two runs is never a session the freeze counts. private async Task ReadAsync(string sql) { - await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); await using var command = new NpgsqlCommand(sql, connection); return (T)(await command.ExecuteScalarAsync())!; } + /// Waits until no session of a runtime role is left on the database, as a stopped fleet leaves none. + internal async Task SettleAsync() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + var deadline = System.Diagnostics.Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(15)) + { + var remaining = await IdentityMembershipFixture.ScalarAsync(owner, null, + """ + SELECT count(*) FROM pg_catalog.pg_stat_activity + WHERE datname = current_database() AND pid <> pg_catalog.pg_backend_pid() + AND usename IN ('learnstack_app', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_platform') + """); + if (remaining == 0) return; + await Task.Delay(50); + } + } + internal async Task> UsersAsync() { await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs index 7daa7e18..6d678129 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs @@ -159,8 +159,8 @@ await FluentActions.Awaiting(() => firstHelper.AcquireAsync(new([], Tenant, Iden [Fact] public async Task Actual_global_subject_acquisition_emits_a_positive_finite_measurement_and_releases_on_rollback() { - var subject = new GlobalIdentitySubject(IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-00000000f001")), - "https://lock-metrics.invalid/realms/learnstack", "subject-canary-must-not-be-a-metric-tag"); + var subject = new GlobalIdentitySubject(IdentityMembershipFixture.Authority.AuthorityId, + IdentityMembershipFixture.Authority.Issuer, "subject-canary-must-not-be-a-metric-tag"); await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); await using var unit = Unit(source); var descriptor = SubjectSignalMint.Create(subject); @@ -269,10 +269,10 @@ private void AssertFinite() signal.Instrument.Should().BeOneOf("learnstack_identity_lock_wait_seconds", "learnstack_identity_lock_refusals_total"); signal.Tags.Keys.Should().BeEquivalentTo(signal.Instrument == "learnstack_identity_lock_wait_seconds" ? WaitTagNames : RefusalTagNames); - signal.Tags["lock_kind"].Should().BeOneOf("subject", "user", "tenant"); + signal.Tags["lock_kind"].Should().BeOneOf("subject", "user", "tenant", "authority"); if (signal.Instrument == "learnstack_identity_lock_wait_seconds") signal.Tags["outcome"].Should().BeOneOf("acquired", "timeout", "cancelled", "fault"); - else signal.Tags["reason"].Should().BeOneOf("timeout", "cancelled", "fault"); + else signal.Tags["reason"].Should().BeOneOf("timeout", "cancelled", "fault", "mismatch"); } } private void Record(Instrument instrument, double value, ReadOnlySpan> tags) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs index af64039d..a5ea46f9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs @@ -70,15 +70,15 @@ internal static FixedRealm Failing() => /// The real store, with seams at the two points a crash or an outage would strike. internal sealed class FaultingAuditStore(IAuditStore inner) : IAuditStore { - internal Func? AfterIntent { get; set; } internal Func? AfterResult { get; set; } + internal bool FailIntent { get; set; } internal bool FailResult { get; set; } public async Task WriteIdentityRebindIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) { + if (FailIntent) throw new AuditWriteFailedException("forced intent failure"); await inner.WriteIdentityRebindIntentAsync(entry, admission, connection, transaction, cancellationToken); - if (AfterIntent is not null) await AfterIntent(connection); } public async Task WriteIdentityRebindResultAsync(AuditEntryDraft entry, PlatformAdmission admission, diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs index 31748dcd..7a2b6edd 100644 --- a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -22,6 +22,8 @@ internal sealed class FakeKeycloakRealm : IAsyncDisposable private readonly HttpClient _client; private string? _failure; private int _pages; + private int _firstPageRequests; + private string _prefix = string.Empty; private FakeKeycloakRealm(WebApplication app, List users) { @@ -52,20 +54,21 @@ private FakeKeycloakRealm(WebApplication app, List users) internal List AdminAuthorization { get; } = []; - internal static Task StartAsync(int users) => - StartAsync(Enumerable.Range(0, users).Select(_ => Guid.NewGuid().ToString("D"))); + internal static Task StartAsync(int users, string prefix = "") => + StartAsync(Enumerable.Range(0, users).Select(_ => Guid.NewGuid().ToString("D")), prefix); - internal static async Task StartAsync(IEnumerable users) + /// Starts the realm; puts it behind a path such as /auth, as older Keycloaks were. + internal static async Task StartAsync(IEnumerable users, string prefix = "") { var builder = WebApplication.CreateBuilder(); builder.Logging.ClearProviders(); builder.WebHost.UseKestrel(options => options.Listen(IPAddress.Loopback, 0)); var app = builder.Build(); - var realm = new FakeKeycloakRealm(app, users.ToList()); + var realm = new FakeKeycloakRealm(app, users.ToList()) { _prefix = prefix }; realm.Map(app); await app.StartAsync(); var origin = app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); - realm.Issuer = origin + "/realms/learnstack"; + realm.Issuer = origin + prefix + "/realms/learnstack"; return realm; } @@ -76,7 +79,7 @@ internal Task ReadAsync() => private void Map(WebApplication app) { - app.MapGet("/realms/learnstack/.well-known/openid-configuration", context => + app.MapGet(_prefix + "/realms/learnstack/.well-known/openid-configuration", context => { if (_failure == "discovery-redirect") { @@ -98,13 +101,13 @@ private void Map(WebApplication app) token_endpoint = token, })); }); - app.MapGet("/realms/learnstack/keys", context => + app.MapGet(_prefix + "/realms/learnstack/keys", context => { context.Response.ContentType = "application/json"; return context.Response.WriteAsync( """{"keys":[{"kty":"RSA","kid":"a","use":"sig"},{"kty":"RSA","kid":"b"},{"kty":"RSA","kid":"c","use":"enc"}]}"""); }); - app.MapPost("/realms/learnstack/protocol/openid-connect/token", async context => + app.MapPost(_prefix + "/realms/learnstack/protocol/openid-connect/token", async context => { var form = await context.Request.ReadFormAsync(); TokenRequests.Add(form.ToDictionary(pair => pair.Key, pair => pair.Value.ToString())); @@ -115,13 +118,21 @@ private void Map(WebApplication app) } context.Response.ContentType = "application/json"; + // The first token is the one an enumeration outlives when "token-expires" is set; the second is accepted. + var issued = TokenRequests.Count; await context.Response.WriteAsync(_failure == "oversized-token-answer" ? "{\"access_token\":\"" + new string('x', 300 * 1024) + "\"}" - : """{"access_token":"realm-token"}"""); + : "{\"access_token\":\"" + (issued >= 2 && _failure == "token-expires" ? "realm-token-2" : "realm-token") + "\"}"); }); - app.MapGet("/admin/realms/learnstack/users/count", context => + app.MapGet(_prefix + "/admin/realms/learnstack/users/count", context => { AdminAuthorization.Add(context.Request.Headers.Authorization); + if (Unauthorized(context)) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + if (_failure == "admin-denied") { context.Response.StatusCode = StatusCodes.Status403Forbidden; @@ -136,9 +147,15 @@ await context.Response.WriteAsync(_failure == "oversized-token-answer" var count = Pages > 0 && CountAfterRead is { } later ? later : ReportedCount ?? Users.Count; return context.Response.WriteAsync(count.ToString(System.Globalization.CultureInfo.InvariantCulture)); }); - app.MapGet("/admin/realms/learnstack/users", context => + app.MapGet(_prefix + "/admin/realms/learnstack/users", context => { AdminAuthorization.Add(context.Request.Headers.Authorization); + if (Unauthorized(context)) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + Interlocked.Increment(ref _pages); if (_failure == "users-redirect") { @@ -155,13 +172,40 @@ await context.Response.WriteAsync(_failure == "oversized-token-answer" var first = int.Parse(context.Request.Query["first"]!, System.Globalization.CultureInfo.InvariantCulture); var max = int.Parse(context.Request.Query["max"]!, System.Globalization.CultureInfo.InvariantCulture); - var page = Users.Skip(first).Take(max).Select(id => _failure == "user-without-id" + if (first == 0) + { + Interlocked.Increment(ref _firstPageRequests); + } + + var users = Users.ToList(); + if (_failure == "duplicate-user" && users.Count > 1) + { + // A user is served twice and another never is, with the count unchanged. + users[^1] = users[0]; + } + + if (_failure == "second-pass-differs" && Volatile.Read(ref _firstPageRequests) >= 2 && users.Count > 0) + { + // A different user at the start of the second pass: the realm changed between the two reads. + users[0] = Guid.NewGuid().ToString("D"); + } + + var page = users.Skip(first).Take(max).Select(id => _failure == "user-without-id" ? (object)new { username = id } : new { id, username = "user-" + id }); return context.Response.WriteAsync(JsonSerializer.Serialize(page)); }); } + // "token-expires": the first token stops being accepted once any admin call has been made with it, as a short-lived + // one does mid-enumeration; "always-unauthorized": no token is ever accepted. + private bool Unauthorized(HttpContext context) + { + var header = context.Request.Headers.Authorization.ToString(); + return _failure == "always-unauthorized" + || (_failure == "token-expires" && header == "Bearer realm-token" && AdminAuthorization.Count > 2); + } + public async ValueTask DisposeAsync() { _client.Dispose(); diff --git a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs index 7095d4a3..1b350364 100644 --- a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs @@ -35,8 +35,8 @@ public async Task Every_User_Of_Every_Page_Is_Reported_And_The_Snapshot_Is_Compl snapshot.DiscoveredIssuer.Should().Be(realm.Issuer); snapshot.SigningKeyCount.Should().Be(2, "only signature keys count, an encryption key does not"); snapshot.Subjects.Should().BeEquivalentTo(realm.Users); - realm.Pages.Should().Be(users / KeycloakRealmContinuitySource.PageSize + 1, - "a page shorter than the page size ends the enumeration, and an exact multiple needs one empty page"); + realm.Pages.Should().Be(2 * (users / KeycloakRealmContinuitySource.PageSize + 1), + "two full passes, each ended by a page shorter than the page size, an exact multiple needing one empty page"); } [Fact] @@ -66,6 +66,60 @@ public async Task A_Realm_That_Changes_While_It_Is_Read_Is_Not_Complete() snapshot.Complete.Should().BeFalse("the count before and after the pages differ"); } + [Fact] + public async Task A_User_Served_Twice_And_Another_Never_Is_Not_Complete_Although_The_Count_Matches() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("duplicate-user"); + + (await realm.ReadAsync()).Complete.Should().BeFalse(); + } + + [Fact] + public async Task A_Realm_That_Reports_Another_Set_On_The_Second_Pass_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("second-pass-differs"); + + (await realm.ReadAsync()).Complete.Should().BeFalse("a user deleted and another created between the passes keeps the count"); + } + + [Fact] + public async Task A_Token_That_Expires_During_The_Enumeration_Is_Obtained_Again_Once_And_The_Read_Completes() + { + await using var realm = await FakeKeycloakRealm.StartAsync(250); + realm.Fail("token-expires"); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + realm.TokenRequests.Should().HaveCount(2, "one more token, not one per request"); + realm.AdminAuthorization.Should().Contain("Bearer realm-token-2"); + } + + [Fact] + public async Task A_Credential_That_Is_Refused_Even_With_A_New_Token_Is_A_Refusal_After_One_Retry() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("always-unauthorized"); + + var act = async () => await realm.ReadAsync(); + + await act.Should().ThrowAsync(); + realm.TokenRequests.Should().HaveCount(2); + } + + [Fact] + public async Task A_Path_Prefixed_Issuer_Reads_Its_Own_Administration_Path() + { + await using var realm = await FakeKeycloakRealm.StartAsync(3, prefix: "/auth"); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + snapshot.Subjects.Should().BeEquivalentTo(realm.Users); + } + [Fact] public async Task A_Reported_Count_That_The_Pages_Do_Not_Add_Up_To_Is_Not_Complete() { @@ -76,12 +130,16 @@ public async Task A_Reported_Count_That_The_Pages_Do_Not_Add_Up_To_Is_Not_Comple } [Fact] - public async Task A_Discovery_Issuer_That_Differs_Is_Reported_As_It_Is_For_The_Proof_To_Refuse() + public async Task A_Discovery_Issuer_That_Differs_Is_Reported_As_It_Is_And_No_Credential_Is_Sent_To_That_Realm() { await using var realm = await FakeKeycloakRealm.StartAsync(1); realm.DiscoveryIssuer = "https://elsewhere.example.test/realms/learnstack"; - (await realm.ReadAsync()).DiscoveredIssuer.Should().Be("https://elsewhere.example.test/realms/learnstack"); + var snapshot = await realm.ReadAsync(); + + snapshot.DiscoveredIssuer.Should().Be("https://elsewhere.example.test/realms/learnstack"); + realm.TokenRequests.Should().BeEmpty("a realm that is not the target never receives the client secret"); + realm.Pages.Should().Be(0); } [Theory] @@ -126,7 +184,7 @@ public async Task A_Reachable_Foreign_Origin_Named_By_Discovery_Is_Never_Called_ } [Fact] - public async Task A_Credential_Replacing_The_Certificate_Check_Is_Refused() + public void A_Credential_Replacing_The_Certificate_Check_Is_Refused() { var handler = new SocketsHttpHandler(); #pragma warning disable CA5359 // The case proves that a replaced certificate check is refused; it is never used. @@ -136,6 +194,5 @@ public async Task A_Credential_Replacing_The_Certificate_Check_Is_Refused() var act = () => KeycloakRealmContinuitySource.CreateClient(handler); act.Should().Throw(); - await Task.CompletedTask; } } diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs index 445edb82..b28b0764 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using System.Text.Json.Nodes; using FluentAssertions; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Hosting; @@ -123,8 +124,10 @@ public async Task An_Unreachable_Issuer_Refuses_The_Operator_Rather_Than_Trustin public async Task A_Discovery_Document_That_Names_Another_Issuer_Is_Refused() { await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); - misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( - misbehaving.Issuer, "https://elsewhere.example.test/realms/x", StringComparison.Ordinal); + // Only the document's own issuer property differs: the key set and the endpoints stay at the issuer's origin. + var document = JsonNode.Parse(misbehaving.DiscoveryDocument)!.AsObject(); + document["issuer"] = "https://elsewhere.example.test/realms/x"; + misbehaving.DiscoveryResponse = document.ToJsonString(); using var backchannel = new PlatformOperatorBackchannel(); var validator = ValidatorFor(misbehaving, backchannel); @@ -132,14 +135,18 @@ public async Task A_Discovery_Document_That_Names_Another_Issuer_Is_Refused() misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); result.IsValid.Should().BeFalse("a discovery issuer other than the pinned one is never trusted"); + result.Cause.Should().Be("metadata_unavailable", "the configuration validator refuses it, not a missing key"); } [Fact] public async Task A_Key_Set_At_Another_Origin_Is_Refused() { + await using var foreign = await TenantAuthenticationIssuer.StartAsync(); await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); - misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( - misbehaving.Issuer + "/keys", "http://127.0.0.1:1/keys", StringComparison.Ordinal); + // A live key set at another origin: a reader that followed it would succeed, so refusing is the control. + var document = JsonNode.Parse(misbehaving.DiscoveryDocument)!.AsObject(); + document["jwks_uri"] = foreign.Issuer + "/keys"; + misbehaving.DiscoveryResponse = document.ToJsonString(); using var backchannel = new PlatformOperatorBackchannel(); var validator = ValidatorFor(misbehaving, backchannel); @@ -147,6 +154,18 @@ public async Task A_Key_Set_At_Another_Origin_Is_Refused() misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); result.IsValid.Should().BeFalse(); + foreign.JwksRequests.Should().Be(0, "the other origin is never called"); + } + + [Theory] + [InlineData("operator.other")] + [InlineData("")] + [InlineData("operator.api ")] + public async Task An_Executor_That_Is_Not_One_Of_The_Two_Registered_Constants_Is_Refused_Before_Any_Token_Is_Read(string executor) + { + var act = async () => await _validator.ValidateAsync(Sign(), executor, Correlation); + + await act.Should().ThrowAsync(); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs new file mode 100644 index 00000000..fc73f86b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs @@ -0,0 +1,146 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.Extensions.Configuration; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// What the tool accepts from its environment and one line of standard input (ADR-0104 § 3), and what it refuses +/// without saying why: a refusal names no value, so a mistake cannot echo a secret. +/// +public sealed class RebindToolInputTests +{ + private const string Authority = "019a1929-5450-7bbb-8df1-516e8e002501"; + + private static Dictionary Valid() => new() + { + ["ConnectionStrings__IdentityRebind"] = "Host=db.example;Database=learnstack;Username=learnstack_identity_rebind;Password=x", // leakwatch:ignore:database-connection-string + ["Identity__AuthorityId"] = Authority, + ["Authentication__Tenant__Issuer"] = "https://new.example.test/realms/learnstack", + ["Deployment__Mode"] = "SaaS", + ["LEARNSTACK_OPERATOR_TOKEN"] = " header.payload.signature ", + ["LEARNSTACK_REBIND_REALM_CLIENT_ID"] = "reader", + ["LEARNSTACK_REBIND_REALM_CLIENT_SECRET"] = "secret-value", + }; + + private static bool Read(Dictionary environment, out RebindToolInput? input, string? line = null) => + RebindToolInput.TryRead(name => environment.GetValueOrDefault(name), () => line, + new ConfigurationBuilder().Build(), out input); + + [Fact] + public void A_Complete_Environment_Is_Read_And_The_Token_Is_Trimmed() + { + Read(Valid(), out var input).Should().BeTrue(); + + input!.OperatorToken.Should().Be("header.payload.signature"); + input.Target.AuthorityId.Value.Should().Be(Guid.Parse(Authority)); + input.Target.Issuer.Should().Be("https://new.example.test/realms/learnstack"); + input.Ticket.Should().BeNull(); + input.Mode.Should().Be(LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS); + } + + [Theory] + [InlineData("ConnectionStrings__IdentityRebind")] + [InlineData("Identity__AuthorityId")] + [InlineData("Authentication__Tenant__Issuer")] + [InlineData("Deployment__Mode")] + [InlineData("LEARNSTACK_OPERATOR_TOKEN")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_ID")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_SECRET")] + public void Each_Required_Value_Missing_Refuses(string missing) + { + var environment = Valid(); + environment.Remove(missing); + + Read(environment, out _).Should().BeFalse(); + } + + [Theory] + [InlineData("0")] + [InlineData("1")] + [InlineData("Development,SaaS")] + [InlineData("development")] + [InlineData("saas")] + [InlineData("Production")] + [InlineData(" Development")] + public void The_Deployment_Mode_Is_A_Declared_Name_Exactly(string mode) + { + var environment = Valid(); + environment["Deployment__Mode"] = mode; + environment["Authentication__Tenant__Issuer"] = "https://new.example.test/realms/learnstack"; + + Read(environment, out _).Should().BeFalse("the API refuses ordinals and lists, so the tool must not guess a mode"); + } + + [Theory] + [InlineData("not-a-guid")] + [InlineData("00000000-0000-0000-0000-000000000000")] + [InlineData("019a192954507bbb8df1516e8e002501")] + public void The_Authority_Must_Be_A_Nonempty_Hyphenated_Guid(string authority) + { + var environment = Valid(); + environment["Identity__AuthorityId"] = authority; + + Read(environment, out _).Should().BeFalse(); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_migration")] + [InlineData("learnstack_platform")] + public void Only_The_Rebind_Role_Is_Accepted_In_The_Connection_String(string role) + { + var environment = Valid(); + environment["ConnectionStrings__IdentityRebind"] = $"Host=db.example;Database=learnstack;Username={role};Password=x"; // leakwatch:ignore:database-connection-string + + Read(environment, out _).Should().BeFalse(); + } + + [Theory] + [InlineData("http://localhost:8080/realms/learnstack", "SaaS", false)] + [InlineData("http://localhost:8080/realms/learnstack", "SelfHostedOnline", false)] + [InlineData("http://localhost:8080/realms/learnstack", "Development", true)] + [InlineData("http://new.example.test/realms/learnstack", "Development", false)] + [InlineData("https://new.example.test/realms/learnstack", "Dedicated", true)] + [InlineData("https://new.example.test/realms/other", "Dedicated", false)] + [InlineData("https://new.example.test/realms/learnstack?x=1", "Dedicated", false)] + public void The_Target_Issuer_Follows_The_Grammar_And_Loopback_Http_Is_Development_Only(string issuer, string mode, bool accepted) + { + var environment = Valid(); + environment["Authentication__Tenant__Issuer"] = issuer; + environment["Deployment__Mode"] = mode; + + Read(environment, out _).Should().Be(accepted); + } + + [Fact] + public void The_Token_Falls_Back_To_One_Line_Of_Standard_Input_And_Never_To_An_Argument() + { + var environment = Valid(); + environment.Remove("LEARNSTACK_OPERATOR_TOKEN"); + + Read(environment, out var input, line: " piped.token.value ").Should().BeTrue(); + input!.OperatorToken.Should().Be("piped.token.value"); + Read(environment, out _, line: " ").Should().BeFalse(); + Read(environment, out _, line: null).Should().BeFalse(); + } + + [Fact] + public void A_Token_Over_The_Length_Bound_Refuses_And_A_Blank_Ticket_Is_No_Ticket() + { + var environment = Valid(); + environment["LEARNSTACK_OPERATOR_TOKEN"] = new string('a', 16 * 1024 + 1); + Read(environment, out _).Should().BeFalse(); + + environment["LEARNSTACK_OPERATOR_TOKEN"] = "a.b.c"; + environment["LEARNSTACK_REBIND_TICKET"] = " "; + Read(environment, out var input).Should().BeTrue(); + input!.Ticket.Should().BeNull(); + + environment["LEARNSTACK_REBIND_TICKET"] = "CHG-104"; + Read(environment, out input).Should().BeTrue(); + input!.Ticket.Should().Be("CHG-104"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs index 26b5b590..58036d39 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs @@ -4,7 +4,6 @@ using LearnStack.Modules.Identity.Infrastructure.Bindings; using LearnStack.Tests.Integration.Database; using LearnStack.Tools.IdentityAuthorityRebind; -using Microsoft.AspNetCore.WebUtilities; using Microsoft.IdentityModel.JsonWebTokens; using Xunit; diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs index 7b912df6..84cd273d 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs @@ -28,6 +28,27 @@ public sealed class PlatformOperatorAuthenticationTests private const string Issuer = "https://operator.example.test/realms/learnstack-hub"; private static readonly DateTimeOffset Now = new(2026, 11, 19, 9, 0, 0, TimeSpan.Zero); + [Theory] + [InlineData("operator.other")] + [InlineData("")] + [InlineData("OPERATOR.API")] + public void Only_The_Two_Registered_Executors_Can_Be_Named_In_A_Witness(string executor) + { + var read = () => PlatformOperatorTokenProfile.TryRead(Token(), Settings(), Now, executor, "00-trace-01", out _, out _); + + read.Should().Throw(); + } + + [Fact] + public void The_Offline_Tool_Executor_Is_Accepted_And_Recorded() + { + PlatformOperatorTokenProfile.TryRead( + Token(), Settings(), Now, PlatformOperatorSettings.RebindToolExecutor, "00-trace-01", out var witness, out _) + .Should().BeTrue(); + + witness!.Executor.Should().Be("operator.rebind"); + } + [Fact] public void A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Pinned_Issuer() { diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs index 14a57f03..7578b329 100644 --- a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs @@ -111,6 +111,29 @@ public void A_Subject_That_Cannot_Be_A_LearnStack_Subject_Is_Counted_And_Matches result.Holds.Should().BeTrue(); } + [Fact] + public void Every_Refusal_Class_Has_Its_Own_Closed_Outcome_Label() + { + var labels = Enum.GetValues().Where(refusal => refusal != IdentityRebindRefusal.None) + .Select(refusal => IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Refused, refusal))) + .ToList(); + + labels.Should().OnlyHaveUniqueItems().And.NotContain("refused", "no class falls through to the default label"); + labels.Should().OnlyContain(label => label.StartsWith("refused_", StringComparison.Ordinal)); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Applied)).Should().Be("applied"); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied)).Should().Be("already_applied"); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Unknown)).Should().Be("unknown"); + } + + [Fact] + public void A_Subject_Containing_Text_That_Cannot_Be_Stored_Is_Counted_Unkeyable() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [], ["ok", "nul\0inside", "\ud800lone-surrogate"]); + + result.Unkeyable.Should().Be(2); + result.Unbootstrapped.Should().Be(1); + } + [Fact] public void Duplicate_Reported_Subjects_Are_One_Subject() { diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs new file mode 100644 index 00000000..7c522514 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs @@ -0,0 +1,34 @@ +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.MultiTenancy; + +/// The closed act catalog never holds the offline issuer rebind (ADR-0104 § 3). +public sealed class PlatformOperatorActCatalogTests +{ + private sealed record Request; + + [Fact] + public void The_Rebind_Operation_Is_Not_A_Pipeline_Act_Even_Though_It_Needs_No_Platform_Role() + { + // NeedsPlatformRole is false for the rebind, which is what the executor admits; only the catalog keeps it out. + PlatformOperations.IdentityAuthorityRebind.NeedsPlatformRole.Should().BeFalse(); + + var act = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(PlatformOperations.IdentityAuthorityRebind))]); + + act.Should().Throw(); + } + + [Fact] + public void An_Onboarding_Operation_Is_Still_Accepted() + { + var catalog = new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(PlatformOperations.HostMap))]); + + catalog.TryGet(typeof(Request), out var found).Should().BeTrue(); + found.Operation.Should().BeSameAs(PlatformOperations.HostMap); + } +} diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 4c1fe39a..b45d0d26 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -62,10 +62,11 @@ platform-scoped, application-read-only `identity_authority` singleton owns the stable authority UUID and current exact issuer URI. The deployment installer creates it once with migration credentials before bootstrap; application code cannot insert, update or automatically replace it. Configuration issuer drift -refuses identity admission. P03-9/G13 owns an approved issuer rebind before the -first change, proving provider continuity and freezing bootstrap and old grants -while preserving authority, keys, actors and closed tombstones. Until that owner -is implemented, issuer renaming is unsupported; aliases and email matching supply +refuses identity admission. The only change is the controlled issuer rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md), an offline tool on a +confined role that proves provider continuity against the new realm and freezes starts +and User creation while it runs, preserving authority, keys, actors and closed +tombstones. Any other issuer change is unsupported; aliases and email matching supply no continuity proof. The subject key is SHA-256 over domain-separated, length-delimited stable diff --git a/docs/decisions/0104-controlled-issuer-rebind.md b/docs/decisions/0104-controlled-issuer-rebind.md index d2af3f9f..a8148542 100644 --- a/docs/decisions/0104-controlled-issuer-rebind.md +++ b/docs/decisions/0104-controlled-issuer-rebind.md @@ -187,8 +187,10 @@ and the runbook follow. ## Amendment 1 — Implementation contract of the rebind tool (2026-11-20) Step 3 of the platform-authority packet implements the decision. Each item below fixes -something the Decision left open or states where the code meets it; none changes the -Decision, the role's grants or the proof's rules. +something the Decision left open or states where the code meets it. Item 4 widens the +freeze check beyond the roles § 5 lists and item 10 records a residual the Decision did +not state; none of them changes the Decision's choice of option, the role's grants or +the proof's rules. 1. **Where the code lives.** The database half, `IdentityIssuerRebind`, lives in the Identity module's Infrastructure `Bindings` namespace so unit and integration @@ -198,52 +200,76 @@ Decision, the role's grants or the proof's rules. and the tool take one definition of the parameters, the bounded metadata manager and the closed profile. The witness minter stays one class; the tool is a second caller of the profile, with the executor `operator.rebind`, which is the "second sanctioned - caller" of § 3. + caller" of § 3. An architecture rule pins the callers of the profile and of the + offline validator. 2. **The order.** The exclusive lock is the first statement of the transaction, held by a server-side `lock_timeout` of 30 seconds, so the tool waits for another rebind and refuses with a class. Under the lock it reads the stored authority. A run whose - target already equals the stored issuer ends there, with no row. Otherwise the intent - row commits on a second connection before the freeze check, the proof or the change. - An authority that is not the configured one is a continuity refusal, so it follows - the intent row. + target already equals the stored issuer, under the same authority, ends there, with + no row. Otherwise the intent row commits on a second connection before the freeze + check, the proof or the change. An authority that is not the configured one is a + continuity refusal, so it follows the intent row. An unknown COMMIT is reconciled on + a fresh connection that first takes the shared lock, so it reads the issuer only + once the original transaction has ended. 3. **The audit rows.** The two operations are `identity.authority.rebind_attempt`, outcome `indeterminate`, and `identity.authority.rebind`, outcome `success`, with the reason slug `issuer_rebind`, the entity type `IdentityAuthority` and the authority id as the entity. The policy arm admits exactly those two operation-and-outcome pairs - and no other row, and the central audit installer owns the `audit_log` SQL, as it - does for the creation witness. The result row carries counts and no subject. + and no other row, the ordinary tenant arm excludes the role so that an announced + tenant cannot widen it, and the central audit installer owns the `audit_log` SQL, as + it does for the creation witness. The result row carries counts and no subject. 4. **The freeze check counts the platform role too.** The platform role runs in the same hosts as the application role, and an idle pooled connection of any of the four is still a session. The check reports a count and never a session's identity. A pooled connection stays a session until its idle lifetime ends, so the runbook's stop step - includes waiting for it. -5. **"Reads the new value" needs a comparison.** A lock alone only makes a creation - wait. Authority qualification takes the shared lock and then reads under a fresh - snapshot, and the User-creation admission takes the shared lock, reads the stored - authority and issuer, and refuses the creation when they are not the facts its process - qualified with. The two auxiliary read sources of the authorization and evidence - lanes take no lock: they run under a five-second total startup deadline, and a start - that straddles the change already fails at the locking read or at their own - comparison. + includes waiting for it. The check runs before the realm is read and again just + before the change. +5. **"Reads the new value" needs a comparison, and "waits" is bounded.** A lock alone + only makes a creation wait. Authority qualification takes the shared lock and then + reads under a fresh snapshot, and the User-creation admission takes the shared lock, + reads the stored authority and issuer, and refuses the creation when they are not + the facts its process qualified with. A creation waits for the lock for the two + seconds of its `lock_timeout` and is refused after that, and a start waits for the + command timeout, thirty seconds, and then fails its start with the fixed + qualification error. The two auxiliary read sources of the authorization and + evidence lanes take no lock: they run under a five-second total startup deadline, + and a start that straddles the change already fails at the locking read or at their + own comparison. 6. **The role is checked before it is used.** The tool refuses unless the session is the rebind role, it holds no inherited, bypass, superuser, creation or replication - attribute and no membership, no privilege on any other table, and exactly the - declared column grants. + attribute and no membership, no privilege on any other relation, and exactly the + declared grants on the three it uses, compared column by column in both directions. 7. **Continuity details the Decision left open.** A Closing user that still holds its subject is judged by neither rule, because closure owns that transition; a Closing user that holds only its key is judged like a Closed one. A reported subject that cannot be a LearnStack subject is counted and cannot equal any stored one. Presence is - the exact ordinal subject. + the exact ordinal subject. The new realm is read in full twice and the reads must + report the same users with none repeated, so a realm that changes while it is read is + refused; a realm above 200,000 users is refused because the proof cannot finish in + the tool's ten-minute deadline; a token that expires mid-enumeration is acquired + again once per request; and the credential is sent only after the realm's discovery + document names the target issuer. 8. **Inputs and exit codes.** The operator token comes from the environment or one line of standard input and the ticket, the realm client and its secret from the environment; - an argument is refused. The deployment mode is explicit, because it decides whether - a loopback operator issuer and the demo operator's grant are admitted. The tool - prints one line of classes and counts, with the correlation id that finds the rows, + an argument is refused. The deployment mode is a declared name exactly, because it + decides whether a loopback operator issuer and the demo operator's grant are admitted, + and outside Development the target issuer must be HTTPS. The tool prints one line of + classes and counts to standard output, with the correlation id that finds the rows, and exits `0` for applied or already applied, `2` for a refusal that left the state - unchanged and `3` when the commit's outcome could not be read back. + unchanged and `3` when the commit's outcome could not be read back. An interrupt or a + termination signal ends the run as the deadline does. 9. **Signals in a short-lived process.** The counters are defined in the library and exported by the tool only when an OTLP endpoint is configured in its environment; the printed line and the audit rows are the record otherwise. +10. **What the credential holder can do, and "the same realm path".** The tool checks the + operator's token, grant and attribution; the database does not force them. The role + holds `UPDATE (issuer)` and can insert a row of the admitted shape, so whoever holds + its password can change the issuer, or record a rebind that did not happen, without + the tool. The runbook therefore keeps the password apart from the operator's + identity and retires it after the window. A database-enforced pairing of the change + and its result row would need a confined definer that reads `audit_log`, and is the + maintainer's decision. "The same realm path" means the realm name: the issuer must + still end in `/realms/learnstack`, and the path before it may change. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/runbooks/identity-issuer-rebind.md b/docs/runbooks/identity-issuer-rebind.md index 19bf8227..cee647a9 100644 --- a/docs/runbooks/identity-issuer-rebind.md +++ b/docs/runbooks/identity-issuer-rebind.md @@ -1,7 +1,7 @@ # Identity issuer rebind Moving the identity authority from one issuer origin to another, under the same realm -path, without re-keying a single person. Decided in +name, without re-keying a single person. Decided in [ADR-0104](../decisions/0104-controlled-issuer-rebind.md); the storage contract of the confined role is in [Database Standards](../standards/05-database.md#controlled-issuer-rebind-storage). @@ -12,13 +12,15 @@ needs it. Use it when the deployment's tenant identity provider keeps its realm and its users but changes address: a new host name, a new load balancer origin, a migration to another -cluster that preserved every user's `sub` (a realm export and import does). +cluster that preserved every user's `sub` (a realm export and import does). The path +before `/realms/learnstack` may change, for example from `/auth/realms/learnstack` to +`/realms/learnstack`; the realm name may not. It does **not** change the stable authority identifier, and it refuses a new realm that -would lose or resurrect a person. It cannot rename the realm path (the issuer must keep -ending in `/realms/learnstack`), re-key users, merge two providers or move a tenant -between authorities. A new realm whose users have new `sub` values is a different -authority and is not reachable here: escalate before doing anything. +would lose or resurrect a person. It cannot rename the realm, re-key users, merge two +providers or move a tenant between authorities. A new realm whose users have new `sub` +values is a different authority and is not reachable here: escalate before doing +anything. ## What it needs @@ -27,15 +29,23 @@ authority and is not reachable here: escalate before doing anything. | An operator with a current token and the grant `platform.identity_authority.admin` | The same operator token and grant model as the other [operator acts](operator-access.md). The grant is read from configuration when the tool runs, never from a claim | | The sixth database role's connection string | `ConnectionStrings__IdentityRebind` for `learnstack_identity_rebind`. It exists only in the tool's environment for the minutes it runs: never in an API, worker, seeder or web configuration, and never in a file under version control | | A read-only credential for the **new** realm | A confidential client with the single role `realm-management/view-users`, created for this run and deleted after it. It is not a LearnStack credential and is not in the realm export | -| The stable `Identity__AuthorityId` and the new `Authentication__Tenant__Issuer` | The same two values the deployment is about to run with. The authority must equal the stored one; the issuer is the target | -| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance | +| The stable `Identity__AuthorityId` and the new `Authentication__Tenant__Issuer` | The same two values the deployment is about to run with. The authority must equal the stored one; the issuer is the target. Outside Development the target must be HTTPS | +| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance. The mode is a declared name exactly (`SaaS`, not `saas` or `1`) | + +**Keep the database password and the operator's identity apart.** The tool checks the +operator token, the grant and the attribution of the audit rows; the database does not +force them, so whoever holds the role's password could change the issuer without the +tool. The person who runs the tool should not hold the password longer than the window, +and the password is retired afterwards (see [After it](#after-it)). ## Before you start: freeze -The tool takes a database lock that makes every API start and every new user binding -wait, and it refuses to run while any session of the application, outbox, ingress or -platform role is open on the database. It cannot see a process that holds no database -connection, so the stop step below is the control for that case. +The tool takes a database lock that every API start and every new user binding queues +behind, and it refuses to run while any session of the application, outbox, ingress or +platform role is open on the database. A start that overlaps the rebind waits for the +lock for up to thirty seconds and then fails with the fixed qualification error, and a +user creation waits two seconds and is refused. The tool cannot see a process that holds +no database connection, so the stop step below is the control for that case. 1. Announce the window and **stop every API and worker process** of the deployment, including the Hangfire server, the outbox dispatcher and the provider-event poller. @@ -46,14 +56,16 @@ connection, so the stop step below is the control for that case. 3. Keep the **old** configuration out of every restart script. A process that is started with the old issuer after the change fails its start on the mismatch, which is the safe outcome; a process that was running and idle is the one the tool cannot see. +4. Do not create or delete users in the **new** realm while the tool runs. It reads the + realm twice and refuses a realm whose users changed between the reads. ## Get the access token Follow [Getting a token](operator-access.md#getting-a-token) for the operator issuer. The token lasts at most 15 minutes and its `auth_time` must be recent, so sign in just before the run. Give it to the tool in `LEARNSTACK_OPERATOR_TOKEN`, or pipe it on -standard input so it does not sit in the environment. **Never pass it as an argument**: -the tool refuses any argument. +standard input within thirty seconds so it does not sit in the environment. **Never +pass it as an argument**: the tool refuses any argument. ## Create the read-only realm credential @@ -77,11 +89,14 @@ export PlatformOperator__Issuer=... PlatformOperator__AuthorizedParties__0=... P export PlatformOperator__Grants__0__Subject= export PlatformOperator__Grants__0__Permissions__0=platform.identity_authority.admin export LEARNSTACK_REBIND_REALM_CLIENT_ID=... LEARNSTACK_REBIND_REALM_CLIENT_SECRET=... -export LEARNSTACK_REBIND_TICKET=CHG-123 # optional, 1 to 64 characters +export LEARNSTACK_REBIND_TICKET=CHG-123 # optional but recommended printf %s "$TOKEN" | dotnet LearnStack.Tools.IdentityAuthorityRebind.dll ``` -It prints exactly one line and exits: +The ticket is 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`; a ticket outside that +grammar is refused. It is recorded on the two audit rows, which no tenant can read. + +It prints exactly one line to standard output and exits: | Exit | Meaning | |---|---| @@ -89,28 +104,41 @@ It prints exactly one line and exits: | `2` | Refused. **The state is unchanged**; fix the cause and run it again | | `3` | `outcome=unknown`: the commit's answer was lost and the stored issuer could not be read back. Read `identity_authority.issuer` before anything else | -Every line carries `correlation=`, which finds the audit rows, and counts where the -proof ran: `active`, `closing`, `closed`, `reported`, `unkeyable`, `missing_active`, -`reappearing_closed` and `unbootstrapped`. It never prints a subject, a key, an issuer, -an address or a credential. +Every line that follows a successful reading of the input carries `correlation=`, +which finds the audit rows, and a line where the proof ran carries counts: `active`, +`closing`, `closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed` and +`unbootstrapped`. `refused_input` and `refused_unexpected` carry neither, because they +happen before a handle exists or when none can be trusted. The line never contains a +subject, a key, an issuer, an address or a credential. + +An interrupt (Ctrl-C) or a termination signal ends the run as the ten-minute deadline +does: the run rolls back, an unknown commit is still reconciled, and the line says +`refused_cancelled` or its true outcome. ## What the tool does, in order 1. Validates the token with the operator validator and admits the act against the grant. A refusal here (`refused_operator_...`) writes nothing, not even a row. -2. Opens one direct, never-pooled connection as the rebind role, checks that the role is - exactly what it was granted, and takes the exclusive rebind lock as its first - statement. If another rebind holds it, the tool waits up to 30 seconds and refuses - with `refused_rebind_in_progress`. +2. Opens one direct, never-pooled connection as the rebind role and checks that the role + is exactly what it was granted, table by table and column by column. It then takes + the exclusive rebind lock as its first statement. If another rebind holds it, the + tool waits up to 30 seconds and refuses with `refused_rebind_in_progress`. 3. Reads the stored authority. If the stored issuer already equals the target it ends with `already_applied` and **writes nothing**. -4. Otherwise commits an **intent** audit row on its own short transaction. From here on an - aborted attempt is on record. +4. Otherwise commits an **intent** audit row on its own short transaction. From here on + an aborted attempt is on record. 5. Refuses while a session of a runtime role is open (`refused_live_sessions`). 6. Reads the new realm's discovery document, key set and users, and requires the realm's - own `issuer` to equal the target, at least one signing key and a complete enumeration. -7. Proves continuity (below), changes the one column, writes the **result** row on the - same transaction and commits. + own `issuer` to equal the target, at least one signing key and a complete + enumeration. The credential is sent only to the realm's own token endpoint, and only + once the discovery document names the target. +7. Proves continuity (below), asks the freeze question again, changes the one column, + writes the **result** row on the same transaction and commits. + +Limits that bound the run: statements time out at 120 seconds, a transaction that idles +for 15 minutes is ended by the server, the whole run has a ten-minute deadline, and a +realm of more than 200,000 users is refused because its proof cannot finish in that +deadline. ## The continuity proof @@ -122,8 +150,12 @@ an address or a credential. signed in yet. - A user that is **Closing** and still holds its subject is judged by neither rule, because closure owns that transition. -- A `sub` that could not be a LearnStack subject (blank, over 255 characters) is counted as - `unkeyable` and cannot equal a stored one. +- A `sub` that could not be a LearnStack subject (blank, over 255 characters or text + that cannot be stored) is counted as `unkeyable` and cannot equal a stored one. + +The realm is read in full twice and the two reads must report the same users, with no +user repeated and the same count before and after. A realm that changes while it is read +is refused as incomplete. `refused_continuity_broken` means the new realm is not the same population. Do not force it: find out why the users differ. The usual cause is an import that generated new @@ -133,20 +165,24 @@ ids. | Outcome | What it means and what to do | |---|---| -| `refused_input` | A required value is missing, malformed, or an argument was given. The tool says no more, so that a mistake cannot echo a secret. Check `Deployment__Mode`, the connection string's role, the authority id, the issuer, the token and the realm credential | -| `refused_operator_token_` | The token failed validation: `token_missing`, `token_expired`, `token_audience`, `token_issuer`, `token_signature`, `token_algorithm`, `token_type`, `token_lifetime`, `metadata_unavailable`, `metadata_stale` or a `profile_*` cause. [The profile](operator-access.md#the-token-profile) says what each requires. Get a fresh token | +| `refused_input` | A required value is missing, malformed, or an argument was given. The tool says no more, so that a mistake cannot echo a secret. Check `Deployment__Mode`, the connection string's role, the authority id, the issuer (HTTPS outside Development), the token and the realm credential | +| `refused_operator_token_` | The token failed validation: `token_missing`, `token_invalid`, `token_expired`, `token_audience`, `token_issuer`, `token_signature`, `token_algorithm`, `token_type`, `token_lifetime`, `metadata_unavailable`, `metadata_stale` or a `profile_*` cause. [The profile](operator-access.md#the-token-profile) says what each requires. Get a fresh token | | `refused_operator_missing_permission` | The token is good and the operator holds no `platform.identity_authority.admin` grant | +| `refused_operator_invalid_ticket` | The ticket is outside its grammar | | `refused_operator_issuer_not_configured` / `..._configuration_invalid` | The `PlatformOperator__*` settings are absent or unsafe | -| `refused_role_invalid` | The connection string is not the rebind role's, or the role holds something beyond its grants. Re-run the roles script | +| `refused_operator_invalid_witness` / `..._unknown_operation` / `..._not_admitted` | A defect in the tool's build, not an operator mistake. Escalate | +| `refused_not_admitted` | The admission was stale, spent or not for this operation. Run the tool again | +| `refused_role_invalid` | The connection string is malformed or not the rebind role's, or the role holds something beyond (or lacks something of) its grants. Re-run the roles script and migrate | | `refused_rebind_in_progress` | Another rebind holds the lock, or a previous run is still open. Wait and retry | | `refused_database_unavailable` | The database could not be reached or answered a failure. Nothing changed | | `refused_authority_mismatch` | The stored authority is not `Identity__AuthorityId`. A different authority would re-key every person: stop and escalate | | `refused_live_sessions` | A session of a runtime role is open (the count is printed). Stop what holds it and retry | -| `refused_new_realm_unavailable` / `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm could not be read completely, published no signing key, changed while it was read, or names another issuer. Check the credential's role and the realm's address | +| `refused_new_realm_unavailable` / `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm could not be read completely, published no signing key, changed while it was read, is too large, or names another issuer. Check the credential's role and the realm's address | | `refused_continuity_broken` | See above | -| `refused_audit_failed` | The audit row could not be written, so the change was rolled back | -| `refused_commit_failed` | The commit failed and the stored issuer was read back unchanged. Retry | +| `refused_audit_failed` | The audit row could not be written, so the change was rolled back or never begun | +| `refused_commit_failed` | The commit failed and the stored issuer was read back unchanged, after the original transaction had ended. Retry | | `refused_cancelled` | The ten-minute deadline or an interrupt ended the run | +| `refused_unexpected` | A defect. Nothing is known to have changed: read the stored issuer, then escalate | Every refusal leaves the stored issuer where it was and the next run repeats the whole proof. The intent row stays, so the trail shows each attempt. @@ -161,7 +197,11 @@ configuration is the unfreeze.** start with the fixed qualification error: that is the guard, not a bug. 2. Delete the read-only realm client and remove `ConnectionStrings__IdentityRebind` from the tool's host. -3. Confirm one sign-in per tenant host and look at the audit rows: +3. Retire the role's credential: set a new password with + `ALTER ROLE learnstack_identity_rebind PASSWORD ''` and discard it, or keep the + role `NOLOGIN` outside windows and `LOGIN` for the next one. The roles script + restores `LOGIN` every time it runs, so rotate or disable after any rerun of it. +4. Confirm one sign-in per tenant host and look at the audit rows: ```sql -- as a role that can read audit_log, not the rebind role @@ -181,18 +221,22 @@ configuration is the unfreeze.** is a short-lived process: it exports them only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set in its environment, and the printed line and the audit rows are the record otherwise. `learnstack_identity_lock_refusals_total{lock_kind="authority"}` counts a user creation -that waited out a rebind and found the issuer changed. +that could not take the shared rebind lock in time (`reason` `timeout`, `cancelled` or +`fault`) and, with `reason="mismatch"`, one that waited out a rebind and found the issuer +changed. A burst of `timeout` is what a window looks like from the API side. ## Not recoverable here - **A change of the stable authority identifier.** It re-keys every person and can resurrect a closed tombstone. There is no tool for it; escalate. -- **A realm rename or a different realm path.** +- **A realm rename.** - **A running process that held no database connection** when the tool ran. It keeps the old issuer until it restarts, and then fails its start on the mismatch. The stop step is the control for it, not the database. - **A wrong rebind that was applied.** Run the tool again with the old issuer as the target; the same proof and the same rows apply. +- **A realm of more than 200,000 users.** The proof cannot finish in the deadline; + escalate. ## What this does not do diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 0ff42d6e..3dda7430 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6318,7 +6318,7 @@ that the act is live before they call it; no SQL-level binding is added. **Derives from:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) and its Amendment 1. The rebind changes one column of the one `identity_authority` row, from a -sixth login role used by an offline tool. It adds a role, exact column grants, three +sixth login role used by an offline tool. It adds a role, exact column grants, four policy changes, one trigger and one advisory-lock key, and **no** definer: the definer census stays at sixteen. @@ -6327,10 +6327,17 @@ census stays at sixteen. `learnstack_identity_rebind` is `LOGIN NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION`, a member of nothing and with no member. Its credential is `ConnectionStrings__IdentityRebind`, read by the tool from its own environment with -`Environment.GetEnvironmentVariable`, never by `GetConnectionString`, and confined to the -one tool file that reads it by +`Environment.GetEnvironmentVariable`, never by `GetConnectionString`, and confined to +the one tool file that reads it by [`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool). -No API, worker, seeder, web or compose service receives it. +No API, worker, seeder, web or compose service receives it. The migration refuses with +a readable message when the role does not exist, because the roles script is its only +definition. + +A runtime role's membership in either confined role is not detected at runtime start, +because the guard of a runtime connection asks about bypass attributes. The roles script +revokes such a membership on every run, and the tool's own posture check refuses a role +that has one. ### Grants, read from the column view @@ -6353,14 +6360,19 @@ the absence of the rest, and each refusal as the role itself. One permissive policy per command is kept. `identity_authority_read` gains the role beside the application role and the owner; a third policy, `identity_authority_rebind`, admits `UPDATE` of the `id = 1` row to the role and nothing else; `users_isolation` -gains the role in its `USING` and keeps its `WITH CHECK`, so the role sees every user and -may write none. The `audit_log_isolation` policy gains one arm in its `WITH CHECK`, -installed by the central audit installer because no module names the table: platform -sentinel tenant, identity module, no organization, `Must` and `SecurityEvent`, entity -type `IdentityAuthority`, reason `issuer_rebind`, no actor, mail, address or agent, an -operator attribution in `metadata`, and exactly `identity.authority.rebind_attempt` with -outcome `indeterminate` or `identity.authority.rebind` with outcome `success`. The role -has no `SELECT` on the table, so it cannot read its own rows back. +gains the role in its `USING` and keeps its `WITH CHECK`, so the role sees every user +and may write none. + +The `audit_log_isolation` policy is restated in its `WITH CHECK`, by the central audit +installer because no module names the table. The ordinary tenant arm now excludes this +role: that arm admits whatever tenant a session announces, any session can announce one, +and an arm that admitted the role there would let it write a row into any tenant's +trail. The rebind arm admits only the platform sentinel tenant, the identity module, no +organization, `Must` and `SecurityEvent`, entity type `IdentityAuthority`, reason +`issuer_rebind`, no actor, mail, address or agent, an operator attribution in +`metadata`, and exactly `identity.authority.rebind_attempt` with outcome +`indeterminate` or `identity.authority.rebind` with outcome `success`. The role has no +`SELECT` on the table, so it cannot read its own rows back. ### The key trigger @@ -6368,52 +6380,61 @@ has no `SELECT` on the table, so it cannot read its own rows back. `learnstack_migration`, `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, on `BEFORE UPDATE` of `identity_authority`. It raises `23514` when `id` or `authority_id` changes, for every role, so the stable key the subject keys hash cannot move even where a grant -would allow it. It is the thirtieth function and thirtieth trigger of the Identity chain -census. The issuer grammar stays in the tool and in qualification, not in SQL. +would allow it. It is the thirtieth function and thirtieth trigger of the Identity +chain census. The issuer grammar stays in the tool and in qualification, not in SQL. ### The lock -One bigint advisory key, `IdentityAdvisoryLockKey.ForAuthorityRebind()`, SHA-256 over the -length-prefixed strings `learnstack.identity.lock.v1` and `authority-rebind`, the first -eight bytes as a big-endian signed integer, with an independently computed vector pinned -in `GlobalIdentityKeyTests`. The tool takes it **exclusive** (`pg_advisory_xact_lock`) as -the first statement of one direct, never-pooled transaction. Authority qualification and -the User-creation admission take the **shared** form first and always before the subject -lock, so the order is fixed and the tool, which takes only this key, cannot form a cycle. +One bigint advisory key, `IdentityAdvisoryLockKey.ForAuthorityRebind()`, SHA-256 over +the length-prefixed strings `learnstack.identity.lock.v1` and `authority-rebind`, the +first eight bytes as a big-endian signed integer, with an independently computed vector +pinned in `GlobalIdentityKeyTests`. The tool takes it **exclusive** +(`pg_advisory_xact_lock`) as the first statement of one direct, never-pooled +transaction. Authority qualification and the User-creation admission take the **shared** +form first and always before the subject lock, so the order is fixed and the tool, +which takes only this key, cannot form a cycle. - **Qualification** takes it after `SET TRANSACTION READ ONLY` and before its read; under `READ COMMITTED` the next statement sees the rebind it waited for and compares against - the new issuer. -- **The creation admission** takes it under its two-second `lock_timeout` and then reads the - stored authority and issuer, refusing with `IdentityAuthorityChangedException` when they - are not the facts the process qualified with. A lock alone would only delay a + the new issuer. It sets no `lock_timeout`, so a start that overlaps a rebind waits + until the command timeout (thirty seconds) and then fails with the fixed + qualification message, which stays failed until the process restarts. +- **The creation admission** takes it under its two-second `lock_timeout` and then reads + the stored authority and issuer, refusing with `IdentityAuthorityChangedException` + when they are not the facts the process qualified with. A creation during a rebind is + therefore refused after two seconds, not held. A lock alone would only delay a creation from a process that qualified before the rebind; the comparison is what - refuses it. The refusal answers as the sibling storage failures do and is counted in - `learnstack_identity_lock_refusals_total{lock_kind="authority",reason="mismatch"}`. + refuses it. The refusal answers as the sibling storage failures do and is counted + in `learnstack_identity_lock_refusals_total{lock_kind="authority",reason="mismatch"}`. +- **The tool's reconciliation** of an unknown `COMMIT` takes the shared form too, so it + reads the issuer only once the original transaction has ended. - [`Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock`](21-architecture-tests-catalogue.md#only_the_rebind_run_and_the_two_freeze_readers_take_the_rebind_lock) - pins the three takers. + pins the takers. ### What the tool checks before it uses the role Server-side, as the role: `session_user` and `current_user` are the role; it is not `INHERIT`, `BYPASSRLS`, superuser, `CREATEDB`, `CREATEROLE` or `REPLICATION`; it has no -membership either way and no schema or database `CREATE`; it holds no privilege on any -other table; and it holds exactly the declared grants on the three it uses. Any other -posture refuses the run before the lock. The freeze check counts sessions of the -application, outbox, ingress and platform roles in the database other than its own, from -`pg_stat_activity`, which shows another role's session with its role and database even -where the statement is hidden. +membership either way and no schema or database `CREATE`; it holds no privilege, table +or column, on any other relation; and on the three it uses it holds exactly the declared +grants, compared column by column in both directions, so an extra column privilege and a +missing declared one both refuse. Any other posture refuses the run before the lock. The +freeze check counts sessions of the application, outbox, ingress and platform roles in +the database other than its own, from `pg_stat_activity`, which shows another role's +session with its role and database even where the statement is hidden. It runs before +the new realm is read and again immediately before the change. ### Proof Real PostgreSQL as the role itself and as each other role: -`IdentityAuthorityRebindStorageTests` (column privileges, the one admitted `UPDATE`, the -key trigger with the grant present, the `users` read, the two audit rows and every -refused variant), `IdentityAuthorityRebindLockTests` (a start that waits for a rebind and -then fails or passes on the value it left, a creation refused within its timeout, a -straggler refused after the change), `IdentityAuthorityRebindTests` (the run end to end, -every refusal class, the continuity rules, an audit failure rolling the change back, a -killed session and a lost commit acknowledgement) and `IdentityAuthorityRebindToolTests` -(the offline tool as a child process). The census counts are in -`GlobalIdentitySchemaTests` (thirty functions, sixteen definers, thirty triggers) and -the head pin in `MigrationRollbackTests`. +`IdentityAuthorityRebindStorageTests` (column privileges, the one admitted `UPDATE`, +the key trigger with the grant present, the `users` read, the two audit rows, every +refused variant, and the rows a role cannot widen by announcing a tenant), +`IdentityAuthorityRebindLockTests` (a start that waits for a rebind and then fails or +passes on the value it left, a creation refused within its timeout, a straggler refused +after the change), `IdentityAuthorityRebindTests` (the run end to end, every refusal +class and posture drift, the continuity rules, an audit failure rolling the change back, +a killed session, a lost commit acknowledgement and a reconciliation that waits) and +`IdentityAuthorityRebindToolTests` (the offline tool as a child process). The census +counts are in `GlobalIdentitySchemaTests` (thirty functions, sixteen definers, thirty +triggers) and the head pin in `MigrationRollbackTests`. diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index b3d589a3..40ab967e 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -530,7 +530,11 @@ backend treat business rejections as system failures. Accepted ADR-0072/0073/0074 require `lock_kind` closed to `subject`, `user`, `tenant`; wait `outcome` closed to `acquired`, `timeout`, `cancelled`, `fault`; and refusal -`reason` closed to `timeout`, `cancelled`, `fault`. No tenant, actor, subject, +`reason` closed to `timeout`, `cancelled`, `fault`. +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) adds `lock_kind=authority` +for the shared rebind lock a User creation takes, and `reason=mismatch` for a creation +that waited out a rebind and found the stored issuer was not the one its process +qualified with. No tenant, actor, subject, digest, raw issuer, SQL, correlation or exception text is a label. Typed closed binding diagnostic reasons remain separate from public Problem Details and are not trusted identity-refusal witnesses. A contextual lock-plan fault increments diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 69189189..805fffef 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -584,13 +584,24 @@ for the full strategy. Standards-side: ### Confined identity-rebind role -`learnstack_identity_rebind` is the sixth login role and the only credential that can -change `identity_authority.issuer`. It is `NOINHERIT` and `NOBYPASSRLS`, holds a handful -of column grants and one policy arm, and is configured on no API, worker, seeder, web or -compose service: [`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool) +`learnstack_identity_rebind` is the sixth login role and the one login credential that +can change `identity_authority.issuer`; the owner credential is deploy-only and can +alter any policy. It is `NOINHERIT` and `NOBYPASSRLS`, holds a handful of column grants +and one policy arm, and is configured on no API, worker, seeder, web or compose service: +[`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool) confines the key to the one tool file that reads it, and the tool refuses to use a role whose posture is not exactly the declared one. A column grant to a runtime role guarded -by a transaction setting was rejected, because any session can set the setting. +by a transaction setting was rejected, because any session can set the setting. The +role's `audit_log` access is bounded by a policy arm that excludes the role from the +ordinary tenant arm, so the tenant a session announces does not widen its rows. + +**Residual.** The operator token, the grant and the attribution in the audit rows are +checked by the tool, and the database does not force them: whoever holds the role's +password can change the issuer without the tool and write a rebind row of the admitted +shape. The role's password is therefore held apart from the operator's identity, and +retired after the window ([runbook](../runbooks/identity-issuer-rebind.md#after-it)). A +database-enforced pairing of the change and its result row would need a confined +definer that reads `audit_log`, and is the maintainer's decision. [Database Standards](05-database.md#controlled-issuer-rebind-storage) owns the grants, policies, trigger and lock. diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index b130598e..423f0094 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -115,9 +115,10 @@ policies are `FiniteTrusted` with that single source, the business actor of ever they write is `UserId.SystemActor`, and the operator is recorded in audit only. The grant is evaluated by the gate on every act, never cached across acts. The rebind of [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) is not an act of that -executor and not a route: its registered operation needs neither the platform role nor -the pipeline, so neither the scope nor the executor can spend its admission, and the -offline tool that consumes it validates the same token and evaluates the same grant. +executor and not a route: the scope refuses an operation that needs no platform role, and the +executor runs only the closed catalog of five onboarding acts, which refuses the rebind +operation by construction (`PlatformOperatorActCatalog`). The offline tool that consumes +the admission validates the same token and evaluates the same grant. Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index cb2b81d8..9a9605fc 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**385 test methods run in +**386 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**289 rules in this catalogue are Implemented, and 171 of them are in that assembly.** +**290 rules in this catalogue are Implemented, and 172 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -5931,6 +5931,24 @@ structural test proves — and what it does not. review; widened to the second caller by P03-9 Step 3). - **Phase:** P03-9. +#### `The_Operator_Token_Validator_Has_Two_Callers_Of_The_Profile_And_One_Of_Its_Own` + +- **Asserts:** by IL, the callers of `PlatformOperatorTokenProfile.TryRead` in every + production assembly are exactly the API scheme's validated event + (`PlatformOperatorEvents.TokenValidated`) and `PlatformOperatorTokenValidator.ValidateAsync`, + and the callers of the offline validator's constructor and `ValidateAsync` are exactly + the rebind tool's `RebindTool.RunAdmittedAsync`. `TryRead` and the validator accept the + two executor constants and refuse any other. +- **Why it matters:** the validator and the profile are public so that the API scheme and the + tool share one definition, and the witness they mint is evidence that a token passed + the closed profile. Pinning the callers keeps a second public door from becoming a + second place a witness can be made ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 7). +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 3. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3 review). +- **Phase:** P03-9. + #### `The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool` - **Asserts:** in code under `backend/src`, comments stripped, none of the spellings @@ -5953,10 +5971,11 @@ structural test proves — and what it does not. - **Asserts:** by IL, the callers of `IdentityAdvisoryLockKey.ForAuthorityRebind` in every production assembly are exactly `NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync`, - `IdentityAuthorityQualification.QualifyCoreAsync` and - `IdentityIssuerRebind.RunCoreAsync`. + `IdentityAuthorityQualification.QualifyCoreAsync`, `IdentityIssuerRebind.CommitAsync` + (the reconciliation of an unknown COMMIT, which waits behind the original + transaction) and `IdentityIssuerRebind.RunCoreAsync`. - **Why it matters:** the exclusive form is the freeze and the shared form is what a start or a - creation waits behind; a fourth taker is a fourth party that can hold or wait on it. + creation waits behind; a further taker is a further party that can hold or wait on it. - **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 5. - **Type:** xUnit + IL scan. **Kind:** structural. - **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3). diff --git a/infra/compose/README.md b/infra/compose/README.md index a9f6d3f3..3863d8b8 100644 --- a/infra/compose/README.md +++ b/infra/compose/README.md @@ -91,8 +91,8 @@ and the P03-9 Step 3 Identity migration requires the sixth. For a warm volume, s private environment, recreate the postgres container with the existing volume to pass the new environment values, then apply the roles script above before `make migrate`. Do not delete a volume to add a role. The sixth role's connection string is never a -compose or host setting: it exists only in the environment of the offline rebind tool. No runtime process receives the migration -password. The [database contract](../../docs/standards/05-database.md#provider-event-intake-storage) +compose or host setting: it exists only in the environment of the offline rebind tool. +No runtime process receives the migration password. The [database contract](../../docs/standards/05-database.md#provider-event-intake-storage) owns the private machine source and its bounds; installing storage alone does not activate provider polling. From c89dd12c73889a839eda6662dabe6531bcbb170f Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 04:53:03 +0300 Subject: [PATCH 16/28] fix(identity): close P03-9 step 3 review round 2 findings Three independent reviews found no blocker; each finding was checked against the code, and the ones that held are fixed. The last-moment freeze check read pg_stat_activity in the transaction that had already read it, and the server serves that view from one snapshot per transaction, so a host that never takes the rebind lock could start unseen; each count now drops the snapshot first. The Npgsql keepalive sent messages that restarted the server's idle-in-transaction clock, so a hung tool's lock was never freed; it is off and the operating system probes instead. The role posture no longer locks out a deployment whose extensions publish PUBLIC views, and it now checks the maintenance privilege, sequences, ownership and that the server applied the session timeouts. Refusals name the check that failed with a closed detail, never a value; a failure to read back an unknown commit is unknown, never a refusal; a hang-up ends a run like an interrupt; tool refusals before the database are counted; the deployment mode is read as the API reads it. The runbook gains the build, enable, exit-3, rollback and settings steps it lacked, and the heavy IL census's lifecycle owner lists name the rebind's transactions. Step 3 delivery records and the Phase 03 Status row are written. Co-Authored-By: Claude Sonnet 5.5 --- backend/Directory.Packages.props | 5 +- .../PlatformOperatorAuthentication.cs | 2 +- .../Tenancy/TenancyCompositionExtensions.cs | 9 +- .../PlatformOperatorTokenValidator.cs | 7 +- .../Hosting/DeploymentModeParser.cs | 36 ++ .../KeycloakRealmContinuitySource.cs | 11 +- .../Program.cs | 86 ++-- .../RebindTool.cs | 31 +- .../RebindToolInput.cs | 85 +++- .../Bindings/INewRealmContinuitySource.cs | 36 +- .../Bindings/IdentityIssuerRebind.cs | 190 ++++++-- .../Bindings/IdentityRebindOutcome.cs | 93 +++- ...tegrationDeliveryLifecycleBoundaryTests.cs | 6 + .../Database/IdentityAuthorityRebindTests.cs | 136 +++++- .../IdentityAuthorityRebindToolTests.cs | 90 +++- .../Database/PostgresFixture.cs | 5 +- .../FakeKeycloakRealm.cs | 6 + .../KeycloakRealmContinuitySourceTests.cs | 23 +- .../PlatformOperatorTokenValidatorTests.cs | 2 +- .../RebindToolInputTests.cs | 98 +++- .../Identity/IdentityRebindDetailTests.cs | 29 ++ .../SharedKernel/DeploymentModeParserTests.cs | 48 ++ .../0104-controlled-issuer-rebind.md | 89 ++-- docs/modules/identity/audit.md | 2 +- docs/modules/identity/permissions.md | 1 + docs/roadmap/phase-03-delivery-log.md | 433 +++++++++--------- docs/roadmap/phase-03-identity-admin.md | 2 +- docs/runbooks/identity-issuer-rebind.md | 286 ++++++++---- docs/runbooks/operator-access.md | 8 + docs/standards/05-database.md | 40 +- docs/standards/11-security.md | 17 +- docs/standards/18-audit-coverage.md | 11 +- docs/standards/19-permissions.md | 4 +- .../21-architecture-tests-catalogue.md | 33 +- 34 files changed, 1434 insertions(+), 526 deletions(-) create mode 100644 backend/src/LearnStack.SharedKernel/Hosting/DeploymentModeParser.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index 2f7f490e..23fa98d4 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -14,7 +14,10 @@ + definition (ADR-0101 § 7, ADR-0104 § 3). The versions are the ones JwtBearer already resolves. + JwtBearer requires Protocols.OpenIdConnect at its own floor: raising JwtBearer past 10.0.12 + can raise that floor above these pins, and restore then fails with NU1605 in every project + that references Infrastructure. Raise the two pins with it. --> diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs index 0dea199e..357c0b64 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs @@ -86,7 +86,7 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthentication( options.AutomaticRefreshInterval = PlatformOperatorValidation.AutomaticRefreshInterval; options.RefreshInterval = PlatformOperatorValidation.RefreshInterval; options.ConfigurationManager = PlatformOperatorValidation.CreateConfigurationManager( - settings, backchannel, health, loggerFactory.CreateLogger("LearnStack.Infrastructure.PlatformOperator.PlatformOperatorDocumentRetriever")); + settings, backchannel, health, loggerFactory); options.TokenValidationParameters = PlatformOperatorValidation.CreateParameters(settings); options.Events = new PlatformOperatorEvents(settings, clock, health, logger); }); diff --git a/backend/src/LearnStack.Api/Tenancy/TenancyCompositionExtensions.cs b/backend/src/LearnStack.Api/Tenancy/TenancyCompositionExtensions.cs index 910f3ef5..2ae5c97e 100644 --- a/backend/src/LearnStack.Api/Tenancy/TenancyCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Tenancy/TenancyCompositionExtensions.cs @@ -59,13 +59,8 @@ public static DeploymentMode RequireDeploymentMode(this IConfiguration configura + "environment-specific appsettings file or in the environment."); } - // Enum.TryParse also accepts ordinals and comma-separated lists, so - // `Deployment__Mode=0` would parse as Development — reintroducing the - // exact silent-default this method exists to remove, through a value - // that looks like a typo rather than a mode. Only a declared name is - // accepted. - if (!Enum.TryParse(raw, ignoreCase: true, out var mode) - || !Enum.GetNames().Contains(raw.Trim(), StringComparer.OrdinalIgnoreCase)) + // Only a declared name is accepted; DeploymentModeParser says why an ordinal or a list is not. + if (!DeploymentModeParser.TryParse(raw, out var mode)) { throw new InvalidOperationException( $"'{DeploymentModeKey}' is '{raw}', which is not one of " diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs index 8fead8da..d1c17a4c 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs @@ -59,16 +59,17 @@ public static ConfigurationManager CreateConfigurati PlatformOperatorSettings settings, PlatformOperatorBackchannel backchannel, PlatformOperatorMetadataHealth health, - ILogger retrieverLogger) + ILoggerFactory loggerFactory) { ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(backchannel); ArgumentNullException.ThrowIfNull(health); - ArgumentNullException.ThrowIfNull(retrieverLogger); + ArgumentNullException.ThrowIfNull(loggerFactory); return new ConfigurationManager( settings.MetadataAddress, new OpenIdConnectConfigurationRetriever(), - new PlatformOperatorDocumentRetriever(settings, backchannel, health, retrieverLogger), + new PlatformOperatorDocumentRetriever( + settings, backchannel, health, loggerFactory.CreateLogger()), new PlatformOperatorConfigurationValidator(settings)) { AutomaticRefreshInterval = AutomaticRefreshInterval, diff --git a/backend/src/LearnStack.SharedKernel/Hosting/DeploymentModeParser.cs b/backend/src/LearnStack.SharedKernel/Hosting/DeploymentModeParser.cs new file mode 100644 index 00000000..95cbbd0d --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Hosting/DeploymentModeParser.cs @@ -0,0 +1,36 @@ +namespace LearnStack.SharedKernel.Hosting; + +/// +/// Reads a from configuration text the one way every host that has to agree on it does: +/// the API at start-up and the offline operator tools. +/// +/// +/// Only a declared name is accepted, compared without regard to case and with surrounding white space ignored. +/// alone also accepts an ordinal and a comma-separated +/// list, so Deployment__Mode=0 would parse as : the silent default the +/// explicit key exists to remove, reached through a value that looks like a typo rather than a mode. +/// +public static class DeploymentModeParser +{ + /// Parses ; false when it is empty or not a declared mode name. + public static bool TryParse(string? text, out DeploymentMode mode) + { + mode = default; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var name = text.Trim(); + foreach (var declared in Enum.GetNames()) + { + if (string.Equals(declared, name, StringComparison.OrdinalIgnoreCase)) + { + mode = Enum.Parse(declared); + return true; + } + } + + return false; + } +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs index 96c2bf40..03bb6e18 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs @@ -54,6 +54,8 @@ internal static HttpClient CreateClient(SocketsHttpHandler? handler = null) public async Task ReadAsync(string issuer, CancellationToken cancellationToken = default) { + // The step the read has reached, so a refusal names where it stopped and never what was being read. + var step = NewRealmStep.Discovery; try { var origin = new Uri(issuer); @@ -66,14 +68,19 @@ public async Task ReadAsync(string issuer, CancellationToken c return new NewRealmSnapshot(discovery.Issuer, 0, false, []); } + step = NewRealmStep.KeySet; var keys = await CountKeysAsync(discovery.KeySet, cancellationToken); + step = NewRealmStep.Token; var session = new AdminSession(discovery.TokenEndpoint); session.Token = await ObtainTokenAsync(session.TokenEndpoint, cancellationToken); var admin = new Uri(origin, realm.AdminPath); + step = NewRealmStep.UserCount; var before = await ReadCountAsync(admin, session, cancellationToken); + step = NewRealmStep.UserList; var first = await EnumerateAsync(admin, session, cancellationToken); var second = await EnumerateAsync(admin, session, cancellationToken); + step = NewRealmStep.UserCount; var after = await ReadCountAsync(admin, session, cancellationToken); var complete = before == after && first.Count == before && second.Count == before && first.Distinct(StringComparer.Ordinal).Count() == first.Count @@ -83,14 +90,14 @@ public async Task ReadAsync(string issuer, CancellationToken c catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { // A request that timed out: refused like any transport failure. The run's own deadline propagates. - throw new NewRealmUnavailableException(); + throw new NewRealmUnavailableException(step); } catch (Exception failure) when (failure is HttpRequestException or IOException or JsonException or InvalidOperationException or UriFormatException or FormatException or ArgumentException or KeyNotFoundException) { // One fixed refusal: no address, credential or body is carried out of the transport. - throw new NewRealmUnavailableException(); + throw new NewRealmUnavailableException(step); } } diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs index 10583420..539c2a55 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs @@ -14,44 +14,41 @@ namespace LearnStack.Tools.IdentityAuthorityRebind; /// internal static class Program { - private const string InputRefusal = "rebind: outcome=refused_input"; - private static readonly TimeSpan Deadline = TimeSpan.FromMinutes(10); private static readonly TimeSpan StandardInputWait = TimeSpan.FromSeconds(30); public static async Task Main(string[] args) { if (args.Length != 0) { - Console.Out.WriteLine(InputRefusal); - return RebindTool.Refused; + return RebindTool.RefuseInput(Console.Out, RebindToolInput.Fields.Arguments); } - try + // The signals that end a run from outside: an interrupt, a terminate, and the hang-up an SSH session that + // drops sends. Each ends it the way the deadline does: through the token, so the run rolls back, the commit's + // outcome is still reconciled, and the one line is still printed. + using var deadline = new CancellationTokenSource(IdentityIssuerRebind.RunDeadline); + ConsoleCancelEventHandler interrupt = (_, signal) => { - using var deadline = new CancellationTokenSource(Deadline); - - // An interrupt ends the run the way the deadline does: through the token, so the run rolls back, the - // commit's outcome is still reconciled, and the one line is still printed. - Console.CancelKeyPress += (_, signal) => - { - signal.Cancel = true; - deadline.Cancel(); - }; - using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context => - { - context.Cancel = true; - deadline.Cancel(); - }); + signal.Cancel = true; + Cancel(deadline); + }; + Console.CancelKeyPress += interrupt; + using var terminate = Register(PosixSignal.SIGTERM, deadline); + using var hangUp = Register(PosixSignal.SIGHUP, deadline); + try + { var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); if (!RebindToolInput.TryRead( name => Environment.GetEnvironmentVariable(name), - ReadStandardInputLine, + () => ReadStandardInputLine(deadline.Token), configuration, - out var input)) + out var input, + out var field)) { - Console.Out.WriteLine(InputRefusal); - return RebindTool.Refused; + return deadline.IsCancellationRequested + ? RebindTool.Refuse(Console.Out, "cancelled") + : RebindTool.RefuseInput(Console.Out, field); } using var meters = input!.OtlpEndpoint is null @@ -70,23 +67,52 @@ public static async Task Main(string[] args) catch (Exception) #pragma warning restore CA1031 { - Console.Out.WriteLine("rebind: outcome=refused_unexpected"); - return RebindTool.Refused; + return RebindTool.Refuse(Console.Out, "unexpected"); + } + finally + { + Console.CancelKeyPress -= interrupt; + } + } + + private static PosixSignalRegistration Register(PosixSignal signal, CancellationTokenSource deadline) => + PosixSignalRegistration.Create(signal, context => + { + context.Cancel = true; + Cancel(deadline); + }); + + /// A signal can arrive in the instant the run is ending; it must not fault the process then. + private static void Cancel(CancellationTokenSource source) + { + try + { + source.Cancel(); + } + catch (ObjectDisposedException) + { } } /// - /// The operator token's line when it is piped: bounded in time, so a pipe that is never closed refuses the run - /// instead of holding it before its deadline exists. + /// The operator token's line when it is piped: bounded in time and ended by a signal, so a pipe that is never + /// closed refuses the run instead of holding it before its deadline exists. /// - private static string? ReadStandardInputLine() + private static string? ReadStandardInputLine(CancellationToken cancellationToken) { if (!Console.IsInputRedirected) { return null; } - var read = Task.Run(Console.In.ReadLine); - return read.Wait(StandardInputWait) ? read.Result : null; + var read = Task.Run(Console.In.ReadLine, CancellationToken.None); + try + { + return read.Wait(StandardInputWait, cancellationToken) ? read.Result : null; + } + catch (OperationCanceledException) + { + return null; + } } } diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs index cfbcc5c2..b57bc2c1 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs @@ -69,6 +69,14 @@ internal static async Task RunAsync( // already rolled back and reported it. return Refuse(output, "cancelled", correlation); } +#pragma warning disable CA1031 // The tool emits one fixed line, never an exception payload that could carry a credential. + catch (Exception failure) when (failure is not OutOfMemoryException) +#pragma warning restore CA1031 + { + // Nothing the run can throw reaches here after its commit: the database half reports an unknown commit as + // such. So the state is unchanged, and the correlation finds the intent row if one was written. + return Refuse(output, "unexpected", correlation); + } } private static async Task RunAdmittedAsync( @@ -82,7 +90,7 @@ private static async Task RunAdmittedAsync( var clock = new SystemClock(); using var backchannel = new PlatformOperatorBackchannel(); var health = new PlatformOperatorMetadataHealth(clock); - var manager = PlatformOperatorValidation.CreateConfigurationManager(settings, backchannel, health, NullLogger.Instance); + var manager = PlatformOperatorValidation.CreateConfigurationManager(settings, backchannel, health, NullLoggerFactory.Instance); var validation = await new PlatformOperatorTokenValidator(settings, manager, health, clock).ValidateAsync( input.OperatorToken, PlatformOperatorSettings.RebindToolExecutor, correlation, cancellationToken); if (!validation.IsValid) @@ -140,6 +148,11 @@ internal static string Line(IdentityRebindOutcome outcome, string correlation) { var line = new StringBuilder("rebind: outcome=").Append(IdentityRebindMetrics.Label(outcome)) .Append(" correlation=").Append(correlation); + if (outcome.Detail != IdentityRebindDetail.None) + { + line.Append(" detail=").Append(IdentityRebindDetails.Token(outcome.Detail)); + } + if (outcome.LiveSessions is { } sessions) { line.Append(" sessions=").Append(sessions); @@ -157,9 +170,23 @@ internal static string Line(IdentityRebindOutcome outcome, string correlation) return line.ToString(); } + /// + /// Refuses before the database half began, under a closed reason. The reason is also the label the run is counted + /// under, once the process exports meters; the line is what an operator keeps either way. + /// internal static int Refuse(TextWriter output, string reason, string? correlation = null) { - output.WriteLine("rebind: outcome=refused_" + reason + (correlation is null ? string.Empty : " correlation=" + correlation)); + var label = "refused_" + reason; + IdentityRebindMetrics.RecordToolRefusal(label); + output.WriteLine("rebind: outcome=" + label + (correlation is null ? string.Empty : " correlation=" + correlation)); + return Refused; + } + + /// Refuses an input before anything was read from it: the setting's closed name, never its value. + internal static int RefuseInput(TextWriter output, string field) + { + IdentityRebindMetrics.RecordToolRefusal("refused_input"); + output.WriteLine("rebind: outcome=refused_input detail=" + field); return Refused; } diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs index 9b12b71e..5f3d7db1 100644 --- a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Identity.Infrastructure.Bindings; using LearnStack.SharedKernel.Hosting; using LearnStack.SharedKernel.Identifiers; @@ -28,49 +29,99 @@ internal sealed record RebindToolInput( internal const string TicketKey = "LEARNSTACK_REBIND_TICKET"; internal const string RealmClientIdKey = "LEARNSTACK_REBIND_REALM_CLIENT_ID"; internal const string RealmClientSecretKey = "LEARNSTACK_REBIND_REALM_CLIENT_SECRET"; - private const int MaximumTokenCharacters = 16 * 1024; + internal const string AuthorityKey = "Identity__AuthorityId"; + internal const string IssuerKey = "Authentication__Tenant__Issuer"; + internal const string ModeKey = "Deployment__Mode"; - /// Reads and validates the input; false means nothing was usable, and no value is reported. + /// + /// The closed names a refused input is reported under: the setting that was unusable, never its value. The + /// connection string covers a missing value, one that does not parse and one that names another role. + /// + internal static class Fields + { + internal const string Arguments = "arguments"; + internal const string ConnectionString = "connection_string"; + internal const string OperatorToken = "operator_token"; + internal const string RealmClient = "realm_client"; + internal const string AuthorityId = "authority_id"; + internal const string Issuer = "issuer"; + internal const string DeploymentMode = "deployment_mode"; + + /// Every name, so the runbook and a test can hold the set closed. + internal static readonly string[] All = + [Arguments, ConnectionString, OperatorToken, RealmClient, AuthorityId, Issuer, DeploymentMode]; + } + + /// + /// Reads and validates the input. False means nothing was usable; then names the first + /// setting that was not, and no value is reported. + /// internal static bool TryRead( - Func environment, Func standardInput, IConfiguration configuration, out RebindToolInput? input) + Func environment, + Func standardInput, + IConfiguration configuration, + out RebindToolInput? input, + out string field) { input = null; + field = Fields.ConnectionString; var connection = environment(ConnectionStringKey); + if (string.IsNullOrWhiteSpace(connection)) + { + return false; + } + var token = environment(TokenKey); if (string.IsNullOrWhiteSpace(token)) { token = standardInput(); } + field = Fields.OperatorToken; + if (string.IsNullOrWhiteSpace(token) || token.Length > PlatformOperatorTokenValidator.MaximumTokenCharacters) + { + return false; + } + var clientId = environment(RealmClientIdKey); var clientSecret = environment(RealmClientSecretKey); - var ticket = environment(TicketKey); - if (string.IsNullOrWhiteSpace(connection) || string.IsNullOrWhiteSpace(token) || token.Length > MaximumTokenCharacters - || string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret) - || !Guid.TryParseExact(environment("Identity__AuthorityId"), "D", out var authority) || authority == Guid.Empty - || string.IsNullOrEmpty(environment("Authentication__Tenant__Issuer"))) + field = Fields.RealmClient; + if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) + { + return false; + } + + field = Fields.AuthorityId; + if (!Guid.TryParseExact(environment(AuthorityKey), "D", out var authority) || authority == Guid.Empty) + { + return false; + } + + field = Fields.Issuer; + var newIssuer = environment(IssuerKey); + if (string.IsNullOrEmpty(newIssuer)) { return false; } - // The mode is explicit, as it is for the API: it decides whether a loopback operator issuer and the demo - // operator's grant are admitted, so a tool that guessed it could admit what the API refuses. - var modeText = environment("Deployment__Mode"); - if (string.IsNullOrEmpty(modeText) || !Enum.GetNames().Contains(modeText, StringComparer.Ordinal) - || !Enum.TryParse(modeText, ignoreCase: false, out var mode)) + // The mode is explicit, as it is for the API and read the way the API reads it: it decides whether a loopback + // operator issuer and the demo operator's grant are admitted, so a tool that guessed it could admit what the + // API refuses. + field = Fields.DeploymentMode; + if (!DeploymentModeParser.TryParse(environment(ModeKey), out var mode)) { - // Declared names only: an ordinal ("0") or a list would parse to a mode the API itself refuses. return false; } try { + field = Fields.ConnectionString; if (new NpgsqlConnectionStringBuilder(connection).Username != IdentityIssuerRebind.RoleName) { return false; } - var newIssuer = environment("Authentication__Tenant__Issuer")!; + field = Fields.Issuer; var target = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authority), newIssuer); if (mode != DeploymentMode.Development && new Uri(newIssuer).Scheme != Uri.UriSchemeHttps) { @@ -79,12 +130,14 @@ internal static bool TryRead( return false; } + var ticket = environment(TicketKey); input = new RebindToolInput( connection, target, token.Trim(), string.IsNullOrWhiteSpace(ticket) ? null : ticket, clientId, clientSecret, mode, configuration, environment("OTEL_EXPORTER_OTLP_ENDPOINT")); + field = string.Empty; return true; } - catch (ArgumentException) + catch (Exception failure) when (failure is ArgumentException or UriFormatException) { return false; } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs index f690ecba..b00b6029 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs @@ -25,6 +25,36 @@ public interface INewRealmContinuitySource Task ReadAsync(string issuer, CancellationToken cancellationToken = default); } -/// The new realm could not be read completely. A fixed message: no address, credential or body is retained. -public sealed class NewRealmUnavailableException() - : Exception("The new realm could not be read completely."); +/// Where in the read of the new realm a refusal happened: a step, never a value. +public enum NewRealmStep +{ + /// Not attributed to one step. + Unspecified = 0, + + /// The discovery document, or the issuer's own path. + Discovery, + + /// The published key set. + KeySet, + + /// The read-only client's token. + Token, + + /// The administration API's user count. + UserCount, + + /// The administration API's user list. + UserList, +} + +/// +/// The new realm could not be read completely. A fixed message: no address, credential or body is retained, only the +/// step that refused. +/// +/// The step of the read that refused. +public sealed class NewRealmUnavailableException(NewRealmStep step = NewRealmStep.Unspecified) + : Exception("The new realm could not be read completely.") +{ + /// The step of the read that refused. + public NewRealmStep Step { get; } = step; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs index 3bafe22d..2a02cb8e 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs @@ -43,6 +43,19 @@ public sealed class IdentityIssuerRebind(IAuditStore audit, IClock clock) /// The longest the tool waits for the exclusive lock when none is asked for. public static readonly TimeSpan DefaultLockWait = TimeSpan.FromSeconds(30); + /// How long one run may take from its start, proof included; the tool's deadline. + public static readonly TimeSpan RunDeadline = TimeSpan.FromMinutes(10); + + /// The bound the server puts on any one statement of the run. + public static readonly TimeSpan StatementTimeout = TimeSpan.FromSeconds(120); + + /// + /// How long the server lets the main transaction sit idle before it ends it and frees the lock: the fence for a + /// tool that is hung rather than dead. It exceeds , so it never ends a run that is still + /// inside its own deadline. + /// + public static readonly TimeSpan IdleTransactionTimeout = TimeSpan.FromMinutes(15); + /// Runs one rebind to and returns how it ended; it never throws for a refusal. /// The rebind role's connection string; any other role is refused. /// The stable authority and the new issuer. @@ -89,7 +102,7 @@ private async Task RunCoreAsync( var connection = TryNormalize(connectionString, lockWait); if (connection is null) { - return Refused(IdentityRebindRefusal.RoleInvalid); + return Refused(IdentityRebindRefusal.RoleInvalid, IdentityRebindDetail.RoleSession); } NpgsqlConnection? main = null; @@ -97,9 +110,10 @@ private async Task RunCoreAsync( try { main = await OpenAsync(connection, cancellationToken); - if (!await HasExactPostureAsync(main, cancellationToken)) + var posture = await CheckPostureAsync(main, lockWait, cancellationToken); + if (posture != IdentityRebindDetail.None) { - return Refused(IdentityRebindRefusal.RoleInvalid); + return Refused(IdentityRebindRefusal.RoleInvalid, posture); } transaction = await main.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); @@ -130,10 +144,14 @@ await ExecuteAsync(main, transaction, AdvisoryLock, cancellationToken, return new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.LiveSessions, null, sessions); } - var snapshot = await ReadRealmAsync(realm, target.Issuer, cancellationToken); - if (snapshot is null) + NewRealmSnapshot snapshot; + try + { + snapshot = await realm.ReadAsync(target.Issuer, cancellationToken); + } + catch (NewRealmUnavailableException failure) { - return Refused(IdentityRebindRefusal.NewRealmUnavailable); + return Refused(IdentityRebindRefusal.NewRealmUnavailable, RealmDetail(failure.Step)); } if (!string.Equals(snapshot.DiscoveredIssuer, target.Issuer, StringComparison.Ordinal)) @@ -154,7 +172,8 @@ await ExecuteAsync(main, transaction, AdvisoryLock, cancellationToken, IdentityRebindResult.Refused, IdentityRebindRefusal.ContinuityBroken, continuity, sessions); } - // The freeze is asked again at the last moment: the proof may have run for minutes. + // The freeze is asked again at the last moment: the proof may have run for minutes, and a host that never + // qualifies against the authority (the outbox, the ingress poller, the platform role) is not held by the lock. var late = await CountRuntimeSessionsAsync(main, transaction, cancellationToken); if (late > 0) { @@ -178,9 +197,9 @@ await audit.WriteIdentityRebindResultAsync( { return Refused(IdentityRebindRefusal.RebindInProgress); } - catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException) + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or StoredAuthorityException) { - return Refused(IdentityRebindRefusal.DatabaseUnavailable); + return Refused(IdentityRebindRefusal.DatabaseUnavailable, Classify(failure)); } catch (OperationCanceledException) { @@ -250,8 +269,10 @@ await ExecuteAsync(reader, check, "SELECT pg_catalog.pg_advisory_xact_lock_share ? new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.CommitFailed, continuity) : new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); } - catch (Exception reconcile) when (reconcile is NpgsqlException or TimeoutException or InvalidOperationException) + catch (Exception reconcile) when (reconcile is not OutOfMemoryException) { + // Whatever stopped the read, the commit's outcome is not known: never a refusal, which would say + // the state is unchanged. return new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); } } @@ -284,18 +305,24 @@ await ExecuteAsync(reader, check, "SELECT pg_catalog.pg_advisory_xact_lock_share builder.IncludeErrorDetail = false; builder.LogParameters = false; builder.Timeout = 15; - builder.CommandTimeout = 120; + builder.CommandTimeout = (int)StatementTimeout.TotalSeconds; builder.ApplicationName = "learnstack-identity-rebind"; - // The main connection sits idle in its transaction while the new realm is read, so keep it alive through - // middleboxes that cut a quiet connection. + // The main connection sits idle in its transaction while the new realm is read, so the operating system probes + // it: a quiet connection survives a middlebox that cuts one. Npgsql's own KeepAlive is deliberately off: it + // sends a message on the idle connection, and every message the server receives restarts the idle-in- + // transaction clock, so a hung tool would never be ended by the fence below. builder.TcpKeepAlive = true; - builder.KeepAlive = 30; + builder.TcpKeepAliveTime = 30; + builder.TcpKeepAliveInterval = 10; + builder.KeepAlive = 0; builder.Options = FormattableString.Invariant( - $"-c lock_timeout={(int)Math.Max(1, lockWait.TotalMilliseconds)} -c statement_timeout=120000 -c idle_in_transaction_session_timeout=900000"); + $"-c lock_timeout={LockTimeoutMilliseconds(lockWait)} -c statement_timeout={(long)StatementTimeout.TotalMilliseconds} -c idle_in_transaction_session_timeout={(long)IdleTransactionTimeout.TotalMilliseconds}"); return builder.ConnectionString; } + private static int LockTimeoutMilliseconds(TimeSpan lockWait) => (int)Math.Max(1, lockWait.TotalMilliseconds); + private static async Task OpenAsync(string connectionString, CancellationToken cancellationToken) { var connection = new NpgsqlConnection(connectionString); @@ -313,9 +340,18 @@ private static async Task OpenAsync(string connectionString, C /// /// The role is exactly what the migration granted: itself, no attribute that escalates, no membership either way, - /// no privilege on any other relation, and on the three it uses exactly the declared table and column grants. + /// owning nothing, no privilege on any other relation, and on the three it uses exactly the declared table and + /// column grants; and the server applied the session settings the run asked for. Returns the first check that + /// failed, or . /// - private static async Task HasExactPostureAsync(NpgsqlConnection connection, CancellationToken cancellationToken) + /// + /// A relation that belongs to an extension (pg_stat_statements and its PUBLIC-readable views, PostGIS + /// catalogs) is not one the deployment's own schema put there and is not counted. Every other relation in + /// public counts, a privilege held through PUBLIC included, because the role is meant to reach nothing but + /// its three tables. + /// + private static async Task CheckPostureAsync( + NpgsqlConnection connection, TimeSpan lockWait, CancellationToken cancellationToken) { await using var command = new NpgsqlCommand( """ @@ -323,13 +359,23 @@ private static async Task HasExactPostureAsync(NpgsqlConnection connection (r.rolcanlogin AND NOT r.rolinherit AND NOT r.rolbypassrls AND NOT r.rolsuper AND NOT r.rolcreatedb AND NOT r.rolcreaterole AND NOT r.rolreplication) AS attributes_ok, NOT EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR m.roleid = r.oid) AS no_membership, - NOT (has_schema_privilege(r.oid, 'public', 'CREATE') - OR has_database_privilege(r.oid, current_database(), 'CREATE')) AS no_creation, + (NOT (has_schema_privilege(r.oid, 'public', 'CREATE') + OR has_database_privilege(r.oid, current_database(), 'CREATE')) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class o WHERE o.relowner = r.oid) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_proc o WHERE o.proowner = r.oid) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace o WHERE o.nspowner = r.oid)) AS no_creation, (SELECT count(*) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'f') - AND c.relname NOT IN ('identity_authority', 'users', @audit) - AND (has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') - OR has_table_privilege(r.oid, c.oid, 'DELETE,TRUNCATE,TRIGGER'))) AS stray_relations, + WHERE n.nspname = 'public' AND c.relname NOT IN ('identity_authority', 'users', @audit) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d + WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + AND CASE + WHEN c.relkind IN ('r', 'p', 'v', 'm', 'f') + THEN has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') + OR has_table_privilege(r.oid, c.oid, 'DELETE,TRUNCATE,TRIGGER,MAINTAIN') + WHEN c.relkind = 'S' + THEN has_sequence_privilege(r.oid, c.oid, 'USAGE,SELECT,UPDATE') + ELSE false + END) AS stray_relations, (SELECT count(*) FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace @@ -345,24 +391,51 @@ OR has_column_privilege(r.oid, c.oid, a.attnum, 'UPDATE') <> (a.attname = 'issue OR (c.relname = @audit AND (has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT,UPDATE,REFERENCES') OR NOT has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT'))))) AS column_drift, - NOT (has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES') - OR has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES') + NOT (has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN') + OR has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN') OR has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), - 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES')) AS no_table_grants + 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN')) AS no_table_grants, + ((SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'lock_timeout') = @lock + AND (SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'statement_timeout') = @statement + AND (SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'idle_in_transaction_session_timeout') = @idle) AS settings_ok FROM pg_catalog.pg_roles r WHERE r.rolname = current_user """, connection); command.Parameters.AddWithValue("role", RoleName); command.Parameters.AddWithValue("audit", IdentityRebindAuditInstaller.Table); + command.Parameters.AddWithValue("lock", (long)LockTimeoutMilliseconds(lockWait)); + command.Parameters.AddWithValue("statement", (long)StatementTimeout.TotalMilliseconds); + command.Parameters.AddWithValue("idle", (long)IdleTransactionTimeout.TotalMilliseconds); await using var reader = await command.ExecuteReaderAsync(cancellationToken); if (!await reader.ReadAsync(cancellationToken)) { - return false; + return IdentityRebindDetail.RoleSession; + } + + // A check the catalog could not answer is a check that failed: a null never passes. + bool Flag(string column) => reader.GetOrdinal(column) is var at && !reader.IsDBNull(at) && reader.GetBoolean(at); + long Count(string column) => reader.GetOrdinal(column) is var at && !reader.IsDBNull(at) ? reader.GetInt64(at) : 1; + + if (!Flag("session_ok")) + { + return IdentityRebindDetail.RoleSession; + } + + if (!Flag("attributes_ok")) + { + return IdentityRebindDetail.RoleAttributes; + } + + if (!Flag("no_membership")) + { + return IdentityRebindDetail.RoleMembership; + } + + if (!Flag("no_creation") || Count("stray_relations") != 0 || Count("column_drift") != 0 || !Flag("no_table_grants")) + { + return IdentityRebindDetail.RoleGrants; } - bool Flag(string column) => reader.GetBoolean(reader.GetOrdinal(column)); - long Count(string column) => reader.GetInt64(reader.GetOrdinal(column)); - return Flag("session_ok") && Flag("attributes_ok") && Flag("no_membership") && Flag("no_creation") - && Count("stray_relations") == 0 && Count("column_drift") == 0 && Flag("no_table_grants"); + return Flag("settings_ok") ? IdentityRebindDetail.None : IdentityRebindDetail.SessionSettings; } private static async Task<(Guid Authority, string Issuer)> ReadAuthorityAsync( @@ -373,13 +446,13 @@ OR has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), await using var reader = await command.ExecuteReaderAsync(cancellationToken); if (!await reader.ReadAsync(cancellationToken)) { - throw new InvalidOperationException("No identity authority is installed."); + throw new StoredAuthorityException("No identity authority is installed."); } var result = (reader.GetGuid(0), reader.GetString(1)); if (await reader.ReadAsync(cancellationToken)) { - throw new InvalidOperationException("The identity authority is not a singleton."); + throw new StoredAuthorityException("The identity authority is not a singleton."); } return result; @@ -413,6 +486,10 @@ await audit.WriteIdentityRebindIntentAsync( private static async Task CountRuntimeSessionsAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) { + // The server serves pg_stat_activity from a snapshot it keeps for the rest of the transaction, so a second + // count in the same transaction would repeat the first. The snapshot is dropped before every count. + await ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_stat_clear_snapshot()", cancellationToken); + // pg_stat_activity shows another role's session as a row with its role and database even where its query // is hidden, which is all the freeze needs: a session of a runtime role, other than this one's own. await using var command = new NpgsqlCommand( @@ -424,19 +501,6 @@ SELECT count(*) FROM pg_catalog.pg_stat_activity return (int)(long)(await command.ExecuteScalarAsync(cancellationToken))!; } - private static async Task ReadRealmAsync( - INewRealmContinuitySource realm, string issuer, CancellationToken cancellationToken) - { - try - { - return await realm.ReadAsync(issuer, cancellationToken); - } - catch (NewRealmUnavailableException) - { - return null; - } - } - private static async Task> ReadUsersAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, Guid authority, CancellationToken cancellationToken) { @@ -450,7 +514,7 @@ private static async Task> ReadUsersAsync( { if (!Enum.TryParse(reader.GetString(2), ignoreCase: false, out var status) || !Enum.IsDefined(status)) { - throw new InvalidOperationException("A stored user has a status this rebind does not know."); + throw new StoredAuthorityException("A stored user has a status this rebind does not know."); } users.Add(new IdentityRebindStoredUser( @@ -472,7 +536,7 @@ private static async Task ChangeIssuerAsync( command.Parameters.AddWithValue("old", oldIssuer); if (await command.ExecuteNonQueryAsync(cancellationToken) != 1) { - throw new InvalidOperationException("The identity authority issuer did not change as read."); + throw new StoredAuthorityException("The identity authority issuer did not change as read."); } } @@ -523,6 +587,32 @@ private static string ContinuityJson(IdentityRebindContinuityResult counts) => + ",\"reported\":" + counts.Enumerated + ",\"unkeyable\":" + counts.Unkeyable + ",\"unbootstrapped\":" + counts.Unbootstrapped + "}"; - private static IdentityRebindOutcome Refused(IdentityRebindRefusal refusal) => - new(IdentityRebindResult.Refused, refusal); + private static IdentityRebindOutcome Refused( + IdentityRebindRefusal refusal, IdentityRebindDetail detail = IdentityRebindDetail.None) => + new(IdentityRebindResult.Refused, refusal, Detail: detail); + + private static IdentityRebindDetail RealmDetail(NewRealmStep step) => step switch + { + NewRealmStep.Discovery => IdentityRebindDetail.RealmDiscovery, + NewRealmStep.KeySet => IdentityRebindDetail.RealmKeySet, + NewRealmStep.Token => IdentityRebindDetail.RealmToken, + NewRealmStep.UserCount => IdentityRebindDetail.RealmUserCount, + NewRealmStep.UserList => IdentityRebindDetail.RealmUserList, + _ => IdentityRebindDetail.None, + }; + + /// The kind of database failure, from its SQLSTATE or its type and never from its text. + private static IdentityRebindDetail Classify(Exception failure) => failure switch + { + PostgresException { SqlState: PostgresErrorCodes.InvalidPassword or PostgresErrorCodes.InvalidAuthorizationSpecification } + => IdentityRebindDetail.DatabaseAuthentication, + PostgresException { SqlState: PostgresErrorCodes.InsufficientPrivilege } => IdentityRebindDetail.DatabasePermission, + PostgresException { SqlState: PostgresErrorCodes.QueryCanceled } or TimeoutException or NpgsqlException { InnerException: TimeoutException } + => IdentityRebindDetail.DatabaseTimeout, + NpgsqlException => IdentityRebindDetail.DatabaseConnection, + _ => IdentityRebindDetail.AuthorityState, + }; + + /// The stored authority or its users are not what the run read, or are not readable as a rebind needs. + private sealed class StoredAuthorityException(string message) : Exception(message); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs index 7964ba52..2e3c4127 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs @@ -37,16 +37,97 @@ public enum IdentityRebindRefusal Cancelled, } +/// +/// Which check inside a refusal class failed: a closed set that names a step or a kind of failure, never a value, an +/// address or a credential, so the one printed line can tell an operator where to look. +/// +public enum IdentityRebindDetail +{ + None = 0, + + /// The connection is not the role's own session. + RoleSession, + + /// A role attribute escalates: superuser, bypass, creation, replication, login or inheritance. + RoleAttributes, + + /// The role belongs to a role or has a member. + RoleMembership, + + /// The role can create objects, or holds a privilege beyond the declared grants or lacks one of them. + RoleGrants, + + /// The server did not apply the session settings the run asked for, as a pooler's startup handling can. + SessionSettings, + + /// The database could not be reached. + DatabaseConnection, + + /// The database refused the role's credential. + DatabaseAuthentication, + + /// The database refused a statement for lack of a privilege. + DatabasePermission, + + /// A database call exceeded its time limit. + DatabaseTimeout, + + /// The stored authority is missing, is not one row, or changed under the run. + AuthorityState, + + /// The new realm's discovery document or issuer path was unreadable. + RealmDiscovery, + + /// The new realm's key set was unreadable. + RealmKeySet, + + /// The new realm refused the read-only client's token. + RealmToken, + + /// The new realm's user count was refused or out of bounds. + RealmUserCount, + + /// The new realm's user list was refused, unreadable or out of bounds. + RealmUserList, +} + +/// The closed spelling of in the printed line. +public static class IdentityRebindDetails +{ + /// The token of ; empty for . + public static string Token(IdentityRebindDetail detail) => detail switch + { + IdentityRebindDetail.RoleSession => "role_session", + IdentityRebindDetail.RoleAttributes => "role_attributes", + IdentityRebindDetail.RoleMembership => "role_membership", + IdentityRebindDetail.RoleGrants => "role_grants", + IdentityRebindDetail.SessionSettings => "session_settings", + IdentityRebindDetail.DatabaseConnection => "database_connection", + IdentityRebindDetail.DatabaseAuthentication => "database_authentication", + IdentityRebindDetail.DatabasePermission => "database_permission", + IdentityRebindDetail.DatabaseTimeout => "database_timeout", + IdentityRebindDetail.AuthorityState => "authority_state", + IdentityRebindDetail.RealmDiscovery => "realm_discovery", + IdentityRebindDetail.RealmKeySet => "realm_key_set", + IdentityRebindDetail.RealmToken => "realm_token", + IdentityRebindDetail.RealmUserCount => "realm_user_count", + IdentityRebindDetail.RealmUserList => "realm_user_list", + _ => string.Empty, + }; +} + /// The end of one run and what it counted. /// How the run ended. /// The class of a refusal, or . /// The continuity counts, when the proof ran. /// How many sessions of a runtime role the freeze check saw, when it ran. +/// The check inside the class that failed, when the class has more than one. public sealed record IdentityRebindOutcome( IdentityRebindResult Result, IdentityRebindRefusal Refusal = IdentityRebindRefusal.None, IdentityRebindContinuityResult? Continuity = null, - int? LiveSessions = null); + int? LiveSessions = null, + IdentityRebindDetail Detail = IdentityRebindDetail.None); /// Counters of the rebind: runs by outcome, and the continuity proof's counts by class (ADR-0104 § 11). /// @@ -72,6 +153,16 @@ public static class IdentityRebindMetrics private static readonly Counter Continuity = Meter.CreateCounter(ContinuityCounterName, description: "Continuity proof counts by class."); + /// + /// Records a run the tool ended before the database half began, under the label its printed line carries. The + /// labels are the closed set the runbook lists: the operator token's refusal causes and the grant gate's. + /// + public static void RecordToolRefusal(string label) + { + ArgumentException.ThrowIfNullOrWhiteSpace(label); + Runs.Add(1, new KeyValuePair("outcome", label)); + } + /// Records one finished run. public static void Record(IdentityRebindOutcome outcome) { diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index e13dfab8..351e5aef 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -556,6 +556,10 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityDeploymentInstaller", "InstallAsync", ["Npgsql.NpgsqlConnection", LifecycleIdentityBindings + "IdentityAuthorityRegistration", BoundaryCancellation]), Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityQualification", "QualifyCoreAsync", [BoundaryCancellation]), + // ADR-0104: the offline rebind owns two transactions of its own on its confined role, never business + // completion: the intent row commits alone, and the issuer change commits with its result row. + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "CommitAsync"), + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "TryWriteIntentAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "CommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation]), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobTerminalStore", "CommitAsync", @@ -570,6 +574,8 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( ], ["database.RollbackAsync"] = [Owner(InfrastructureAssembly, LifecycleAdapter, "RollbackCoreAsync"), Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "DisposeAsync"), + // ADR-0104: a rebind whose target is already stored ends its own read-only transaction, writing nothing. + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "RunCoreAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeCommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation]), // Read-only metadata probes own a separate connection/transaction and join its actual rollback/cleanup. diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs index f9070b36..17ee047e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs @@ -127,6 +127,9 @@ public async Task Any_Role_But_The_Rebind_Role_Is_Refused_Before_Its_First_State [InlineData(false, "GRANT UPDATE (outcome) ON public.audit_log TO learnstack_identity_rebind", "REVOKE UPDATE (outcome) ON public.audit_log FROM learnstack_identity_rebind")] [InlineData(false, "GRANT DELETE ON public.tenants TO learnstack_identity_rebind", "REVOKE DELETE ON public.tenants FROM learnstack_identity_rebind")] [InlineData(false, "GRANT TRUNCATE ON public.tenants TO learnstack_identity_rebind", "REVOKE TRUNCATE ON public.tenants FROM learnstack_identity_rebind")] + // PostgreSQL 17 added a privilege that locks, vacuums and reindexes a table; it is a grant like any other. + [InlineData(false, "GRANT MAINTAIN ON public.tenants TO learnstack_identity_rebind", "REVOKE MAINTAIN ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT MAINTAIN ON public.users TO learnstack_identity_rebind", "REVOKE MAINTAIN ON public.users FROM learnstack_identity_rebind")] // A declared grant that is missing is drift too: the proof reads users through four columns and changes one. [InlineData(false, "REVOKE UPDATE (issuer) ON public.identity_authority FROM learnstack_identity_rebind", "GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind")] [InlineData(false, "REVOKE INSERT ON public.audit_log FROM learnstack_identity_rebind", "GRANT INSERT ON public.audit_log TO learnstack_identity_rebind")] @@ -141,6 +144,7 @@ public async Task A_Role_That_Holds_Anything_Beyond_Its_Grants_Is_Refused_Before var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid, escalate); + outcome.Detail.Should().NotBe(IdentityRebindDetail.None, "the refusal names which check failed: " + escalate); } finally { @@ -162,6 +166,121 @@ async Task Apply(bool superuser, string sql) } } + [Theory] + // What only the superuser can put there, in this test's own database: a sequence the role may use, and the + // ownership of a function or a schema, which carry every privilege without any grant to read. + [InlineData("CREATE SEQUENCE public.rebind_probe_seq; GRANT USAGE ON SEQUENCE public.rebind_probe_seq TO learnstack_identity_rebind", + "DROP SEQUENCE public.rebind_probe_seq")] + [InlineData("CREATE FUNCTION public.rebind_probe_fn() RETURNS int LANGUAGE sql AS 'SELECT 1'; ALTER FUNCTION public.rebind_probe_fn() OWNER TO learnstack_identity_rebind", + "DROP FUNCTION public.rebind_probe_fn()")] + [InlineData("CREATE SCHEMA rebind_probe_schema AUTHORIZATION learnstack_identity_rebind", + "DROP SCHEMA rebind_probe_schema")] + [InlineData("CREATE VIEW public.rebind_probe_view AS SELECT 1 AS one; GRANT SELECT ON public.rebind_probe_view TO PUBLIC", + "DROP VIEW public.rebind_probe_view")] + public async Task A_Sequence_An_Owned_Object_Or_A_Public_Readable_Relation_The_Deployment_Added_Is_Refused(string add, string remove) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await parent.Postgres.ExecuteAsSuperuserAsync(add, proof.Database); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid, add); + outcome.Detail.Should().Be(IdentityRebindDetail.RoleGrants, add); + } + finally + { + await parent.Postgres.ExecuteAsSuperuserAsync(remove, proof.Database); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task The_Public_Readable_Views_Of_An_Extension_In_The_Public_Schema_Do_Not_Lock_The_Tool_Out() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // pg_stat_statements is the extension a production database most often carries, and it grants its views to PUBLIC. + await parent.Postgres.ExecuteAsSuperuserAsync("CREATE EXTENSION pg_stat_statements SCHEMA public", proof.Database); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Result.Should().Be(IdentityRebindResult.Applied, "an extension's relations are not the deployment's own"); + } + finally + { + await parent.Postgres.ExecuteAsSuperuserAsync("DROP EXTENSION pg_stat_statements", proof.Database); + } + } + + [Fact] + public async Task A_Session_That_Appears_During_The_Realm_Read_Freezes_The_Run_Before_The_Change() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + IAsyncDisposable? late = null; + var realm = new FixedRealm(async (issuer, _) => + { + // A host that never takes the rebind lock starts while the proof runs. The server serves the activity + // view from one snapshot per transaction, so only a count that refreshes it can see this session. + late = await proof.OpenSessionAsync("learnstack_outbox_admin"); + return new NewRealmSnapshot(issuer, 2, true, proof.Subjects); + }); + + try + { + var outcome = await proof.RunAsync(admission, realm, settle: false); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.LiveSessions); + outcome.LiveSessions.Should().Be(1); + outcome.Continuity.Should().NotBeNull("the proof had run: it is the last-moment question that refused"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("only the intent row").Which.Operation + .Should().Be("identity.authority.rebind_attempt"); + } + finally + { + if (late is not null) await late.DisposeAsync(); + } + } + + [Fact] + public async Task The_Idle_Main_Transaction_Is_Never_Touched_By_A_Client_Keepalive_Whatever_The_Connection_String_Asks() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // A client keepalive sends a message on the idle connection, and every message the server receives restarts its + // idle-in-transaction clock: the fence that frees a hung tool's lock would never fire. The tool turns it off. + var asked = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { KeepAlive = 1 }.ConnectionString; // leakwatch:ignore:database-connection-string + DateTime? first = null; + DateTime? second = null; + var realm = new FixedRealm(async (issuer, token) => + { + await using var probe = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.RebindConnection, token); + first = await StateChangeOfTheMainSessionAsync(probe); + await Task.Delay(TimeSpan.FromSeconds(3.5), token); + second = await StateChangeOfTheMainSessionAsync(probe); + return new NewRealmSnapshot(issuer, 2, true, proof.Subjects); + }); + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), realm, connection: asked); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + first.Should().NotBeNull("the main transaction sits idle while the realm is read"); + second.Should().Be(first, "nothing reached the idle transaction in between"); + + static async Task StateChangeOfTheMainSessionAsync(NpgsqlConnection probe) + { + await using var command = new NpgsqlCommand( + """ + SELECT state_change FROM pg_catalog.pg_stat_activity + WHERE usename = current_user AND application_name = 'learnstack-identity-rebind' + AND state = 'idle in transaction' AND pid <> pg_catalog.pg_backend_pid() + """, probe); + return (DateTime?)await command.ExecuteScalarAsync() is { } at ? at : null; + } + } + [Fact] public async Task A_Rebind_That_Is_Already_Running_Makes_The_Second_One_Wait_Then_Refuse_Without_A_Row() { @@ -363,10 +482,19 @@ public async Task A_Database_That_Cannot_Be_Reached_And_A_Malformed_Connection_S await using var proof = await Proof.CreateAsync(parent, active: 1); var closedPort = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Host = "127.0.0.1", Port = 1, Timeout = 2 }.ConnectionString; - (await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: closedPort)) - .Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); - (await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: "Host=;;=Username")) - .Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + var wrongPassword = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Password = "not-the-password" }.ConnectionString; // leakwatch:ignore:database-connection-string + + var unreachable = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: closedPort); + unreachable.Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); + unreachable.Detail.Should().Be(IdentityRebindDetail.DatabaseConnection); + + var refused = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: wrongPassword); + refused.Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); + refused.Detail.Should().Be(IdentityRebindDetail.DatabaseAuthentication, "a credential the server refuses is not an outage"); + + var malformed = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: "Host=;;=Username"); + malformed.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + malformed.Detail.Should().Be(IdentityRebindDetail.RoleSession); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs index 3b780f69..750510f2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs @@ -56,10 +56,10 @@ public async Task The_Tool_Rebinds_With_A_Token_In_The_Environment_And_A_Repeat_ } [Theory] - [InlineData("no-token", "refused_input")] - [InlineData("argument", "refused_input")] - [InlineData("no-realm-credential", "refused_input")] - [InlineData("no-mode", "refused_input")] + [InlineData("no-token", "refused_input detail=operator_token")] + [InlineData("argument", "refused_input detail=arguments")] + [InlineData("no-realm-credential", "refused_input detail=realm_client")] + [InlineData("no-mode", "refused_input detail=deployment_mode")] [InlineData("wrong-audience", "refused_operator_token_token_audience")] [InlineData("wrong-issuer", "refused_operator_token_token_issuer")] [InlineData("expired", "refused_operator_token_token_expired")] @@ -76,10 +76,12 @@ public async Task A_Refusal_Before_The_Database_Leaves_The_Issuer_And_Writes_No_ var result = await run.ExecuteAsync(scenario); result.Code.Should().Be(2); - (result.Out + result.Error).Should().Contain(expected); + result.Out.Should().StartWith("rebind: outcome=" + expected); + result.Out.Trim().Split('\n').Should().ContainSingle("one fixed line, on standard output and nowhere else"); + result.Error.Should().BeEmpty(); run.AssertNoValueLeaked(result); (await run.IssuerAsync()).Should().Be(run.OldIssuer); - (await run.RebindRowsAsync()).Should().Be(0, "a refusal at the gate is a counter and a log, never a durable row"); + (await run.RebindRowsAsync()).Should().Be(0, "a refusal at the gate writes no durable row: the line and the counter are its record"); } [Fact] @@ -90,7 +92,7 @@ public async Task A_Database_Role_That_Is_Not_The_Rebind_Role_Is_Refused() var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, connection: run.AppConnection); result.Code.Should().Be(2); - (result.Out + result.Error).Should().Contain("refused_input", "the connection string is not the rebind role's"); + result.Out.Should().StartWith("rebind: outcome=refused_input detail=connection_string", "the string is not the rebind role's"); run.AssertNoValueLeaked(result); (await run.IssuerAsync()).Should().Be(run.OldIssuer); } @@ -123,6 +125,50 @@ public async Task A_Rebind_Role_Session_Beside_A_Live_Application_Session_Is_Fro (await run.IssuerAsync()).Should().Be(run.OldIssuer); } + [Fact] + public async Task A_New_Realm_That_Refuses_The_Client_Names_The_Step_And_Never_The_Address() + { + await using var run = await Run.StartAsync(parent); + run.Realm.Fail("token-denied"); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_new_realm_unavailable correlation=rebind-") + .And.EndWith(" detail=realm_token" + Environment.NewLine.TrimEnd('\r'), "the step is named, nothing else"); + result.Error.Should().BeEmpty(); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + [Theory] + [InlineData("TERM")] + [InlineData("HUP")] + public async Task A_Signal_During_The_Realm_Read_Rolls_Back_Reports_Cancelled_And_Keeps_The_Intent_Row(string signal) + { + await using var run = await Run.StartAsync(parent); + run.Realm.Fail("discovery-hang"); + + // The intent row is written only after the signal handlers are in place, so its appearance is the readiness + // the signal waits for: no sleep guesses how long the runtime takes to start. + // A process started under `nohup` inherits an ignored hang-up and keeps ignoring it, as it should, so the case + // starts the tool with the default disposition restored: a tool the operator runs in tmux has it. + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, resetHangUp: signal == "HUP", whileRunning: async child => + { + await run.WaitForRebindRowAsync(TimeSpan.FromSeconds(60)); + using var kill = Process.Start("kill", ["-" + signal, child.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)])!; + await kill.WaitForExitAsync(); + }); + + result.Code.Should().Be(2, result.Text); + result.Out.Should().StartWith("rebind: outcome=refused_cancelled correlation=rebind-"); + result.Out.Trim().Split('\n').Should().ContainSingle(); + result.Error.Should().BeEmpty(); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal("identity.authority.rebind_attempt"); + } + private sealed record Result(int Code, string Out, string Error) { internal string Text => Out + Error; @@ -149,6 +195,8 @@ private Run(IdentityPublicReadFixture database, TenantAuthenticationIssuer @oper internal string AppConnection => _database.AppConnectionString; + internal FakeKeycloakRealm Realm => _realm; + internal static async Task StartAsync(PublicReadFixture parent, int reportedUsers = 2) { var users = new[] { UserId.From(Guid.CreateVersion7()), UserId.From(Guid.CreateVersion7()) }; @@ -202,9 +250,10 @@ internal Task ExecuteAsync(string scenario) internal async Task ExecuteAsync( string? token, bool tokenOnInput, string? argument = null, bool realmCredential = true, string? mode = "Development", - string? grant = Grant, bool operatorIssuer = true, string? connection = null) + string? grant = Grant, bool operatorIssuer = true, string? connection = null, + Func? whileRunning = null, bool resetHangUp = false) { - var start = new ProcessStartInfo("dotnet") + var start = new ProcessStartInfo(resetHangUp ? "perl" : "dotnet") { WorkingDirectory = AppContext.BaseDirectory, RedirectStandardOutput = true, @@ -212,6 +261,13 @@ internal async Task ExecuteAsync( RedirectStandardInput = true, UseShellExecute = false, }; + if (resetHangUp) + { + start.ArgumentList.Add("-e"); + start.ArgumentList.Add("$SIG{HUP} = 'DEFAULT'; exec @ARGV"); + start.ArgumentList.Add("dotnet"); + } + start.ArgumentList.Add("exec"); start.ArgumentList.Add("--runtimeconfig"); start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); @@ -256,7 +312,11 @@ internal async Task ExecuteAsync( if (token is not null && tokenOnInput) await child.StandardInput.WriteLineAsync(token); child.StandardInput.Close(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(90)); - try { await child.WaitForExitAsync(deadline.Token); } + try + { + if (whileRunning is not null) await whileRunning(child); + await child.WaitForExitAsync(deadline.Token); + } finally { if (!child.HasExited) @@ -303,6 +363,16 @@ internal async Task RebindRowsAsync() return (long)(await command.ExecuteScalarAsync())!; } + internal async Task WaitForRebindRowAsync(TimeSpan within) + { + var clock = Stopwatch.StartNew(); + while (await RebindRowsAsync() == 0) + { + if (clock.Elapsed > within) throw new TimeoutException("The tool never wrote its intent row."); + await Task.Delay(100); + } + } + internal async Task> OperationsAsync(string correlation) { await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs index 11e3fe6b..15c5e160 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs @@ -249,12 +249,15 @@ internal Task UnpauseOwnedServerAsync(CancellationToken cancellationToken = defa /// Every caller reverts what it did in a finally: the cluster is shared, /// and an isolation suite running against a bypass role is vacuous. /// - public async Task ExecuteAsSuperuserAsync(string sql) + /// The statement batch. + /// A database other than the container's own, for an object that belongs to one database. + public async Task ExecuteAsSuperuserAsync(string sql, string? database = null) { const int timeoutSeconds = 30; using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); var connectionString = new NpgsqlConnectionStringBuilder(_container.GetConnectionString()) { + Database = database ?? new NpgsqlConnectionStringBuilder(_container.GetConnectionString()).Database, // This helper retains the container superuser privately. Every call // owns a physical connection, outside any caller's ambient transaction. Pooling = false, diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs index 7a2b6edd..e9395589 100644 --- a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -88,6 +88,12 @@ private void Map(WebApplication app) return Task.CompletedTask; } + if (_failure == "discovery-hang") + { + // The realm never answers: the request ends only when its caller gives up or goes away. + return Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, context.RequestAborted); + } + var foreign = ForeignOrigin ?? "http://127.0.0.1:1"; var jwks = _failure == "jwks-other-origin" ? foreign + "/realms/learnstack/keys" : Issuer + "/keys"; var token = _failure == "token-other-origin" diff --git a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs index 1b350364..1e4f8a0a 100644 --- a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs @@ -143,17 +143,17 @@ public async Task A_Discovery_Issuer_That_Differs_Is_Reported_As_It_Is_And_No_Cr } [Theory] - [InlineData("jwks-other-origin")] - [InlineData("token-other-origin")] - [InlineData("token-denied")] - [InlineData("admin-denied")] - [InlineData("users-redirect")] - [InlineData("discovery-redirect")] - [InlineData("users-not-an-array")] - [InlineData("user-without-id")] - [InlineData("count-not-a-number")] - [InlineData("oversized-token-answer")] - public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names_Nothing(string failure) + [InlineData("jwks-other-origin", NewRealmStep.Discovery)] + [InlineData("token-other-origin", NewRealmStep.Discovery)] + [InlineData("discovery-redirect", NewRealmStep.Discovery)] + [InlineData("token-denied", NewRealmStep.Token)] + [InlineData("oversized-token-answer", NewRealmStep.Token)] + [InlineData("admin-denied", NewRealmStep.UserCount)] + [InlineData("count-not-a-number", NewRealmStep.UserCount)] + [InlineData("users-redirect", NewRealmStep.UserList)] + [InlineData("users-not-an-array", NewRealmStep.UserList)] + [InlineData("user-without-id", NewRealmStep.UserList)] + public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names_Only_The_Step(string failure, NewRealmStep step) { await using var realm = await FakeKeycloakRealm.StartAsync(3); realm.Fail(failure); @@ -161,6 +161,7 @@ public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names var act = async () => await realm.ReadAsync(); var thrown = (await act.Should().ThrowAsync()).Which; + thrown.Step.Should().Be(step, "the refusal says where the read stopped, which is all an operator needs to look"); thrown.Message.Should().Be("The new realm could not be read completely."); thrown.Message.Should().NotContain(ClientSecret).And.NotContain("127.0.0.1").And.NotContain("realm-token"); thrown.InnerException.Should().BeNull("no transport exception is carried out"); diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs index b28b0764..ddc01d0a 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs @@ -190,7 +190,7 @@ private PlatformOperatorTokenValidator ValidatorFor(TenantAuthenticationIssuer i DeploymentMode.Development)!; var health = new PlatformOperatorMetadataHealth(new SystemClock()); var manager = PlatformOperatorValidation.CreateConfigurationManager( - settings, backchannel ?? _backchannel, health, NullLogger.Instance); + settings, backchannel ?? _backchannel, health, NullLoggerFactory.Instance); return new PlatformOperatorTokenValidator(settings, manager, health, new SystemClock()); } diff --git a/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs index fc73f86b..74366869 100644 --- a/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.Metrics; using FluentAssertions; using LearnStack.Modules.Identity.Infrastructure.Bindings; using LearnStack.Tools.IdentityAuthorityRebind; @@ -26,8 +27,11 @@ public sealed class RebindToolInputTests }; private static bool Read(Dictionary environment, out RebindToolInput? input, string? line = null) => + Read(environment, out input, out _, line); + + private static bool Read(Dictionary environment, out RebindToolInput? input, out string field, string? line = null) => RebindToolInput.TryRead(name => environment.GetValueOrDefault(name), () => line, - new ConfigurationBuilder().Build(), out input); + new ConfigurationBuilder().Build(), out input, out field); [Fact] public void A_Complete_Environment_Is_Read_And_The_Token_Is_Trimmed() @@ -42,36 +46,59 @@ public void A_Complete_Environment_Is_Read_And_The_Token_Is_Trimmed() } [Theory] - [InlineData("ConnectionStrings__IdentityRebind")] - [InlineData("Identity__AuthorityId")] - [InlineData("Authentication__Tenant__Issuer")] - [InlineData("Deployment__Mode")] - [InlineData("LEARNSTACK_OPERATOR_TOKEN")] - [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_ID")] - [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_SECRET")] - public void Each_Required_Value_Missing_Refuses(string missing) + [InlineData("ConnectionStrings__IdentityRebind", "connection_string")] + [InlineData("Identity__AuthorityId", "authority_id")] + [InlineData("Authentication__Tenant__Issuer", "issuer")] + [InlineData("Deployment__Mode", "deployment_mode")] + [InlineData("LEARNSTACK_OPERATOR_TOKEN", "operator_token")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_ID", "realm_client")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_SECRET", "realm_client")] + public void Each_Required_Value_Missing_Refuses_Naming_Only_The_Setting(string missing, string field) { var environment = Valid(); environment.Remove(missing); - Read(environment, out _).Should().BeFalse(); + Read(environment, out _, out var named).Should().BeFalse(); + named.Should().Be(field); + RebindToolInput.Fields.All.Should().Contain(named, "the name is one of the closed set the runbook lists"); + } + + [Fact] + public void The_Closed_Field_Names_Are_Distinct_Lowercase_Tokens() + { + RebindToolInput.Fields.All.Should().OnlyHaveUniqueItems() + .And.OnlyContain(name => name.All(character => char.IsAsciiLetterLower(character) || character == '_')); } [Theory] [InlineData("0")] [InlineData("1")] [InlineData("Development,SaaS")] - [InlineData("development")] - [InlineData("saas")] [InlineData("Production")] - [InlineData(" Development")] - public void The_Deployment_Mode_Is_A_Declared_Name_Exactly(string mode) + [InlineData("")] + public void The_Deployment_Mode_Is_A_Declared_Name_And_Never_An_Ordinal_Or_A_List(string mode) + { + var environment = Valid(); + environment["Deployment__Mode"] = mode; + + Read(environment, out _, out var field).Should().BeFalse("the API refuses ordinals and lists, so the tool must not guess a mode"); + field.Should().Be("deployment_mode"); + } + + [Theory] + [InlineData("development", LearnStack.SharedKernel.Hosting.DeploymentMode.Development)] + [InlineData("saas", LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS)] + [InlineData(" SaaS ", LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS)] + [InlineData("SELFHOSTEDAIRGAPPED", LearnStack.SharedKernel.Hosting.DeploymentMode.SelfHostedAirGapped)] + public void The_Deployment_Mode_Is_Read_The_Way_The_Api_Reads_It_Without_Regard_To_Case_Or_Padding( + string mode, LearnStack.SharedKernel.Hosting.DeploymentMode expected) { var environment = Valid(); environment["Deployment__Mode"] = mode; environment["Authentication__Tenant__Issuer"] = "https://new.example.test/realms/learnstack"; - Read(environment, out _).Should().BeFalse("the API refuses ordinals and lists, so the tool must not guess a mode"); + Read(environment, out var input).Should().BeTrue("an API started with this spelling accepts it, so the tool must too"); + input!.Mode.Should().Be(expected); } [Theory] @@ -115,6 +142,47 @@ public void The_Target_Issuer_Follows_The_Grammar_And_Loopback_Http_Is_Developme Read(environment, out _).Should().Be(accepted); } + [Fact] + public void The_Printed_Line_Names_The_Detail_After_The_Correlation_And_Before_The_Counts() + { + var line = RebindTool.Line( + new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.RoleInvalid, null, 2, IdentityRebindDetail.RoleGrants), + "rebind-abc"); + + line.Should().Be("rebind: outcome=refused_role_invalid correlation=rebind-abc detail=role_grants sessions=2"); + RebindTool.Line(new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied), "rebind-abc") + .Should().Be("rebind: outcome=already_applied correlation=rebind-abc", "a class with one cause carries no detail"); + } + + [Fact] + public void A_Refusal_Before_The_Database_Is_Printed_And_Counted_Under_The_Same_Label() + { + var seen = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, subscriber) => + { + if (instrument.Meter.Name == IdentityRebindMetrics.MeterName) subscriber.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag.Key == "outcome") seen.Add((string)tag.Value!); + } + }); + listener.Start(); + var output = new StringWriter(); + + RebindTool.RefuseInput(output, RebindToolInput.Fields.ConnectionString).Should().Be(RebindTool.Refused); + RebindTool.Refuse(output, "operator_missing_permission", "rebind-abc").Should().Be(RebindTool.Refused); + + output.ToString().Replace("\r", string.Empty).Split('\n', StringSplitOptions.RemoveEmptyEntries).Should().Equal( + "rebind: outcome=refused_input detail=connection_string", + "rebind: outcome=refused_operator_missing_permission correlation=rebind-abc"); + // The meter is process-wide and other cases record on it too, so the labels are looked for, not counted. + seen.Should().Contain(["refused_input", "refused_operator_missing_permission"]); + } + [Fact] public void The_Token_Falls_Back_To_One_Line_Of_Standard_Input_And_Never_To_An_Argument() { diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs new file mode 100644 index 00000000..1145088f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs @@ -0,0 +1,29 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// The closed detail tokens of a refusal and the timing invariants the run's fences rely on (ADR-0104). +public sealed class IdentityRebindDetailTests +{ + [Fact] + public void Every_Detail_Has_Its_Own_Lowercase_Token_And_None_Has_None() + { + var tokens = Enum.GetValues().Where(detail => detail != IdentityRebindDetail.None) + .Select(IdentityRebindDetails.Token).ToList(); + + tokens.Should().OnlyHaveUniqueItems().And.NotContain(string.Empty); + tokens.Should().OnlyContain(token => token.All(character => char.IsAsciiLetterLower(character) || character == '_')); + IdentityRebindDetails.Token(IdentityRebindDetail.None).Should().BeEmpty(); + } + + [Fact] + public void The_Servers_Idle_Fence_Outlasts_The_Run_Deadline_And_The_Statement_Bound_Fits_Inside_It() + { + // The fence frees the lock of a tool that is hung, never of one still inside its own deadline. + IdentityIssuerRebind.IdleTransactionTimeout.Should().BeGreaterThan( + IdentityIssuerRebind.RunDeadline + IdentityIssuerRebind.DefaultLockWait); + IdentityIssuerRebind.StatementTimeout.Should().BeLessThan(IdentityIssuerRebind.RunDeadline); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs new file mode 100644 index 00000000..d4de8bc7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs @@ -0,0 +1,48 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Hosting; +using Xunit; + +namespace LearnStack.Tests.Unit.SharedKernel; + +/// The one reading of a deployment mode that the API and the offline tools share. +public sealed class DeploymentModeParserTests +{ + [Theory] + [InlineData("Development", DeploymentMode.Development)] + [InlineData("saas", DeploymentMode.SaaS)] + [InlineData(" Dedicated ", DeploymentMode.Dedicated)] + [InlineData("SELFHOSTEDONLINE", DeploymentMode.SelfHostedOnline)] + [InlineData("selfHostedAirGapped", DeploymentMode.SelfHostedAirGapped)] + public void A_Declared_Name_Is_Read_Without_Regard_To_Case_Or_Padding(string text, DeploymentMode expected) + { + DeploymentModeParser.TryParse(text, out var mode).Should().BeTrue(); + + mode.Should().Be(expected); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("0")] + [InlineData("1")] + [InlineData("-1")] + [InlineData("Development,SaaS")] + [InlineData("Development SaaS")] + [InlineData("Production")] + [InlineData("Sass")] + public void Anything_That_Is_Not_A_Declared_Name_Is_Refused_Ordinals_And_Lists_Included(string? text) + { + DeploymentModeParser.TryParse(text, out _).Should().BeFalse(); + } + + [Fact] + public void Every_Declared_Name_Is_Accepted_As_It_Is_Spelled() + { + foreach (var name in Enum.GetNames()) + { + DeploymentModeParser.TryParse(name, out var mode).Should().BeTrue(name); + mode.ToString().Should().Be(name); + } + } +} diff --git a/docs/decisions/0104-controlled-issuer-rebind.md b/docs/decisions/0104-controlled-issuer-rebind.md index a8148542..2a63d80f 100644 --- a/docs/decisions/0104-controlled-issuer-rebind.md +++ b/docs/decisions/0104-controlled-issuer-rebind.md @@ -188,9 +188,9 @@ and the runbook follow. Step 3 of the platform-authority packet implements the decision. Each item below fixes something the Decision left open or states where the code meets it. Item 4 widens the -freeze check beyond the roles § 5 lists and item 10 records a residual the Decision did -not state; none of them changes the Decision's choice of option, the role's grants or -the proof's rules. +freeze check beyond the roles § 5 lists, and items 10 and 11 record residuals the +Decision did not state; none of them changes the Decision's choice of option, the +role's grants or the proof's rules. 1. **Where the code lives.** The database half, `IdentityIssuerRebind`, lives in the Identity module's Infrastructure `Bindings` namespace so unit and integration @@ -223,7 +223,10 @@ the proof's rules. still a session. The check reports a count and never a session's identity. A pooled connection stays a session until its idle lifetime ends, so the runbook's stop step includes waiting for it. The check runs before the realm is read and again just - before the change. + before the change, and each time it first drops the server's per-transaction snapshot + of the activity view, which would otherwise return the first count again. A host that + never takes the rebind lock (the outbox dispatcher, the ingress poller, the platform + role) is held only by this check. 5. **"Reads the new value" needs a comparison, and "waits" is bounded.** A lock alone only makes a creation wait. Authority qualification takes the shared lock and then reads under a fresh snapshot, and the User-creation admission takes the shared lock, @@ -237,39 +240,69 @@ the proof's rules. own comparison. 6. **The role is checked before it is used.** The tool refuses unless the session is the rebind role, it holds no inherited, bypass, superuser, creation or replication - attribute and no membership, no privilege on any other relation, and exactly the - declared grants on the three it uses, compared column by column in both directions. + attribute, no membership, no owned object and no privilege on any other relation (a + sequence included, and the maintenance privilege of PostgreSQL 17), and exactly the + declared grants on the three it uses, compared column by column in both directions. A + relation that belongs to an extension is not counted, so a production database that + carries `pg_stat_statements` in `public` is not locked out; any other + `PUBLIC`-readable relation in `public` is. The tool also reads the session's own + `lock_timeout`, `statement_timeout` and `idle_in_transaction_session_timeout` from + the server and refuses when they are not what it asked for, as a connection pooler + that drops startup options would leave them. A refusal names the check that failed + with a closed `detail`, never a value. 7. **Continuity details the Decision left open.** A Closing user that still holds its subject is judged by neither rule, because closure owns that transition; a Closing user that holds only its key is judged like a Closed one. A reported subject that - cannot be a LearnStack subject is counted and cannot equal any stored one. Presence is - the exact ordinal subject. The new realm is read in full twice and the reads must + cannot be a LearnStack subject is counted and cannot equal any stored one. Presence + is the exact ordinal subject. The new realm is read in full twice and the reads must report the same users with none repeated, so a realm that changes while it is read is refused; a realm above 200,000 users is refused because the proof cannot finish in the tool's ten-minute deadline; a token that expires mid-enumeration is acquired again once per request; and the credential is sent only after the realm's discovery document names the target issuer. -8. **Inputs and exit codes.** The operator token comes from the environment or one line of - standard input and the ticket, the realm client and its secret from the environment; - an argument is refused. The deployment mode is a declared name exactly, because it - decides whether a loopback operator issuer and the demo operator's grant are admitted, - and outside Development the target issuer must be HTTPS. The tool prints one line of - classes and counts to standard output, with the correlation id that finds the rows, - and exits `0` for applied or already applied, `2` for a refusal that left the state - unchanged and `3` when the commit's outcome could not be read back. An interrupt or a - termination signal ends the run as the deadline does. +8. **Inputs and exit codes.** The operator token comes from the environment or one line + of standard input and the ticket, the realm client and its secret from the + environment; an argument is refused. The deployment mode is a declared name, read as + the API reads it (case and padding do not matter, an ordinal or a list is refused), + because it decides whether a loopback operator issuer and the demo operator's grant + are admitted, and outside Development the target issuer must be HTTPS. The tool + prints one line of classes and counts to standard output, with the correlation id + that finds the rows, a closed `detail` where a class has more than one cause, and + exits `0` for applied or already applied, `2` for a refusal that left the state + unchanged and `3` when the commit's outcome could not be read back. A failure to read + back an unknown commit is `unknown`, never a refusal. An interrupt, a termination + signal or a hang-up ends the run as the deadline does. 9. **Signals in a short-lived process.** The counters are defined in the library and - exported by the tool only when an OTLP endpoint is configured in its environment; - the printed line and the audit rows are the record otherwise. -10. **What the credential holder can do, and "the same realm path".** The tool checks the - operator's token, grant and attribution; the database does not force them. The role - holds `UPDATE (issuer)` and can insert a row of the admitted shape, so whoever holds - its password can change the issuer, or record a rebind that did not happen, without - the tool. The runbook therefore keeps the password apart from the operator's - identity and retires it after the window. A database-enforced pairing of the change - and its result row would need a confined definer that reads `audit_log`, and is the - maintainer's decision. "The same realm path" means the realm name: the issuer must - still end in `/realms/learnstack`, and the path before it may change. + exported by the tool only when an OTLP endpoint is configured in its environment, + under the label the printed line carries, including the refusals that happen before + the database is reached. The tool writes no log. The printed line and the audit rows + are the record otherwise, and a refusal at the operator gate leaves no row by design, + so the line is its only record unless the counter is exported. +10. **What the credential holder can do, and "the same realm path".** The tool checks + the operator's token, grant and attribution; the database does not force them. The + role holds `UPDATE (issuer)` and can insert a row of the admitted shape, so whoever + holds its password can change the issuer, or record a rebind that did not happen, + without the tool. The platform and outbox roles bypass row security and can insert + `audit_log` rows too, so the rebind rows are evidence under the same trust as every + other platform-sentinel row; no trigger confines these two operations to the rebind + role as one confines `identity.user.create`. The runbook keeps the password apart + from the operator's identity and retires it after the window; the grant and the + password sit in the tool's one environment, so that separation is a practice. A + database-enforced pairing of the change and its result row would need a confined + definer that reads `audit_log`, and is the maintainer's decision. "The same realm + path" means the realm name: the issuer must still end in `/realms/learnstack`, and + the path before it may change. +11. **What the move out of the API project loosened.** The operator token profile's + reader, `PlatformOperatorTokenProfile.TryRead`, is a public method of Infrastructure + so that the tool can call it, and it mints the witness the operator gate accepts. + Before the move the API project kept it internal and the compiler confined it. Its + callers are now confined by two census rules, the source census of the witness + minter and the IL census of the validator's callers, which cover the production + assemblies; a test assembly or reflection is outside them. The tool also leaves the + server's idle fence in force: it turns Npgsql's application keepalive off, because a + keepalive message restarts the server's idle-in-transaction clock, and asks the + operating system for TCP probes instead, so a hung tool is ended at fifteen minutes + and its lock freed. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 8d743a61..fc61f00b 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -35,7 +35,7 @@ the request exists, and off-path events register by slug when their writer lands | Membership including Profile/Assignments | `identity.membership.recover_admin` | **MUST** (`security-event`) | `OperatorRecoverAdminCommand`, the operator's replacement administrator for a tenant with none active; one Membership transaction on the operator source, refused while any administrator is active. | | MembershipProfile, captured under Membership | `identity.membership_profile.set_seed_profile` | **MUST** (`update`) | `SetSeedMembershipProfile`; same Membership transaction. The slug matches the gated sub-resource while the row's subject remains its owning aggregate. | | Identity authority | `identity.authority.rebind_attempt` `(off-path)` | **MUST** (`security-event`) | The controlled issuer rebind's intent row ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)): committed on the offline tool's own short transaction, by the confined `learnstack_identity_rebind` role, before the main transaction begins, so an aborted attempt is on record. Platform sentinel tenant, outcome `indeterminate`, no actor, `metadata.operator` with the ticket. Written through the witness-bound `WriteIdentityRebindIntentAsync`, never the pipeline. | -| Identity authority | `identity.authority.rebind` `(off-path)` | **MUST** (`security-event`) | The rebind's result row: written on the same transaction as the one-column issuer change, so it commits with the change or not at all, and a forced audit failure rolls the change back. Outcome `success`, before and after issuer, continuity counts and no subject in `metadata`. Written through the witness-bound `WriteIdentityRebindResultAsync`. | +| Identity authority | `identity.authority.rebind` `(off-path)` | **MUST** (`security-event`) | The rebind's result row: written on the same transaction as the one-column issuer change, so it commits with the change or not at all, and a forced audit failure rolls the change back. Outcome `success`; the old and new issuer are in `before_state` and `after_state`, and `metadata` holds the operator attribution and the continuity counts, with no subject. Written through the witness-bound `WriteIdentityRebindResultAsync`. | | Authorization decision | `identity.authorization.deny` `(off-path)` | **MUST** (`security-event`) | Central HTTP/application/resource denial owner; one decided invocation event, separate from ordinary plural resource intents. No tenant override or host suppression budget. | | Membership directory | `identity.membership.list` | **MUST** (`read-sensitive`) | Internal `ListMembershipsQuery` under existing Tenant `identity.membership.admin`; ordinary ReadWrite owner commits its row before disclosure. No HTTP activation follows from its catalogue entry. | | Role including grants | `identity.role.change_grants` | **MUST** (`security-event`) | `ChangeRoleGrantsCommand`; one Role root and contained grant diff, expected row version and fresh post-lock authority recheck; success/audit share the transaction. | diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md index 2263a475..92f1b82f 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -29,6 +29,7 @@ permission admission. An attribute, realm role or SystemActor value grants no ro | `OperatorInitializeRoleCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | One finite template of the target tenant, before any Membership exists; idempotent on the operator's Role id ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) | | `OperatorCreateFirstAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | The first tenant-wide administrator of a tenant with no Membership history; the person is named by provider subject and must be an Active, bootstrapped User | | `OperatorRecoverAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | A replacement administrator while no Active tenant-wide administrator Membership exists; the last-administrator guard is the database's and is unchanged | +| `IdentityIssuerRebind` (an offline tool, not a command or a route) | Platform `platform.identity_authority.admin`, `PlatformOperator` token | The operator's per-act grant for the rebind operation only, checked by the operator gate in the tool; the write itself runs on the confined `learnstack_identity_rebind` role, with no tenant context ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)) | Scope selection derives from immutable target Membership/validated declaration, never a claimed scope string. Finite metadata alternatives count the exact five diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 5ec90910..be540316 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,15 +509,16 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 802 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 790 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines - - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 107 lines - - [P03-9 Step 1 — review round 2 and its fixes (2026-11-19)](#p03-9-step-1--review-round-2-and-its-fixes-2026-11-19) — 116 lines - - [P03-9 Step 2 — production onboarding (2026-11-19)](#p03-9-step-2--production-onboarding-2026-11-19) — 126 lines + - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 137 lines - [P03-9 Step 2 — review round 1 and its fixes (2026-11-19)](#p03-9-step-2--review-round-1-and-its-fixes-2026-11-19) — 46 lines - [P03-9 Step 2 — review round 2 and its fixes (2026-11-19)](#p03-9-step-2--review-round-2-and-its-fixes-2026-11-19) — 35 lines + - [P03-9 Step 3 — controlled issuer rebind (2026-11-20)](#p03-9-step-3--controlled-issuer-rebind-2026-11-20) — 107 lines + - [P03-9 Step 3 — review round 1 and its fixes (2026-11-20)](#p03-9-step-3--review-round-1-and-its-fixes-2026-11-20) — 23 lines + - [P03-9 Step 3 — review round 2 and its fixes (2026-11-20)](#p03-9-step-3--review-round-2-and-its-fixes-2026-11-20) — 70 lines @@ -24641,227 +24642,15 @@ scope's call stays as the named first refusal. #### Proof run locally -| Suite | Result | -|---|---| -| Unit | 4,229 passed | -| Integration, the whole suite (Release, 1 h 33 m, real PostgreSQL and pinned Keycloak) | 4,433 passed | -| Integration, operator subset rerun on the final tree (platform scope, operator HTTP, killswitch writer order, realm file, real-realm login, job admission) | 115 passed | -| Contract | 13 passed | -| Architecture (Release): platform scope, audit and API conventions | 31 passed | -| Architecture (Release, 43 min): `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests` | 178 passed | - -The last row is the result the Step 1 record deferred to this entry. It is also the run -that found the withdrawn start-time credential check: a compiled census of -connection-string readers failed on the new reader, which is why the check is recorded -above and not shipped. - -### P03-9 Step 1 — review round 2 and its fixes (2026-11-19) - -Three further independent reviewers read the range from the accepted decisions to the -round 1 fixes: an adversarial security review, a review of correctness and test -validity, and a review of the operator experience and the documentation. None reported a -Blocker. Each finding was checked against the code, and for the security question that -could not be settled by reading, against the pinned Keycloak. - -#### Settled by running it: the second factor and the account console - -The security reviewer asked whether a password-only session on the operator realm could -remove or add an authenticator through the account console, which asks for no `acr`. -Both paths were run against Keycloak 26.7.5 with a normally-roled operator who has an -authenticator: the console accepts the password alone, a credential listing succeeds, -and removing the authenticator is refused ("Credential type cannot be removed"); a login -that asks for `kc_action=CONFIGURE_TOTP` is sent to the existing-code form, not to -set-up. Both are now realm tests, so a Keycloak upgrade that changed either fails them. -The window that remains is the first login before any authenticator exists, which the -runbook already closes by ordering enrolment before the grant. - -#### Fixed - -| Area | Finding | Fix | -|---|---|---| -| Authentication | After one successful load, an issuer that stops answering left the last keys trusted indefinitely, so the claim "an outage refuses every operator" was false, and a withdrawn key stayed valid while egress was blocked | The scheme records when a fetch last succeeded and failed. Once a later fetch has failed and the last success is older than 15 minutes, tokens are refused (`metadata_stale`). The comment and runbook now say what an outage does | -| Authentication | While the first configuration was unavailable, every waiting unauthenticated request fetched it in turn, each holding its request for the transport timeout | A failed fetch makes the next ones fail at once for 30 seconds | -| Authentication | A caller who hung up during validation was counted as an issuer fault; a token with no `exp` was labelled as a bad `iat` | An `aborted` caller gets its own label; a missing `exp` is a lifetime cause | -| Gate | The ticket grammar was judged before the grant, so an ungranted operator's probe was filed as `InvalidTicket`, and the endpoint comment said the opposite | The grant is read first. An ungranted operator is refused as such whatever the request carries, and the refusal causes are snake case like the others | -| Endpoint | The framework bound the body before the handler ran, so a malformed body or a wrong content type was answered to an operator with no grant; outside Development it was a bare status | The handler reads the body after the gate has been asked, answers 415 and 400 as Problem Details, and caps the body at 4 KB. The response's correlation id is no longer optional in the contract | -| Killswitch writer | The ticket was stored in `platform_killswitches.reason`, a table the application role can read, against ADR-0101 § 9 | `reason` is NULL on every flip; the ticket is on the sentinel audit rows. [ADR-0101](../decisions/0101-platform-operator-authority.md) § 13 carries an erratum and Amendment 1; ADR-0045 Amendment 6 follows | -| Killswitch writer | The time was taken before the row lock; a toggle that waited stamped an earlier time than the one it followed. The lock result and the update count were trusted | The time is taken under the lock. A lock that finds no row, or an update that changes none, abandons the toggle before any result row exists | -| Scope | The facade accepted statements after the result row and any text naming `audit_log` (the platform role holds audit maintenance rights); a caller's state JSON reached the database unchecked and would have been reported as an audit outage; the entry's failure path could strand the connection if disposing the transaction threw; a size cap on the entry metadata could have dropped the operator and made the store refuse the row for good | The result row is the last write. No statement may name the audit log. State is checked as JSON and capped at 32 KB, and a refused argument does not fault the scope. The connection is disposed in a `finally`. The cap is removed | -| Credential | A connection string with `No Reset On Close` or `Multiplexing` would let session state outlive a scope on the pool that bypasses row level security | The platform credential is refused when either is on, as the sibling privileged sources pin them off | -| Contract | The operator document had a default title, Host-derived servers, no security scheme and no request body or error statuses beyond the generator's | A document transformer sets the title, drops `servers`, declares the bearer scheme and its token profile, a requirement on every operation, the request body, and 400, 401, 403, 404, 415, 500 and 503 with their headers | -| Operability | The overlay's two error events were numbered 1 and 2, which other components also use, so an operator could not search for them; the runbooks omitted events 7101, 7104 and two causes, did not define `API`, asked the operator to substitute variables by hand, and named a database administrator where the platform role is required | The events are 7107 and 7108 and the runbooks name every event, cause and role; the commands are runnable as written; the record-reading section names the role | -| Docs | Seven documents still described a writer-less table or the removed `EnterAsync(reason, …)` signature | Corrected: the Tenancy README, Standards 05 and 20, the glossary, the Phase 03 decision register, the Keycloak and compose READMEs | - -New cases: the future-dated admission, the grant-before-ticket order in the gate -(granted and ungranted operator, three malformed tickets) and over HTTP (three bodies, -including one the framework would have refused first), the audit-failure counter, the -415 and the malformed JSON as Problem Details, the operator document's title, servers, -scheme, body and statuses, stale keys after a failed refresh with a clock the test moves -(a blip within the window is bridged), twelve waiting requests answered from one failed -fetch, the aborted caller, the metadata health rules (six cases), the platform -credential's pool settings, the result row as the last write, three statements that name -the audit log, three non-JSON states and one oversized one with the scope still -committable afterwards, a lock that finds no row and an update that changes none, the -unreadable ticket column at the midpoint of a real toggle, and the two account-console -cases above. - -#### Recorded, not changed - -- **Pool settings in the builder.** `BuildPlatformDataSource` is inspected by a compiled - census of credential builders, so the platform source refuses a string that turns - session state on rather than rewriting it as its siblings do. Rewriting is a change to - that census and to every sibling at once, which belongs with Phase 11's credential - hardening. -- **The Development relaxations.** The loopback issuer and the demo grant depend on - `Deployment:Mode` alone, which the shipped development settings set. A host started in - the Development environment in production would honour both. This is the gate every - Development relaxation uses - ([ADR-0020](../decisions/0020-triple-deployment-hybrid-license.md)), a production - environment never loads that file, and the operator realm is not exposed by the - shipped compose; a second environment check would make this the one relaxation that - differs. -- **The internal Hub scheme.** When `/api/internal` gets a bearer scheme on the same - issuer, it must pin its own client and audience and refuse `learnstack-platform`, and - this scheme's `azp` list must never name a service client. Owned by the Hub contract - packet that adds it. -- **`IAuditStore.WritePlatformOperatorResultAsync` is a default interface method** that - throws, so a fake inherits a runtime failure and not a compile error. Making it - abstract touches ten test fakes for one production implementation; the architecture - census of store implementations is the guard, and a second production store would be a - decision of its own. -- **`TryConsume` and the minters are public.** A holder of an admission can spend it, - which only harms the holder. Narrowing them needs `InternalsVisibleTo` across three - assemblies for no gain the censuses do not already give. -- **Dead and decorative code.** `PlatformOperatorEvents.Forbidden` is unreachable under - the current policy and stays as the documented 403 mapping for the per-permission - policies the next operations add. The validation attributes on the request record - shape the contract and are not enforced by the framework; the gate and the handler - enforce the real rules. -- **Splitting `PlatformOperatorAuthentication.cs`.** It holds nine types, and an - architecture rule pins it as the authentication boundary. The split belongs with Step - 3, which adds the second caller of the profile and must edit that rule anyway. - -#### Mutation checks - -Twelve mutations of the round 2 guards, each applied, built, run and restored with the -restored file touched. All were killed: statements allowed after the result row, -statements that name the audit log, a result state that is not validated, an update row -count and a lock row count left unchecked, stale keys still trusted, no backoff after a -failed fetch, an aborted caller counted as an issuer fault, the ticket judged before the -grant, the ticket stored in the killswitch row, the unsafe pool settings accepted, and -the Host-derived `servers` left in the operator document. - -#### Proof run locally - -| Suite | Result | -|---|---| -| Unit | 4,242 passed | -| Contract | 13 passed | -| Integration, the whole suite (Release, 1 h 24 m) | 4,450 passed, 1 failed (below) | -| Integration, the account-console credential cases against pinned Keycloak 26.7.5 | 2 passed | -| Architecture (Release): platform scope, audit and API conventions | 31 passed | -| Architecture (Release, 46 min): `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests` | 178 passed | - -The one failure in the full integration run is -`AuthenticatedHttpSurfaceRuntimeTests.Production_endpoint_union_has_exact_patterns_methods_handlers_and_requests` -for the Development environment. Its message pattern names the asserted collection -(`authorizations`), which FluentAssertions reads back from the call-site source; the run -reported the generic wording instead, so the mutation control inside the case did not -match. The case passed alone, the whole class passed twice more, and the same case -passed in the earlier full run on the same code, so it is recorded as an inference flake -in an unrelated control and not as a defect of this change. - -### P03-9 Step 2 — production onboarding (2026-11-19) - -Step 2 delivers [ADR-0102](../decisions/0102-production-tenant-onboarding.md): five -operator acts that create a production tenant and its first administrator, on the -application role, through the ordinary request pipeline. The decisions were Accepted in -`a396f50e`; this record is the implementation and its proof. - -Delivered: - -- **A fourth trusted-operation source.** `AuthorizationSourceKind.PlatformOperator`, a - `PlatformOperatorAttribution` the descriptor carries (issuer, subject digest, `acr`, - executor, closed reason slug), and `PlatformOperatorOperationSource`, the fourth - `MintingSource`, scoped to one frame and bound to the operation of one admission. The - seed, delivery and job sources and their policies are unchanged, so neither authority - can perform the other's acts. -- **The executor.** `PlatformOperatorActExecutor` consumes the single-use admission, - refuses a request outside its closed catalog, an admission for another operation, the - platform sentinel and a stale admission before it is spent, opens a fresh scope, - installs an immutable resolved `OperatorTenantContext` for the tenant the route names, - sends the command and restores the accessor. It is the fifth writer of the context - accessor and adds no tenant setter. -- **Five commands and their handlers.** `OperatorProvisionTenantCommand` and - `OperatorMapHostCommand` are handled by the same classes as the seed commands, so the - three-write order, the conflict mapping and the one cross-aggregate exception exist - once. `OperatorInitializeRoleCommand`, `OperatorCreateFirstAdminCommand` and - `OperatorRecoverAdminCommand` are new Identity handlers. `OperatorActGuard` - (SharedKernel) restates source, context and transaction on the handler's own owner, - takes the ordered locks of [ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md) - and asks again before every write. -- **The person.** A sixteenth confined definer, `fn_identity_operator_resolve_user`, - resolves a provider subject to the `UserId` of an Active user for the stored - authority; `users` is invisible to a tenant announcement otherwise. -- **Five routes** under `/api/platform/v1/tenants/...`, each a `PUT` on - operator-supplied identifiers, so a reply lost on the wire is repaired by sending the - request again; the operator document `platform-v1` describes them. -- **Audit.** The composer, authorization context and evidence coordinator gain the - operator branch: a null actor, the closed reason slug and `metadata.operator`, no - ticket. A refused act writes the ordinary `failed` MUST row in the tenant; an - authorization refusal of an operator request writes none. -- **The Seeder refuses outside Development** (exit 2, before it reads a credential). -- **Signals.** `learnstack_platform_operator_acts_total{operation,outcome}` and event - 7109. -- **Documents.** The onboarding runbook, ADR errata and Amendments in ADR-0102, 0040, - 0036 and 0033, Standards 05, 11, 18, 19 and 21, the Identity and Tenancy module - specifications, the glossary, the seed skill and the README. - -Findings made while implementing, each fixed or recorded: - -- **ADR-0102 § 1 could not be built as written.** It promised one new confined tenant - setter and unchanged context writers. The query filters and the transaction behavior - read the accessor, so an act that is not installed in it is invisible to row security. - The executor installs the context, the ordinary behavior announces it, the setter - census stays at fourteen and the writers are five. Inline errata and - [ADR-0040](../decisions/0040-ambient-unit-of-work.md) Amendment 25 and - [ADR-0036](../decisions/0036-tenant-resolution-trusted-inputs.md) Amendment 22 record - it. The test that enumerates writers keeps its name, which three Accepted records cite. -- **The last-administrator guard makes recovery a break-glass.** The real-database proof - showed the deferred `fn_identity_complete_graph_guard` (`P0303`) rejects any commit - that leaves a tenant without an available administrator, so the state § 8 recovers - from is unreachable by revocation, and users have no update owner. The predicate is - implemented as accepted, the proof reaches the state by an owner-level repair that - steps around the guard and shows the invariant intact after the recovery, and - Amendment 1 item 4 records it. A predicate that also reads the User's eligibility needs - a second confined definer and is the maintainer's decision. -- **A refused act is audited.** Refused acts write `failed` rows in the target tenant, so - the first proof's assertion that nothing failed was wrong and the attempts are now the - evidence. -- **Row security applies to the owner.** The owner credential cannot read a tenant's rows - or the host index without announcing the tenant, and the memberships guards need the - advisory locks. The fixtures that repair state announce and lock like a handler does. -- **Six Step 1 leftovers.** The fast architecture classes had not been run over Step 1's - rounds: the metadata readers were not on the transport-holder list, the killswitch - ordering test sat under `Database/` without a Docker need, the realm-file test named - the Keycloak fixture, the endpoint built a killswitch key from the route (the registry - now resolves it), and Standard 21's counts were two methods and one rule behind. All - fixed here. -- **The pre-commit hook.** `dotnet format` adds a byte-order mark to a new C# file, which - made the stash restore conflict once, and an intent-to-add entry fails the hook; both - are recorded in the working notes, not in the repository. - -#### Proof run locally +On the final code of the step, after round 2: | Suite | Result | |---|---| -| Unit | 4,283 passed (new: guard 14, executor 12, catalog disjointness 1) | -| Integration, `PlatformOperatorOnboardingTests` (real PostgreSQL through the actual Program, as `learnstack_app`) | 16 passed | -| Integration, `OperatorSubjectResolverTests`, `SeederDevelopmentOnlyTests`, `SeedOperationSourceTests`, `PlatformOperatorHttpTests` | 3, 7, 15 and 28 passed | -| Integration, definer, schema and migration census classes | passed after the pins moved to 16 definers and 29 functions | -| Architecture (Release), every class except the four IL-census classes | 492 passed | -| Architecture (Release, 42 min), `AuthenticatedHttpSurfaceTests`, `BackgroundJobManifestBoundaryTests`, `AuthenticationAuthorityTests`, `OutboxDispatchConventionTests`, `BackgroundJobAdmissionBoundaryTests`, run on the final code after both review rounds | 178 passed | -| Integration, the whole suite, on the final code after both review rounds (1 h 25 min) | 4,478 passed, none failed, none skipped | +| Unit | 4,327 passed | +| Integration, the whole suite (every rebind class: storage as the role and as every other role, the locks, the run end to end, the audit store, the tool as a child process, the realm reader against a loopback realm and the pinned Keycloak 26.7.5, the operator validator, the input rules) | 4,661 passed | +| Architecture (Release), every class except the five IL-census classes | 495 passed | +| Architecture (Release), the five IL-census classes | 178 passed, three of them after the lifecycle owner lists were completed (see round 2) | +| Docs: `make lint-docs` | passed | What the real-database cases show: each act answers `200` and again `200` on a repeat; a changed value under the same identifiers is refused; a reply lost after the commit @@ -24977,3 +24766,203 @@ the document set. None reported a Blocker. metadata marker on the row is not built. - **A `replayed` flag in the response** would tell an operator resuming a setup without reading the metric; the response shape is the contract and is left as it is. + +### P03-9 Step 3 — controlled issuer rebind (2026-11-20) + +Step 3 delivers [ADR-0104](../decisions/0104-controlled-issuer-rebind.md): an offline +tool that moves the identity authority to a new issuer origin under the same realm +path, on a sixth confined database role, after a freeze and a continuity proof. The +decision was Accepted in `a396f50e`; this record is the implementation and its proof. + +Delivered: + +- **The sixth role.** `learnstack_identity_rebind` in the roles script, compose, the + environment example and every fixture that runs the script, `NOINHERIT NOBYPASSRLS`, + a member of nothing, with its credential in no host configuration. The compose + README says how to add it to a warm volume. +- **The storage.** One forward-only Identity migration: `SELECT` and `UPDATE (issuer)` + on `identity_authority`, four `users` columns, a third `identity_authority` policy for + the update and the role added to the read policy and to `users_isolation`'s `USING`, + and the trigger that refuses any change of `id` or `authority_id` for every role. The + `audit_log` grant and the policy arm are installed by a central audit installer, + because no module names the table. The definer census stays at sixteen; functions and + triggers are thirty. +- **The freeze.** A fixed advisory key. Authority qualification takes the shared form + after `SET TRANSACTION READ ONLY`; the User-creation admission takes it first, under + its two-second `lock_timeout`, and then reads the stored authority and issuer and + refuses a creation from a process that qualified with other facts. +- **The seam.** `platform.identity_authority.admin`, the `identity.authority.rebind` + operation with its attempt slug, two witness-bound audit methods on `IAuditStore` with + throwing defaults and their off-path declarations. +- **One validator.** The operator validator moved from the API project into + Infrastructure: settings, the bounded metadata client, the profile and a new + `PlatformOperatorTokenValidator` for the offline caller. The scheme and the tool take + the validation parameters and the metadata manager from one factory. +- **The run.** `IdentityIssuerRebind`, with the continuity proof as a pure function, and + the tool project that supplies the operator token, the grant, the new-realm reader and + the exit codes. It prints one line of classes and counts. +- **Documents.** The runbook, ADR-0104 Amendment 1, ADR-0073 Amendment 9, Standard 05's + new section and its role, identity-authority and ledger text, Standards 10, 11, 18, 19 + and 21, the Identity module specifications, the glossary and the local-dev skill. + +Findings made while implementing, each fixed or recorded: + +- **ADR-0104 § 5's "reads the new value" is not what a lock does.** The creation + admission never read the issuer, so a lock would only have delayed a creation from a + process that qualified before the rebind. The comparison after the lock is what + refuses it; Amendment 1 item 5 records it. +- **No module may name `audit_log`.** The first migration put the grant and the policy + arm in the Identity module's DDL and the architecture rule refused it, so the SQL + moved to a central installer beside the creation witness's, and the rebind run names + the table only through the installer's constant. +- **The IL-shape rules are Release rules.** Run in Debug, a rule over the evidence + coordinator's IL failed on an unrelated method. The architecture suite is run in + Release, as the earlier steps' records say. +- **A pooled idle connection is still a session.** The freeze check refuses until the + pools of the stopped hosts have drained, and the runbook says so. +- **The role's posture is checked before use.** An escalated attribute, a membership, an + extra table grant or a column grant beyond the declared ones refuses the run before + the lock, with a test for each. +- **Step 2 left two Docker classes out of the CI shard plan.** + `PlatformOperatorOnboardingTests` and `OperatorSubjectResolverTests` carry xUnit + fixtures and were missing from `sharedFixtureClasses`, which the plan test would have + failed on. Both are added with the Step 3 classes. +- **A Step 2 analyzer warning** (`CA2263` in a unit test) would have failed the + warnings-as-errors build and is fixed. + +#### Proof run locally + +| Suite | Result | +|---|---| +| Unit | (result below) | +| Integration, `IdentityAuthorityRebindStorageTests` (real PostgreSQL as the role and as every other role) | 7 passed | +| Integration, `IdentityAuthorityRebindLockTests` | 6 passed | +| Integration, `IdentityAuthorityRebindTests` | (result below) | +| Integration, `IdentityRebindAuditStoreTests`, `IdentityAuthorityRebindToolTests` (child process), `KeycloakRealmContinuitySourceTests`, `PlatformOperatorTokenValidatorTests` | (result below) | +| Integration, `KeycloakEnumerationTests` (pinned Keycloak 26.7.5) | 1 passed | +| Architecture (Release), every class except the five IL-census classes | (result below) | +| Architecture (Release), the five IL-census classes | (result below) | +| Integration, the whole suite | (result below) | + +What the real-database cases show: the role holds exactly its column privileges and +nothing else and each refusal is raised by the database as that role; the key trigger +refuses a change of `id` and `authority_id` even with the grant present; a start that +overlaps a rebind waits for it and then fails or succeeds on the value it left; a +creation is refused within its two seconds while a rebind runs and after one it did not +qualify against; a rebind that changes only the issuer leaves every user row identical +and writes an intent row and a result row, both under the platform sentinel with no +actor and the ticket in `metadata.operator`; a run whose target is already stored writes +nothing; every refusal class leaves the issuer where it was and an intent row where the +run reached the decision; a forced audit failure rolls the change back; a session +terminated before the commit is reconciled as not applied; a commit whose answer was +dropped by a relay is reconciled as applied by reading the issuer. The child process +refuses a missing or malformed input, a bad token, a missing grant and a wrong role with +one fixed line that names no credential, subject, issuer or address. + +#### Mutation checks + +More than forty mutations of the guards, each applied, built, run against its owning +test class and restored: the continuity comparison and its Closed, Closing and ordinal +rules, the lock and the rollback on audit failure, the posture attributes, the freeze +check, the policy arms, the operator validator's four validations, the realm reader's +completeness, origin and paging, and the key trigger. Six survived at first. Four were +real gaps and are killed by new cases: the audit store's tenant rule, which the ticket +check masked; the realm reader's origin rule, which was exercised only against a closed +port; the page loop past a first page boundary; and the sign-in creation path's mapping +of a changed authority. Two are equivalent and recorded: the audit store's +operation-identity check, which its off-path catalogue lookup makes redundant, and +`ValidateIssuerSigningKey`, which governs the key's own validity and not signature +verification. + +### P03-9 Step 3 — review round 1 and its fixes (2026-11-20) + +Three independent reviewers, each read-only, read the range from the accepted decisions +to the implementation: authority, security and the attack surface; correctness, +concurrency and failure windows; and tests, censuses and documentation. None reported a +Blocker. Each finding was checked against the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Regression | The creation admission's issuer comparison broke two existing integration tests that used an authority other than the installed one, and the lock-signal assertion did not know the new authority kind | Both tests use the installed facts; the signal census knows the kind | +| Audit | The role's `audit_log` access was open to any tenant it announced through the tenant setting, because the ordinary arm named no role | The ordinary arm excludes the role; a test announces a tenant as the role and is refused | +| Role posture | The check compared table grants only, so an extra or a missing column privilege passed | It compares the three tables column by column in both directions and sweeps every other relation for any privilege | +| Commit | A reconciliation of an unknown `COMMIT` could read the issuer before the original transaction had ended and report a false "unchanged" | It takes the shared lock first, so it reads only after the original transaction ends | +| Freeze | The check ran once, before a proof that can last minutes | It runs again immediately before the change | +| Outcome | A failure to dispose could replace the outcome of an applied rebind | Disposal never replaces the outcome | +| Inputs | The target issuer and the deployment mode were read more loosely than the API reads them | The mode is a declared name, the issuer follows the realm grammar, and outside Development it is HTTPS | +| Realm reader | One pass, no repeat check, no token renewal, the credential sent to any address the discovery document named, and no size bound | Two passes that must agree, repeats refused, one renewal per request, same-origin only and only after the discovery issuer equals the target, and a 200,000-user bound | +| Tool | An interrupt was not handled, the stdin wait had no bound, an outcome could go to standard error and a refusal carried no correlation | Interrupts end the run through the token, the wait is thirty seconds, everything goes to standard output, every refusal after the input carries its correlation | +| Census | The validator's and the profile's callers were unpinned and the executor set was open | Two rules pin the callers and the executor set is closed | +| Documents | The runbook, Amendment 1 and Standards 05, 10, 11, 19 and 21 said things the code did not do | Corrected | + +### P03-9 Step 3 — review round 2 and its fixes (2026-11-20) + +Three further independent reviewers, with lenses different from round 1: composition, +regression and the runtime; SQL, row security, locks, the migration and performance; and +operability, maintainability and the coherence of the document set. None reported a +Blocker. Each finding was checked against the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Freeze | The last-moment session count ran in the same transaction as the first, and the server serves `pg_stat_activity` from one snapshot per transaction, so the second count always repeated the first and a host that never takes the rebind lock could start in between | Each count first calls `pg_stat_clear_snapshot()`; a case opens an outbox session while the realm is read and expects `refused_live_sessions` before the change | +| Idle fence | Round 1's `KeepAlive` sends a message on the idle connection, and every message restarts the server's idle-in-transaction clock, so a hung tool's lock was never freed at fifteen minutes | The application keepalive is off whatever the connection string says; the operating system's TCP probes stay; a case sets `KeepAlive=1` in the string and watches the idle session's `state_change` stay still | +| Role posture | A `PUBLIC`-readable relation an extension owns (`pg_stat_statements`) locked the tool out in a way the runbook's remedy could not fix; the maintenance privilege, sequences and owned objects were not checked; a null answer threw | Extension-owned relations are not counted; the maintenance privilege, sequences and ownership of a relation, function or schema are; a null is a failed check; cases for each | +| Session settings | The three timeouts depend on the connection's startup options, which a pooler drops, and nothing checked they took effect | They are read back from `pg_settings` and refuse the run as `session_settings` | +| Diagnosis | `refused_input` covered nine causes, `refused_new_realm_unavailable` six and `refused_database_unavailable` swallowed stored-state faults as outages | A closed `detail` names the setting, the step of the realm read, the kind of database failure, or the posture check; it names no value | +| Exit codes | A failure to read back an unknown commit could escape as `refused_unexpected` and exit 2, which says the state is unchanged; an unexpected failure printed no correlation | Any reconciliation failure is `unknown`; an unexpected failure prints its correlation | +| Signals | A hang-up (an SSH drop) was unhandled, a signal in the last instant could fault the process, and nothing tested the handlers | Hang-up is handled, a late signal cannot throw, the stdin wait ends on a signal, and child-process cases send TERM and HUP while the realm read hangs and expect `refused_cancelled`, the intent row and no change | +| Deployment mode | The tool compared the mode exactly while the API ignores case and padding, so a lawful `saas` was an opaque `refused_input` | One `DeploymentModeParser` in the kernel is read by both | +| Counters | The runbook and Standard 10 said every run is counted, and the refusals before the database were not | They are recorded under the label the line prints | +| Logs | The runbook and the test comments said the tool logs; it writes none | Said plainly in the runbook, ADR-0104 Amendment 1 item 9 and the operator-access runbook | +| Runbook | It named no build step, said a rollback was unrecoverable while its own proof allows one before the new realm takes people, deleted the client and retired the password before a sign-in was confirmed, listed one setting where four name the realm, gave no way to enable the role, quoted a password unsafely, and left exit 3 and the continuity counts without a next step | Build, enable and retire steps, a rollback section with its precondition, the full settings table, a quoted example with TLS, the exit-3 read-back and the two shapes of continuity failure | +| Documents | Eleven prose lines over 88 columns, the rebind's token and role text twice in Standard 11, a missing Identity permissions row, a wrong place for the issuers in the audit specification, and a profile reader that became public without saying what confines it | Wrapped, pointed, added and stated in ADR-0104 Amendment 1 item 11 | +| Dependencies | The two new package pins are coupled to JwtBearer with nothing saying so | A comment in the props file says so | +| Logger category | The API named the retriever's category with a hand-typed string | The factory takes an `ILoggerFactory` and owns the category | +| Magic numbers | The idle fence had to exceed the run deadline and lived as literals in two files | Named constants in the library, with a test that the fence outlasts the deadline | +| Census | The heavy IL census, never run on Step 3's final code, found three cases of one cause: the lifecycle census enumerates every owner of a database commit and rollback, and the rebind's two transactions and its already-applied rollback were not listed | The three owners are listed with the reason; the census passes | + +#### Recorded, not changed + +- **No release artifact carries the tool.** The runbook builds it from the deployed + commit. A packaging decision belongs to whoever owns releases; none is made here. +- **A denied operator attempt at the offline tool leaves the printed line and, with an + OTLP endpoint, the counter, and no durable server-side trace.** Standard 10 and + ADR-0101 § 11 ask a counter and a log; the tool writes none. A stderr log would carry + the operator's identity into terminals and logs the tool promises not to write. The + maintainer decides whether the line is enough. +- **The tool does not require TLS to PostgreSQL.** The runbook asks for it. Nothing else + in the repository enforces database TLS either. +- **The platform and outbox roles can write rebind-shaped audit rows**, as they can + write every other platform-sentinel row. A trigger that confines the two operations to + the rebind role is not built; ADR-0104 Amendment 1 item 10 says so. +- **`PlatformOperatorTokenProfile.TryRead` is public**, confined by two census rules and + not by the compiler; the alternative is `InternalsVisibleTo` for the API project. +- **`RunCoreAsync` is long**, and `DisposeQuietlyAsync` has two siblings elsewhere. They + read as phases and are left alone rather than refactored in a review fix. +- **Shard weights for about a hundred new Docker cases** are the default until a CI run + measures them. The balance, not correctness, is affected. +- **A 55P03 from the final `UPDATE`'s row wait** reports `refused_rebind_in_progress`; + no state changes either way. +- **ADR-0003 Amendment 14 says the canonical policy template is unchanged**, which + holds: the restated `audit_log_isolation` arm is the central installer's, owned by + Standard 05. + +#### Mutation checks + +Sixteen mutations of the round 2 guards, each applied, built, run and restored, and all +killed: the activity snapshot not refreshed before the count (which also showed the +reviewer's claim true: without the call the late count repeats the first), the client +keepalive left to the connection string, extension relations counted, the maintenance +privilege, sequences, function ownership and schema ownership ignored, a +`PUBLIC`-readable relation outside an extension tolerated, the session settings not +compared, an authentication failure classified as a connection failure, the deployment +mode compared with case, the hang-up not handled, the realm token step not named, tool +refusals not counted, the detail not printed, and the refused input's field not named. +Two branches have no case that reaches them and are recorded: the refusal for session +settings the server did not apply (it needs a pooler in the path), and the stdin wait +ending on a signal. Both are small, and the first is checked in the positive on every +run. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 67a422fa..358653f0 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -37,7 +37,7 @@ > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | -> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch) and Step 2 (production onboarding) delivered and twice reviewed, Steps 3 to 5 pending | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding) and Step 3 (controlled issuer rebind) delivered and twice reviewed, Steps 4 and 5 pending | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | diff --git a/docs/runbooks/identity-issuer-rebind.md b/docs/runbooks/identity-issuer-rebind.md index cee647a9..585635a4 100644 --- a/docs/runbooks/identity-issuer-rebind.md +++ b/docs/runbooks/identity-issuer-rebind.md @@ -26,19 +26,52 @@ anything. | Needed | Why | |---|---| -| An operator with a current token and the grant `platform.identity_authority.admin` | The same operator token and grant model as the other [operator acts](operator-access.md). The grant is read from configuration when the tool runs, never from a claim | -| The sixth database role's connection string | `ConnectionStrings__IdentityRebind` for `learnstack_identity_rebind`. It exists only in the tool's environment for the minutes it runs: never in an API, worker, seeder or web configuration, and never in a file under version control | +| An operator with a current token and the grant `platform.identity_authority.admin` | The same operator token and grant model as the other [operator acts](operator-access.md). The grant is read from the tool's own configuration when it runs, never from a claim. See [Two people](#two-people) | +| The sixth database role's connection string | `ConnectionStrings__IdentityRebind` for `learnstack_identity_rebind`, to PostgreSQL **directly**, never through a connection pooler: the tool's session settings and its lock belong to one physical session. It exists only in the tool's environment for the minutes it runs: never in an API, seeder or web configuration, and never in a file under version control | | A read-only credential for the **new** realm | A confidential client with the single role `realm-management/view-users`, created for this run and deleted after it. It is not a LearnStack credential and is not in the realm export | | The stable `Identity__AuthorityId` and the new `Authentication__Tenant__Issuer` | The same two values the deployment is about to run with. The authority must equal the stored one; the issuer is the target. Outside Development the target must be HTTPS | -| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance. The mode is a declared name exactly (`SaaS`, not `saas` or `1`) | +| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance. The mode is read as the API reads it: a declared name, with case and padding ignored; an ordinal or a list is refused | +| The new realm's administration API on the issuer's **own origin** | The tool asks `/admin/realms//users`. A load balancer that blocks `/admin` on the public host makes the proof impossible from there; run the tool from a host that can reach it. The tool uses no proxy and the operating system's trust store only, so a private authority belongs in that store | -**Keep the database password and the operator's identity apart.** The tool checks the -operator token, the grant and the attribution of the audit rows; the database does not -force them, so whoever holds the role's password could change the issuer without the -tool. The person who runs the tool should not hold the password longer than the window, -and the password is retired afterwards (see [After it](#after-it)). +### Two people -## Before you start: freeze +The tool checks the operator's token, the grant and the attribution it writes into the +audit rows. The grant and the database password sit in the same process environment, so +the tool cannot tell who wrote them. Separate the roles by practice: whoever deploys the +change writes the tool's environment, including `PlatformOperator__Grants__*`, and +supplies the database password for the window only; the operator who signs in supplies +the token and runs it. The database does not force that separation: whoever holds the +role's password could change the issuer without the tool. The password is therefore +enabled for the window and retired after it (see [After it](#after-it)). + +## Before you start + +### Build the tool + +There is no release artifact that carries the tool. Build it from the same commit as the +deployed migrations, on a host with the .NET 10 SDK, and run the output on a host with +the .NET 10 runtime: + +```sh +dotnet publish backend/src/LearnStack.Tools.IdentityAuthorityRebind -c Release -o ./rebind-tool +``` + +### Enable the role for the window + +The role's login is closed outside a window. A role administrator opens it with a +password made for this window and hands that over through the secret channel: + +```sql +ALTER ROLE learnstack_identity_rebind LOGIN PASSWORD ''; +``` + +The roles script sets `LOGIN` and the password from `LEARNSTACK_IDENTITY_REBIND_PW` +every time it runs, so rerunning it opens the role; retire it again afterwards. On a +database that predates the role, run the roles script before the migration that grants +it: the migration stops with a message that names the missing role, and the roles script +is the role's only definition. + +### Freeze The tool takes a database lock that every API start and every new user binding queues behind, and it refuses to run while any session of the application, outbox, ingress or @@ -47,25 +80,28 @@ lock for up to thirty seconds and then fails with the fixed qualification error, user creation waits two seconds and is refused. The tool cannot see a process that holds no database connection, so the stop step below is the control for that case. -1. Announce the window and **stop every API and worker process** of the deployment, +1. Announce the window and **stop every API and seeder process** of the deployment, including the Hangfire server, the outbox dispatcher and the provider-event poller. -2. Wait for their connections to close. A pooled connection stays a session until its - idle lifetime ends (about five minutes by default), so the tool will refuse with - `refused_live_sessions` and a count until the pools have drained. A count is all it - reports; to see which role, read `pg_stat_activity` yourself. -3. Keep the **old** configuration out of every restart script. A process that is started - with the old issuer after the change fails its start on the mismatch, which is the - safe outcome; a process that was running and idle is the one the tool cannot see. +2. Check that nothing still holds a session. A stopped process leaves none. A connection + pooler (PgBouncer) or a process that was missed does: the tool refuses with + `refused_live_sessions` and a count, and that count is all it reports. To see which + role, read `pg_stat_activity` yourself. +3. Keep the **old** configuration out of every restart script, and out of anything that + restarts a crashed service. A process started with the old issuer fails its start on + the mismatch, which is the safe outcome. A process that starts while the tool runs + queues behind its lock and holds a session, which makes the tool refuse at its last + check, again the safe outcome; a process that was already running and idle is the one + the tool cannot see. 4. Do not create or delete users in the **new** realm while the tool runs. It reads the realm twice and refuses a realm whose users changed between the reads. ## Get the access token -Follow [Getting a token](operator-access.md#getting-a-token) for the operator issuer. The -token lasts at most 15 minutes and its `auth_time` must be recent, so sign in just +Follow [Getting a token](operator-access.md#getting-a-token) for the operator issuer. +The token lasts at most 15 minutes and its `auth_time` must be recent, so sign in just before the run. Give it to the tool in `LEARNSTACK_OPERATOR_TOKEN`, or pipe it on -standard input within thirty seconds so it does not sit in the environment. **Never -pass it as an argument**: the tool refuses any argument. +standard input within thirty seconds so it does not sit in the environment. **Never pass +it as an argument**: the tool refuses any argument. ## Create the read-only realm credential @@ -77,51 +113,81 @@ the client when the run is over, whatever the outcome. ## Run it -From a host that can reach the database and both issuers, with the stopped deployment's -settings in the environment: +From a host that can reach the database, the operator issuer and the new realm, with the +settings of the stopped deployment in the environment. Run it in `tmux` or `screen`: a +dropped connection ends the run, as an interrupt does. Under `nohup` the hang-up is +ignored and the run goes on. ```sh export Deployment__Mode= -export ConnectionStrings__IdentityRebind="Host=$DB_HOST;Database=$DB_NAME;Username=learnstack_identity_rebind;Password=$REBIND_PASSWORD" # leakwatch:ignore:database-connection-string +export ConnectionStrings__IdentityRebind="Host=$DB_HOST;Database=$DB_NAME;Username=learnstack_identity_rebind;Password='$REBIND_PASSWORD';SSL Mode=VerifyFull" # leakwatch:ignore:database-connection-string export Identity__AuthorityId= export Authentication__Tenant__Issuer= export PlatformOperator__Issuer=... PlatformOperator__AuthorizedParties__0=... PlatformOperator__AcceptedAcr__0=... -export PlatformOperator__Grants__0__Subject= +export PlatformOperator__Grants__0__Subject= export PlatformOperator__Grants__0__Permissions__0=platform.identity_authority.admin export LEARNSTACK_REBIND_REALM_CLIENT_ID=... LEARNSTACK_REBIND_REALM_CLIENT_SECRET=... export LEARNSTACK_REBIND_TICKET=CHG-123 # optional but recommended -printf %s "$TOKEN" | dotnet LearnStack.Tools.IdentityAuthorityRebind.dll +printf %s "$TOKEN" | dotnet ./rebind-tool/LearnStack.Tools.IdentityAuthorityRebind.dll ``` +The password is single-quoted inside the string, and a quote inside it is doubled, so a +`;` or `=` in it cannot split the string. The tool does not require TLS to the database; +outside a loopback host, ask for it (`SSL Mode=VerifyFull`) because the role's password +crosses that link. The two issuer settings are different things: the operator issuer +signs the person in, the tenant issuer is the realm being moved. + The ticket is 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`; a ticket outside that grammar is refused. It is recorded on the two audit rows, which no tenant can read. -It prints exactly one line to standard output and exits: +It prints exactly one line to standard output, nothing to standard error, and exits: | Exit | Meaning | |---|---| | `0` | The issuer was changed (`outcome=applied`), or already equalled the target (`outcome=already_applied`, nothing written) | | `2` | Refused. **The state is unchanged**; fix the cause and run it again | -| `3` | `outcome=unknown`: the commit's answer was lost and the stored issuer could not be read back. Read `identity_authority.issuer` before anything else | +| `3` | `outcome=unknown`: the commit's answer was lost and the stored issuer could not be read back. See [After exit 3](#after-exit-3) | + +The line is `rebind: outcome=`, then `correlation=`, which finds the audit +rows of a run that reached the database (a refusal before that writes none), then +`detail=` where the class has more than one cause, then `sessions=` when the +freeze check ran, then the counts of the proof where it ran: `active`, `closing`, +`closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed` and +`unbootstrapped`. A refusal that happens before a run has a handle (`refused_input`, and +a cancelled start that was waiting for the token) carries no correlation. The line never +contains a subject, a key, an issuer, an address or a credential; keep it in the change +ticket, because it is the only record of a refusal that happens before the database is +reached. + +An interrupt (Ctrl-C), a termination signal or a hang-up ends the run as the ten-minute +deadline does: the run rolls back, an unknown commit is still reconciled, and the line +says `refused_cancelled` or its true outcome. A second interrupt does not shorten the +reconciliation, which can take up to about a minute because it waits for the original +transaction to end. + +### After exit 3 + +The commit may or may not have landed. Read the stored issuer with the same role, from a +host that can reach the database: -Every line that follows a successful reading of the input carries `correlation=`, -which finds the audit rows, and a line where the proof ran carries counts: `active`, -`closing`, `closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed` and -`unbootstrapped`. `refused_input` and `refused_unexpected` carry neither, because they -happen before a handle exists or when none can be trusted. The line never contains a -subject, a key, an issuer, an address or a credential. +```sh +psql "host=$DB_HOST dbname=$DB_NAME user=learnstack_identity_rebind sslmode=verify-full" \ + -c 'SELECT issuer FROM identity_authority' +``` -An interrupt (Ctrl-C) or a termination signal ends the run as the ten-minute deadline -does: the run rolls back, an unknown commit is still reconciled, and the line says -`refused_cancelled` or its true outcome. +- It equals the **target**: the change landed. Run the tool again; it answers + `already_applied` and writes nothing. Then continue with [After it](#after-it). +- It equals the **old** value: the change did not land. Run the tool again. +- It is **anything else**: stop and escalate. ## What the tool does, in order 1. Validates the token with the operator validator and admits the act against the grant. A refusal here (`refused_operator_...`) writes nothing, not even a row. 2. Opens one direct, never-pooled connection as the rebind role and checks that the role - is exactly what it was granted, table by table and column by column. It then takes - the exclusive rebind lock as its first statement. If another rebind holds it, the + is exactly what it was granted, table by table and column by column, and that the + server applied the session timeouts it asked for. It then takes the exclusive rebind + lock as the first statement of its transaction. If another rebind holds it, the tool waits up to 30 seconds and refuses with `refused_rebind_in_progress`. 3. Reads the stored authority. If the stored issuer already equals the target it ends with `already_applied` and **writes nothing**. @@ -132,13 +198,15 @@ does: the run rolls back, an unknown commit is still reconciled, and the line sa own `issuer` to equal the target, at least one signing key and a complete enumeration. The credential is sent only to the realm's own token endpoint, and only once the discovery document names the target. -7. Proves continuity (below), asks the freeze question again, changes the one column, - writes the **result** row on the same transaction and commits. +7. Proves continuity (below), asks the freeze question again with a fresh view of the + database's sessions, changes the one column, writes the **result** row on the same + transaction and commits. Limits that bound the run: statements time out at 120 seconds, a transaction that idles for 15 minutes is ended by the server, the whole run has a ten-minute deadline, and a realm of more than 200,000 users is refused because its proof cannot finish in that -deadline. +deadline. A realm of a size near that limit can end as `refused_cancelled` for the same +reason: each page is one request, twice over, and a slow realm uses the deadline up. ## The continuity proof @@ -158,31 +226,45 @@ user repeated and the same count before and after. A realm that changes while it is refused as incomplete. `refused_continuity_broken` means the new realm is not the same population. Do not -force it: find out why the users differ. The usual cause is an import that generated new -ids. +force it. Read the counts: + +- **`missing_active` is close to `active`** (or `reported` shares almost nothing with + it): the realm's users have new ids, as an import that generated them does. This is a + different authority and not reachable here. Escalate. +- **A few `missing_active`:** accounts were deleted or not copied. Restore them in the + new realm with their original `sub`, or close those people in LearnStack first through + the normal lifecycle, then run it again. +- **Any `reappearing_closed`:** a person LearnStack closed has an account in the new + realm. Delete that account, then run it again. Never reactivate it here. + +To compare by hand, the stored subject is `users.provider_subject`, which the rebind +role can read, and the new realm's is the user's `id` in the administration console. ## When it refuses +`detail` is a closed name that says which check failed and never a value. + | Outcome | What it means and what to do | |---|---| -| `refused_input` | A required value is missing, malformed, or an argument was given. The tool says no more, so that a mistake cannot echo a secret. Check `Deployment__Mode`, the connection string's role, the authority id, the issuer (HTTPS outside Development), the token and the realm credential | +| `refused_input detail=` | A required value is missing, malformed, or an argument was given, and the setting is named: `arguments`, `connection_string` (missing, malformed or not the rebind role's), `operator_token` (missing, empty or over its length bound), `realm_client`, `authority_id`, `issuer` (not the realm grammar, or not HTTPS outside Development) or `deployment_mode` | | `refused_operator_token_` | The token failed validation: `token_missing`, `token_invalid`, `token_expired`, `token_audience`, `token_issuer`, `token_signature`, `token_algorithm`, `token_type`, `token_lifetime`, `metadata_unavailable`, `metadata_stale` or a `profile_*` cause. [The profile](operator-access.md#the-token-profile) says what each requires. Get a fresh token | | `refused_operator_missing_permission` | The token is good and the operator holds no `platform.identity_authority.admin` grant | | `refused_operator_invalid_ticket` | The ticket is outside its grammar | | `refused_operator_issuer_not_configured` / `..._configuration_invalid` | The `PlatformOperator__*` settings are absent or unsafe | | `refused_operator_invalid_witness` / `..._unknown_operation` / `..._not_admitted` | A defect in the tool's build, not an operator mistake. Escalate | | `refused_not_admitted` | The admission was stale, spent or not for this operation. Run the tool again | -| `refused_role_invalid` | The connection string is malformed or not the rebind role's, or the role holds something beyond (or lacks something of) its grants. Re-run the roles script and migrate | +| `refused_role_invalid detail=` | `role_session`: the string is malformed or not the rebind role's. `role_attributes`: the role gained an attribute that escalates. `role_membership`: it belongs to a role or has a member. `role_grants`: it can create objects, owns something, or holds a privilege on a relation beyond its declared grants (a `PUBLIC`-readable relation you added to `public` counts; an extension's own relations do not) or lacks one. `session_settings`: the server did not apply the timeouts the tool asked for, as a pooler in the path can; connect directly. For the first four, re-run the roles script and migrate, then open the role again | | `refused_rebind_in_progress` | Another rebind holds the lock, or a previous run is still open. Wait and retry | -| `refused_database_unavailable` | The database could not be reached or answered a failure. Nothing changed | +| `refused_database_unavailable detail=` | `database_connection`: the host or port could not be reached, or the TLS handshake failed. `database_authentication`: the server refused the credential or `pg_hba` does not admit this host (try the same string with `psql`). `database_permission`: a statement was refused for a missing privilege. `database_timeout`: the server or the network took too long. `authority_state`: the stored authority is missing, is not one row or changed under the run; this is not an outage, so escalate. Nothing changed | | `refused_authority_mismatch` | The stored authority is not `Identity__AuthorityId`. A different authority would re-key every person: stop and escalate | | `refused_live_sessions` | A session of a runtime role is open (the count is printed). Stop what holds it and retry | -| `refused_new_realm_unavailable` / `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm could not be read completely, published no signing key, changed while it was read, is too large, or names another issuer. Check the credential's role and the realm's address | -| `refused_continuity_broken` | See above | +| `refused_new_realm_unavailable detail=` | The read of the new realm stopped at `realm_discovery` (the discovery document, the issuer's path or an address that is not on the issuer's origin), `realm_key_set`, `realm_token` (the client credential was refused, or the token endpoint did not answer), `realm_user_count` (the administration API refused it: the client lacks `view-users`, `/admin` is blocked on this origin, or the realm is above 200,000 users) or `realm_user_list` (the user list was refused or malformed). It names no address and no body | +| `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm published no signing key, changed while it was read or reported inconsistent counts, or names another issuer than the target | +| `refused_continuity_broken` | See [the proof](#the-continuity-proof) | | `refused_audit_failed` | The audit row could not be written, so the change was rolled back or never begun | | `refused_commit_failed` | The commit failed and the stored issuer was read back unchanged, after the original transaction had ended. Retry | -| `refused_cancelled` | The ten-minute deadline or an interrupt ended the run | -| `refused_unexpected` | A defect. Nothing is known to have changed: read the stored issuer, then escalate | +| `refused_cancelled` | The ten-minute deadline, an interrupt, a termination signal or a hang-up ended the run | +| `refused_unexpected` | A defect. The state is unchanged, because a commit whose outcome cannot be confirmed is reported as `unknown`. Quote the correlation, which finds the intent row if one was written, and escalate | Every refusal leaves the stored issuer where it was and the next run repeats the whole proof. The intent row stays, so the trail shows each attempt. @@ -190,40 +272,89 @@ proof. The intent row stays, so the trail shows each attempt. ## After it The change is done when the tool prints `applied`. **Deploying the new issuer -configuration is the unfreeze.** - -1. Set `Authentication__Tenant__Issuer` to the new value in every API and worker - configuration, and start them. A process that still holds the old value fails its - start with the fixed qualification error: that is the guard, not a bug. -2. Delete the read-only realm client and remove `ConnectionStrings__IdentityRebind` - from the tool's host. -3. Retire the role's credential: set a new password with - `ALTER ROLE learnstack_identity_rebind PASSWORD ''` and discard it, or keep the - role `NOLOGIN` outside windows and `LOGIN` for the next one. The roles script - restores `LOGIN` every time it runs, so rotate or disable after any rerun of it. -4. Confirm one sign-in per tenant host and look at the audit rows: +configuration is the unfreeze.** Do the cleanup only after a sign-in works, because a +rollback needs the old realm, the realm credential and the role's password +([Rolling back](#rolling-back)). + +1. Set every setting that names the issuer or the realm to the new value, then start + the processes. A process that still holds the old issuer fails its start with the + fixed qualification error: that is the guard, not a bug. + + | Setting | Where | + |---|---| + | `Authentication__Tenant__Issuer` | Every API and seeder configuration. The federation adapter reads the same key | + | `LEARNSTACK_BFF_ISSUER` | The web application, when native sign-in is enabled | + | `IdentityEvents__RealmId` and `IdentityEvents__ClientSecret` | The API, when the provider-event mirror is configured: the realm's immutable id and the event reader's secret, [as the Keycloak setup describes](../../infra/keycloak/README.md) | + | The realm's own clients and their secrets | In the new realm. A Keycloak export masks confidential client secrets, so set them again there | + +2. Confirm one sign-in per tenant host and look at the audit rows (below). +3. Only then clean up. Delete the read-only realm client and remove + `ConnectionStrings__IdentityRebind` from the tool's host. Close the role's login and + discard its password: ```sql - -- as a role that can read audit_log, not the rebind role - SELECT timestamp, operation, outcome, reason, entity_id, before_state, after_state, - metadata->'operator' AS operator, metadata->'continuity' AS continuity - FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; + ALTER ROLE learnstack_identity_rebind NOLOGIN PASSWORD NULL; ``` - The two rows are `identity.authority.rebind_attempt` (`indeterminate`) and - `identity.authority.rebind` (`success`), under the platform sentinel tenant, with no - actor. The ticket is in `metadata.operator`, because no tenant can read these rows. + The roles script restores `LOGIN` and the password every time it runs, so close the + role again after any rerun of it. +4. Keep the old realm until you have no use for a rollback. + +The audit rows are readable only by the platform role, because they sit under the +platform sentinel tenant and no tenant policy admits them: + +```sql +-- as learnstack_platform, not the rebind role +SELECT timestamp, operation, outcome, reason, entity_id, before_state, after_state, + metadata->'operator' AS operator, metadata->'continuity' AS continuity +FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; +``` + +The two rows are `identity.authority.rebind_attempt` (`indeterminate`) and +`identity.authority.rebind` (`success`), with no actor. The old and new issuer are in +`before_state` and `after_state`, and the ticket is in `metadata.operator`. A run that +was refused or interrupted leaves its attempt row and no result row. To list those: + +```sql +SELECT a.correlation_id, a.timestamp FROM audit_log a +WHERE a.operation = 'identity.authority.rebind_attempt' + AND NOT EXISTS (SELECT 1 FROM audit_log r + WHERE r.correlation_id = a.correlation_id + AND r.operation = 'identity.authority.rebind') +ORDER BY a.timestamp DESC; +``` + +## Rolling back + +An applied rebind to a wrong issuer is undone by running the tool again with the old +issuer as the target. The same freeze, proof and rows apply, so it needs everything the +first run did: every runtime process stopped, a fresh operator token, a fresh read-only +client in the **old** realm, the old realm reachable, and the role opened again. + +It works only while the old realm still reports every Active user. Once anyone has been +created in the new realm after the change, that person's `sub` is stored and is not in +the old realm, so the proof answers `refused_continuity_broken` with `missing_active`. +Roll back before the new realm takes new people, or fix forward. ## Signals -`learnstack_identity_rebind_runs_total{outcome}` counts each run and -`learnstack_identity_rebind_continuity_total{class}` counts the proof by class. The tool -is a short-lived process: it exports them only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set -in its environment, and the printed line and the audit rows are the record otherwise. +`learnstack_identity_rebind_runs_total{outcome}` counts each run that read its input: +every printed class, `applied` and `already_applied` and `unknown` included, and the +operator-gate and input refusals under the label the line prints. The tool is a +short-lived process: it exports the counters only when `OTEL_EXPORTER_OTLP_ENDPOINT` is +set in its environment. It writes no log. A refusal at the gate leaves no audit row by +design, so its record is the printed line, which belongs in the change ticket, and the +counter when it is exported. `learnstack_identity_rebind_continuity_total{class}` counts +the proof by class. + +Any outcome other than `applied` and `already_applied` outside a planned window means +someone ran the tool; alert on it where the counters are exported. The audit query +above lists every attempt that did not finish. + `learnstack_identity_lock_refusals_total{lock_kind="authority"}` counts a user creation that could not take the shared rebind lock in time (`reason` `timeout`, `cancelled` or -`fault`) and, with `reason="mismatch"`, one that waited out a rebind and found the issuer -changed. A burst of `timeout` is what a window looks like from the API side. +`fault`) and, with `reason="mismatch"`, one that waited out a rebind and found the +issuer changed. A burst of `timeout` is what a window looks like from the API side. ## Not recoverable here @@ -233,8 +364,7 @@ changed. A burst of `timeout` is what a window looks like from the API side. - **A running process that held no database connection** when the tool ran. It keeps the old issuer until it restarts, and then fails its start on the mismatch. The stop step is the control for it, not the database. -- **A wrong rebind that was applied.** Run the tool again with the old issuer as the - target; the same proof and the same rows apply. +- **A rollback after the new realm took new people.** See [Rolling back](#rolling-back). - **A realm of more than 200,000 users.** The proof cannot finish in the deadline; escalate. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 8079a3e3..e6b94b8a 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -199,3 +199,11 @@ onboarding act an admitted operator had refused for a business reason, which wri A refusal at the gate leaves no record in the audit log, only the counter and the log line. An operator cannot grant themselves anything: grants are configuration, edited by whoever deploys it. + +The offline [issuer rebind](identity-issuer-rebind.md) tool reads the same grants from +its own environment, and it writes no log: a refusal there leaves the printed line and, +when an OTLP endpoint is set, the counter. Because the grant and the database password +sit in that one environment, the tool cannot tell who wrote them, so keeping the person +who writes the environment apart from the operator who signs in is a practice the +runbook asks for, not a control the tool enforces ([ADR-0104 Amendment +1](../decisions/0104-controlled-issuer-rebind.md), item 10). \ No newline at end of file diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 3dda7430..4445e548 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6394,10 +6394,10 @@ transaction. Authority qualification and the User-creation admission take the ** form first and always before the subject lock, so the order is fixed and the tool, which takes only this key, cannot form a cycle. -- **Qualification** takes it after `SET TRANSACTION READ ONLY` and before its read; under - `READ COMMITTED` the next statement sees the rebind it waited for and compares against - the new issuer. It sets no `lock_timeout`, so a start that overlaps a rebind waits - until the command timeout (thirty seconds) and then fails with the fixed +- **Qualification** takes it after `SET TRANSACTION READ ONLY` and before its read; + under `READ COMMITTED` the next statement sees the rebind it waited for and compares + against the new issuer. It sets no `lock_timeout`, so a start that overlaps a rebind + waits until the command timeout (thirty seconds) and then fails with the fixed qualification message, which stays failed until the process restarts. - **The creation admission** takes it under its two-second `lock_timeout` and then reads the stored authority and issuer, refusing with `IdentityAuthorityChangedException` @@ -6415,14 +6415,32 @@ which takes only this key, cannot form a cycle. Server-side, as the role: `session_user` and `current_user` are the role; it is not `INHERIT`, `BYPASSRLS`, superuser, `CREATEDB`, `CREATEROLE` or `REPLICATION`; it has no -membership either way and no schema or database `CREATE`; it holds no privilege, table -or column, on any other relation; and on the three it uses it holds exactly the declared -grants, compared column by column in both directions, so an extra column privilege and a -missing declared one both refuse. Any other posture refuses the run before the lock. The -freeze check counts sessions of the application, outbox, ingress and platform roles in -the database other than its own, from `pg_stat_activity`, which shows another role's +membership either way, owns no relation, function or schema, and has no schema or +database `CREATE`; it holds no privilege, table, column or sequence, including the +maintenance privilege of PostgreSQL 17, on any other relation of `public`; and on the +three it uses it holds exactly the declared grants, compared column by column in both +directions, so an extra column privilege and a missing declared one both refuse. A +relation that belongs to an extension (`pg_depend` type `e`) is not counted, so the +`PUBLIC`-readable views of `pg_stat_statements` do not lock the tool out; any other +relation in `public` that the role can reach, a privilege through `PUBLIC` included, is. +The session's own `lock_timeout`, `statement_timeout` and +`idle_in_transaction_session_timeout` are read back from `pg_settings` and must be what +the tool asked for, so a connection pooler that drops startup options refuses the run +instead of silently removing the lock wait and the idle fence. A check the catalog +cannot answer is a failed check. Any other posture refuses the run before the lock, and +the refusal names the first check that failed as a closed `detail`. + +The freeze check counts sessions of the application, outbox, ingress and platform roles +in the database other than its own, from `pg_stat_activity`, which shows another role's session with its role and database even where the statement is hidden. It runs before -the new realm is read and again immediately before the change. +the new realm is read and again immediately before the change. The server serves that +view from one snapshot per transaction, so each count first calls +`pg_stat_clear_snapshot()`, which every role may execute; without it the second count +would repeat the first and a host that starts while the proof runs, and never takes the +rebind lock, would not be seen. The tool turns Npgsql's application keepalive off and +asks the operating system for TCP probes instead: a client keepalive is a message, and +every message the server receives restarts its idle-in-transaction clock, so the +fifteen-minute fence that frees a hung tool's lock would never fire. ### Proof diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 805fffef..b908974f 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -175,10 +175,10 @@ LearnStack runs **two Keycloak realms** per ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)) is not an HTTP route at all: an offline tool validates the same operator token with the same validator, admits the act against the same per-act grant (`platform.identity_authority.admin`) and then - uses a sixth, confined database role whose credential exists only in the tool's - environment ([Database Standards](05-database.md#controlled-issuer-rebind-storage)). - Its realm credential is an operator-supplied `view-users` client for the new realm, - created for the run and deleted after it; it is not a LearnStack runtime or federation + uses a sixth, confined database role + ([§ Confined identity-rebind role](#confined-identity-rebind-role)). Its realm + credential is an operator-supplied `view-users` client for the new realm, created for + the run and deleted after it; it is not a LearnStack runtime or federation credential, and [ADR-0099](../decisions/0099-confined-tenant-federation.md)'s refusal of user-level authority for LearnStack is unaffected. @@ -598,10 +598,13 @@ ordinary tenant arm, so the tenant a session announces does not widen its rows. **Residual.** The operator token, the grant and the attribution in the audit rows are checked by the tool, and the database does not force them: whoever holds the role's password can change the issuer without the tool and write a rebind row of the admitted -shape. The role's password is therefore held apart from the operator's identity, and -retired after the window ([runbook](../runbooks/identity-issuer-rebind.md#after-it)). A +shape, and the platform and outbox roles, which bypass row security, can write such a +row too. The grant and the password sit in the tool's one environment, so keeping the +person who writes it apart from the operator is a practice, and the password is retired +after the window ([runbook](../runbooks/identity-issuer-rebind.md#two-people)). A database-enforced pairing of the change and its result row would need a confined -definer that reads `audit_log`, and is the maintainer's decision. +definer that reads `audit_log`, and is the maintainer's decision +([ADR-0104 Amendment 1](../decisions/0104-controlled-issuer-rebind.md), item 10). [Database Standards](05-database.md#controlled-issuer-rebind-storage) owns the grants, policies, trigger and lock. diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 386e6fae..b0921302 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -228,11 +228,12 @@ will raise them — which this standard requires it to do. shipped its writer ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)); it keeps `(off-path)` because the write runs inside the platform scope rather than through the - pipeline. The controlled issuer rebind's two rows, `identity.authority.rebind_attempt` - and `identity.authority.rebind` ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) - § 8), are `(off-path)` for the same reason one step further: they are written by an - offline tool on its own role through two witness-bound methods, under the platform - sentinel, with no actor and the ticket in `metadata.operator`. + pipeline. The controlled issuer rebind's two rows, + `identity.authority.rebind_attempt` and `identity.authority.rebind` + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 8), are `(off-path)` for + the same reason one step further: they are written by an offline tool on its own role + through two witness-bound methods, under the platform sentinel, with no actor and the + ticket in `metadata.operator`. ## Baseline Coverage (LearnStack Core Modules) diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 423f0094..6d2e4fab 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -114,8 +114,8 @@ The five onboarding acts of policies are `FiniteTrusted` with that single source, the business actor of every row they write is `UserId.SystemActor`, and the operator is recorded in audit only. The grant is evaluated by the gate on every act, never cached across acts. The rebind of -[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) is not an act of that -executor and not a route: the scope refuses an operation that needs no platform role, and the +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) is not an act of that executor +and not a route: the scope refuses an operation that needs no platform role, and the executor runs only the closed catalog of five onboarding acts, which refuses the rebind operation by construction (`PlatformOperatorActCatalog`). The offline tool that consumes the admission validates the same token and evaluates the same grant. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 9a9605fc..85b5e007 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -5918,7 +5918,8 @@ structural test proves — and what it does not. - **Asserts:** the source files that name `PlatformOperatorTokenProfile` are exactly the profile's own file, the API scheme's boundary (`LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs`) and the offline - validator (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs`); + validator + (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs`); the files that call its `TryRead` are exactly the scheme boundary and the offline validator, the two callers of ADR-0101 § 7 through one validator; and the only file that names `PlatformOperatorWitness.Minter` is the profile's own, where the one @@ -5935,14 +5936,18 @@ structural test proves — and what it does not. - **Asserts:** by IL, the callers of `PlatformOperatorTokenProfile.TryRead` in every production assembly are exactly the API scheme's validated event - (`PlatformOperatorEvents.TokenValidated`) and `PlatformOperatorTokenValidator.ValidateAsync`, - and the callers of the offline validator's constructor and `ValidateAsync` are exactly - the rebind tool's `RebindTool.RunAdmittedAsync`. `TryRead` and the validator accept the - two executor constants and refuse any other. -- **Why it matters:** the validator and the profile are public so that the API scheme and the - tool share one definition, and the witness they mint is evidence that a token passed - the closed profile. Pinning the callers keeps a second public door from becoming a - second place a witness can be made ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 7). + (`PlatformOperatorEvents.TokenValidated`) and + `PlatformOperatorTokenValidator.ValidateAsync`, and the callers of the offline + validator's constructor and `ValidateAsync` are exactly the rebind tool's + `RebindTool.RunAdmittedAsync`. `TryRead` and the validator accept the two executor + constants and refuse any other. +- **Why it matters:** the validator and the profile are public so that the API scheme + and the tool share one definition, and the witness they mint is evidence that a token + passed the closed profile. Before the move the compiler confined the profile to the + API project; now these rules do, for the production assemblies, and a test assembly + or reflection is outside them. Pinning the callers keeps a second public door from + becoming a second place a witness can be made + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 7). - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 3. - **Type:** xUnit + IL scan. **Kind:** structural. @@ -5969,13 +5974,15 @@ structural test proves — and what it does not. #### `Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock` -- **Asserts:** by IL, the callers of `IdentityAdvisoryLockKey.ForAuthorityRebind` in every - production assembly are exactly `NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync`, +- **Asserts:** by IL, the callers of `IdentityAdvisoryLockKey.ForAuthorityRebind` in + every production assembly are exactly + `NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync`, `IdentityAuthorityQualification.QualifyCoreAsync`, `IdentityIssuerRebind.CommitAsync` (the reconciliation of an unknown COMMIT, which waits behind the original transaction) and `IdentityIssuerRebind.RunCoreAsync`. -- **Why it matters:** the exclusive form is the freeze and the shared form is what a start or a - creation waits behind; a further taker is a further party that can hold or wait on it. +- **Why it matters:** the exclusive form is the freeze and the shared form is what a + start or a creation waits behind; a further taker is a further party that can hold or + wait on it. - **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 5. - **Type:** xUnit + IL scan. **Kind:** structural. - **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3). From fc57429da99ad182bf11c7fe2aeaecdbd0828feb Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 05:45:06 +0300 Subject: [PATCH 17/28] feat(platform): operator recovery of dead-lettered work Implements ADR-0103: a metadata-only operator inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and two fenced transitions, a subscriber replay and a narrow producer reset, each behind an operator admission with a MUST row on the same transaction. There is no dashboard and no job recovery. The platform role already read outbox_messages whole, so its table-wide SELECT is revoked and named columns of four tables are granted instead. The two dispatcher stores gain a reserved operator slot and a fenced transition each, and a sibling witness binds the audit row to the admitted operation, the operator and the fence before and after. A stale fence answers 409 on the field fence, a refused state 409 on the field state, a lost commit answer 503 outcome_unknown. The capacity ledger grows by the two lanes. The operator recovery runbook, ADR-0103 Amendment 1 and the standards that name the changed seams are written; the delivery records follow the review rounds. Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 13 +- .../OutboxCompositionExtensions.cs | 9 +- .../PersistenceCompositionExtensions.cs | 4 + .../PlatformOperatorEndpoints.Recovery.cs | 328 +++++++++++++++++ .../Platform/PlatformOperatorEndpoints.cs | 1 + .../PostgresAuditStore.cs | 45 +++ .../Jobs/BackgroundJobPhysicalCapacity.cs | 5 +- .../DeliveryDispatchStore.Operator.cs | 209 +++++++++++ .../Messaging/DeliveryDispatchStore.cs | 55 +-- .../Messaging/OperatorRecovery.cs | 69 ++++ .../Messaging/OperatorRecoveryAdmission.cs | 24 ++ .../Messaging/OutboxDispatchStore.Operator.cs | 201 +++++++++++ .../Messaging/OutboxDispatchStore.cs | 22 +- ...t_platform_delivery_inspection.Designer.cs | 29 ++ ...0000_grant_platform_delivery_inspection.cs | 51 +++ .../PlatformOperator/DeliveryInspection.cs | 247 +++++++++++++ .../PlatformOperatorActCatalog.cs | 8 +- .../PlatformOperatorActExecutor.cs | 2 +- .../PlatformOperatorMetrics.cs | 25 ++ .../PlatformOperatorOperationSource.cs | 2 +- .../Audit/IAuditStore.cs | 19 + .../Audit/OperatorRecoveryTransition.cs | 210 +++++++++++ .../Platform/IDeliveryInspection.cs | 66 ++++ .../Platform/IOperatorRecovery.cs | 77 ++++ .../Platform/PlatformOperation.cs | 71 +++- .../Platform/PlatformPermissions.cs | 10 +- .../Audit/TenancyAuditCatalogSource.cs | 9 + .../AuditConventionTests.cs | 4 +- ...roundJobRuntimeCompositionBoundaryTests.cs | 24 +- .../DeliveryDispatchBoundaryTests.cs | 25 +- ...tegrationDeliveryLifecycleBoundaryTests.cs | 5 +- .../OperatorRecoveryBoundaryTests.cs | 165 +++++++++ .../OutboxDispatchBoundaryTests.cs | 18 +- .../OutboxDispatchObservationTests.cs | 2 + .../PlatformAdminScopeConventionTests.cs | 30 ++ .../PrivilegedDispatchCleanupBoundaryTests.cs | 5 +- .../BackgroundJobGrantExpectations.cs | 12 + .../BackgroundJobRuntimeFacadeTests.cs | 4 +- .../Database/DeliveryDispatchStoreTests.cs | 333 ++++++++++++++++-- .../Database/DeliveryInspectionTests.cs | 270 ++++++++++++++ .../Database/EventDeliveryMigrationTests.cs | 18 +- .../Database/MigrationRollbackTests.cs | 4 +- .../Database/OutboxDispatchStoreTests.cs | 277 ++++++++++++++- .../Database/TenancySchemaTests.cs | 3 +- .../Database/UnitOfWorkTests.cs | 24 +- .../PlatformOperatorHttpTests.cs | 312 +++++++++++++++- .../BackgroundJobPhysicalCapacityTests.cs | 8 +- .../MultiTenancy/PlatformAdminGateTests.cs | 4 +- .../PlatformOperatorActCatalogTests.cs | 38 +- docs/architecture/15-event-and-outbox.md | 13 +- docs/architecture/23-data-protection.md | 12 +- docs/architecture/31-audit-subsystem.md | 7 +- ...-operator-recovery-of-asynchronous-work.md | 76 ++++ docs/glossary.md | 5 +- docs/modules/audit/audit.md | 5 +- docs/modules/tenancy/audit.md | 3 + docs/modules/tenancy/permissions.md | 12 +- docs/runbooks/README.md | 1 + docs/runbooks/operator-access.md | 7 +- docs/runbooks/operator-recovery.md | 158 +++++++++ docs/standards/05-database.md | 108 +++++- docs/standards/10-observability.md | 1 + docs/standards/18-audit-coverage.md | 8 +- docs/standards/19-permissions.md | 10 +- docs/standards/20-infrastructure-stack.md | 9 + .../21-architecture-tests-catalogue.md | 56 ++- scripts/ci-test-shards-plan.json | 1 + 67 files changed, 3695 insertions(+), 193 deletions(-) create mode 100644 backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs create mode 100644 backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs create mode 100644 backend/src/LearnStack.Infrastructure/Messaging/OperatorRecovery.cs create mode 100644 backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryAdmission.cs create mode 100644 backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs create mode 100644 backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.Designer.cs create mode 100644 backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.cs create mode 100644 backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs create mode 100644 backend/src/LearnStack.SharedKernel/Audit/OperatorRecoveryTransition.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/IDeliveryInspection.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs create mode 100644 backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs create mode 100644 docs/runbooks/operator-recovery.md diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 583bf0f6..957743fe 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -51,7 +51,7 @@ public async Task TransformAsync( continue; } - foreach (var operation in path.Operations.Values) + foreach (var (method, operation) in path.Operations) { operation.Security = [ @@ -61,7 +61,8 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum }, ]; DescribeResponses(document, operation); - if (operation.RequestBody is null) + // An inspection is a read and carries no body. + if (operation.RequestBody is null && method != HttpMethod.Get) { // Declared here and not through `Accepts` on the endpoint: that metadata makes routing // reject any other content type itself, before the handler can answer 415 as a problem. @@ -85,6 +86,8 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum "PlatformHostMap" => typeof(Platform.HostMapRequest), "PlatformRoleInitialize" => typeof(Platform.RoleInitializeRequest), "PlatformFirstAdminCreate" or "PlatformAdminRecover" => typeof(Platform.AdministratorRequest), + "PlatformDeliveryReplay" => typeof(Platform.DeliveryReplayBody), + "PlatformOutboxReset" => typeof(Platform.OutboxResetBody), _ => throw new InvalidOperationException("An operator operation declares no request body: " + operationId), }; @@ -144,12 +147,12 @@ private static readonly (string Status, string Description)[] Statuses = ("400", "validation_failed: the body is malformed, a required field is missing, an identifier is not a UUIDv7, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate or by a route check carries no per-field errors."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), - ("404", "not_found: the killswitch key is not declared, or the tenant the route names does not exist."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), + ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, or a recovery names no such row."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one a reset may act on). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), ("500", "internal_error: an unexpected failure. An act whose final commit's outcome is unknown may have landed; repeat the same request (every act is idempotent on its identifiers) or read the state before changing it."), - ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or an ordered lock could not be taken, so nothing changed. Retry after the delay."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or an ordered lock could not be taken, so nothing changed. Retry after the delay. A recovery can also answer outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed reset answers a repeat 409 on errors.fence."), ]; } diff --git a/backend/src/LearnStack.Api/Composition/OutboxCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/OutboxCompositionExtensions.cs index 70ffb033..7323af89 100644 --- a/backend/src/LearnStack.Api/Composition/OutboxCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/OutboxCompositionExtensions.cs @@ -6,6 +6,7 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Time; using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; using LearnStack.Modules.Tenancy.Infrastructure.Jobs; using Microsoft.Extensions.DependencyInjection.Extensions; using Npgsql; @@ -44,7 +45,8 @@ public static IServiceCollection AddLearnStackOutboxDispatcher( provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService(), - provider.GetRequiredService())); + provider.GetRequiredService(), + provider.GetRequiredService())); services.TryAddSingleton(); services.AddHostedService(ResolveOutboxHostedService); if (!services.Any(descriptor => descriptor.ServiceType == typeof(OutboxHealthCheck))) @@ -61,7 +63,10 @@ public static IServiceCollection AddLearnStackOutboxDispatcher( provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService(), - provider.GetRequiredService())); + provider.GetRequiredService(), + provider.GetRequiredService())); + // The operator recovery owner holds the two stores and no credential of its own (ADR-0103 § 4). + services.TryAddSingleton(); services.TryAddSingleton(); services.AddHostedService(ResolveDeliveryHostedService); if (!services.Any(descriptor => descriptor.ServiceType == typeof(DeliveryHealthCheck))) diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index d29fa85d..909a7619 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -28,6 +28,8 @@ using LearnStack.Infrastructure.MultiTenancy; using LearnStack.Infrastructure.Persistence; using LearnStack.Infrastructure.Messaging; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; using LearnStack.Modules.Audit.Infrastructure.Persistence; using LearnStack.Modules.Customization.Application.Abstractions; using LearnStack.Modules.Tenancy.Application.Abstractions; @@ -302,6 +304,8 @@ public static IServiceCollection AddLearnStackPersistence( // cache flight that runs it outlives the caller that started it. services.TryAddScoped(); services.TryAddScoped(); + // The operator inspection of asynchronous work reads in the platform scope on column grants (ADR-0103 § 1). + services.TryAddScoped(); // The entitlement socket. A SINGLETON and registered in EVERY deployment mode, // not Development only: ADR-0035 names NullEntitlementProvider the working default diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs new file mode 100644 index 00000000..5d82fbba --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs @@ -0,0 +1,328 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using LearnStack.Api.Authentication; +using LearnStack.Api.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using Microsoft.AspNetCore.Mvc; + +namespace LearnStack.Api.Platform; + +/// The fence a subscriber replay presents, as the inspection showed it. +/// The delivery's replay count; required. +/// The instant it was dead-lettered, to the microsecond, as the inspection returned it; required. +/// The terminal reason the inspection showed; required. +/// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. +internal sealed record DeliveryReplayBody( + [property: Required] int? ReplayCount, + [property: Required] DateTimeOffset? DeadLetteredAt, + [property: Required][property: StringLength(32, MinimumLength = 1)] string? TerminalReason, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); + +/// The fence a producer reset presents, as the inspection showed it. +/// The row's attempt count; required. +/// The instant it was dead-lettered, to the microsecond, as the inspection returned it; required. +/// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. +internal sealed record OutboxResetBody( + [property: Required] int? Attempts, + [property: Required] DateTimeOffset? DeadLetteredAt, + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); + +/// What an applied recovery answers: the row it reset, the count it now carries and the correlation id. +internal sealed record RecoveryResponse( + string Outcome, Guid TenantId, Guid EventId, string? SubscriptionId, int CountAfter, string CorrelationId); + +/// The cursor envelope of Standard 04, for an inspection page. +internal sealed record InspectionPageInfo(string? NextCursor, string? PreviousCursor, bool HasNext, bool HasPrevious); + +/// One page of an inspection. +internal sealed record InspectionResponse(IReadOnlyList Items, InspectionPageInfo PageInfo); + +/// +/// The recovery routes of the operator surface (ADR-0103): a metadata-only inspection of dead-lettered work and +/// the two fenced transitions that act on what it shows. There is no dashboard and no job recovery. +/// +/// +/// Each route runs the gate first. The acts are POSTs that carry the fence read at inspection: a stale fence +/// answers 409 with the reason on the field fence, a state a reset may not act on answers 409 with +/// the reason on the field state, a MUST row that cannot be written answers 503 with nothing changed, and +/// a commit whose outcome is unknown answers 503 so the operator inspects before repeating. +/// +internal static partial class PlatformOperatorEndpoints +{ + private const string WorkPrefix = "/asynchronous-work"; + private const int DefaultPageSize = 20; + private const int MaximumPageSize = 100; + + private static readonly Regex SubscriptionPattern = new( + @"\A[a-z][a-z0-9]*\.[a-z][a-z0-9-]*\.v[1-9][0-9]*\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); + + private static void MapRecovery(RouteGroupBuilder group) + { + DescribeInspection( + group.MapGet(WorkPrefix + "/outbox-messages", InspectOutboxAsync) + .WithName("PlatformOutboxInspect") + .WithSummary("List dead-lettered or terminal-requested outbox rows, metadata only, with the fence a reset needs."), + typeof(InspectionResponse)); + DescribeInspection( + group.MapGet(WorkPrefix + "/event-deliveries", InspectDeliveriesAsync) + .WithName("PlatformDeliveryInspect") + .WithSummary("List dead-lettered or terminal-requested subscriber deliveries, metadata only, with the fence a replay needs."), + typeof(InspectionResponse)); + DescribeInspection( + group.MapGet(WorkPrefix + "/quarantined-jobs", InspectJobsAsync) + .WithName("PlatformJobInspect") + .WithSummary("List quarantined jobs with their reservation occupancy; nothing here releases or requeues one."), + typeof(InspectionResponse)); + Describe( + group.MapPost(WorkPrefix + "/event-deliveries/{tenantId:guid}/{subscriptionId}/{eventId:guid}/replay", ReplayDeliveryAsync) + .WithName("PlatformDeliveryReplay") + .WithSummary("Reset one dead-lettered subscriber delivery under the fence the inspection returned."), + typeof(RecoveryResponse)); + Describe( + group.MapPost(WorkPrefix + "/outbox-messages/{tenantId:guid}/{eventId:guid}/reset", ResetOutboxAsync) + .WithName("PlatformOutboxReset") + .WithSummary("Reset one retry-exhausted outbox row under the fence the inspection returned; this renews its attempt budget."), + typeof(RecoveryResponse)); + } + + private static void DescribeInspection(RouteHandlerBuilder route, Type success) => route + .Produces(StatusCodes.Status200OK, success, "application/json") + .ProducesProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status403Forbidden) + .ProducesProblem(StatusCodes.Status500InternalServerError) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable); + + private static Task InspectOutboxAsync( + [FromQuery] string? state, [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, + HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, + CancellationToken cancellationToken) => + InspectAsync( + http, gate, ticket, state, limit, loggers, cancellationToken, + async (admission, parsedState, size) => await inspection.InspectOutboxAsync(admission, parsedState, cursor, size, cancellationToken)); + + private static Task InspectDeliveriesAsync( + [FromQuery] string? state, [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, + HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, + CancellationToken cancellationToken) => + InspectAsync( + http, gate, ticket, state, limit, loggers, cancellationToken, + async (admission, parsedState, size) => await inspection.InspectDeliveriesAsync(admission, parsedState, cursor, size, cancellationToken)); + + private static Task InspectJobsAsync( + [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, + HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, + CancellationToken cancellationToken) => + InspectAsync( + http, gate, ticket, "dead_lettered", limit, loggers, cancellationToken, + async (admission, _, size) => await inspection.InspectJobsAsync(admission, cursor, size, cancellationToken)); + + /// + /// The shared flow of an inspection: the gate first, so the query is answered only to an operator who may inspect, + /// then the page parameters, then one page in an entered platform scope. + /// + private static async Task InspectAsync( + HttpContext http, + IPlatformOperatorGate gate, + string? ticket, + string? state, + string? limit, + ILoggerFactory loggers, + CancellationToken cancellationToken, + Func?>> page) + { + var (refusal, admission) = await AdmitAsync(http, gate, PlatformOperations.DeliveryInspect, ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (!TryState(state, out var parsedState) || !TryLimit(limit, out var size)) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await page(admission!, parsedState, size); + return result is null + ? Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed") + : Results.Ok(new InspectionResponse( + result.Items, new InspectionPageInfo(result.NextCursor, null, result.NextCursor is not null, false))); + } + catch (AuditWriteFailedException failure) + { + return AuditUnavailableProblem(http, loggers, PlatformOperations.DeliveryInspect, failure); + } + } + + private static async Task ReplayDeliveryAsync( + Guid tenantId, string subscriptionId, Guid eventId, HttpContext http, IPlatformOperatorGate gate, + IOperatorRecovery recovery, ILoggerFactory loggers, CancellationToken cancellationToken) + { + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, PlatformOperations.DeliveryReplay, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (body is null || !IsOperatorRowId(tenantId) || eventId == Guid.Empty || !SubscriptionPattern.IsMatch(subscriptionId) + || body.ReplayCount is not { } count || body.DeadLetteredAt is not { } deadLettered || body.TerminalReason is not { } reason) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + return await RecoverAsync( + http, loggers, PlatformOperations.DeliveryReplay, admission!, tenantId, eventId, subscriptionId, + () => recovery.ReplayDeliveryAsync( + admission!, new DeliveryReplayRequest(tenantId, subscriptionId, eventId, count, deadLettered, reason), cancellationToken)); + } + + private static async Task ResetOutboxAsync( + Guid tenantId, Guid eventId, HttpContext http, IPlatformOperatorGate gate, IOperatorRecovery recovery, + ILoggerFactory loggers, CancellationToken cancellationToken) + { + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, PlatformOperations.DeliveryReset, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (body is null || !IsOperatorRowId(tenantId) || eventId == Guid.Empty + || body.Attempts is not { } attempts || body.DeadLetteredAt is not { } deadLettered) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + return await RecoverAsync( + http, loggers, PlatformOperations.DeliveryReset, admission!, tenantId, eventId, null, + () => recovery.ResetOutboxAsync( + admission!, new OutboxResetRequest(tenantId, eventId, attempts, deadLettered), cancellationToken)); + } + + private static async Task RecoverAsync( + HttpContext http, + ILoggerFactory loggers, + PlatformOperation operation, + PlatformAdmission admission, + Guid tenantId, + Guid eventId, + string? subscriptionId, + Func> transition) + { + try + { + var result = await transition(); + return result.Outcome switch + { + OperatorRecoveryOutcome.Applied => Results.Ok(new RecoveryResponse( + "applied", tenantId, eventId, subscriptionId, result.CountAfter ?? 0, + admission.Operator.CorrelationId ?? http.TraceIdentifier)), + OperatorRecoveryOutcome.StaleFence => ResultProblem(http, Rule("fence", "lockey_stale_fence")), + OperatorRecoveryOutcome.NotRecoverable => ResultProblem(http, Rule("state", "lockey_not_recoverable")), + _ => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), + }; + } + catch (AuditWriteFailedException failure) + { + return AuditUnavailableProblem(http, loggers, operation, failure); + } + catch (OperatorRecoveryUnavailableException failure) + { + RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); + return Problem( + http, StatusCodes.Status503ServiceUnavailable, + failure.CommitOutcomeUnknown ? "lockey_outcome_unknown" : "lockey_dependency_unavailable"); + } + } + + /// A 409 with the reason on the field it concerns; the status map is closed, so the code stays the business rule's. + private static Error Rule(string field, string reason) => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage(reason)], + }); + + private static async Task<(IResult? Refusal, PlatformAdmission? Admission)> AdmitAsync( + HttpContext http, IPlatformOperatorGate gate, PlatformOperation operation, string? ticket, CancellationToken cancellationToken) + { + var witness = http.Features.Get()?.Witness; + if (witness is null) + { + return (Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"), null); + } + + var admission = await gate.AdmitAsync(witness, operation, ticket, cancellationToken); + return admission.IsAdmitted ? (null, admission.Admission) : (RefusalProblem(http, admission.Refusal), null); + } + + /// The body is read to find the ticket, and answered only after the gate has admitted the act. + private static async Task<(TBody? Body, IResult? Refusal, PlatformAdmission? Admission)> AdmitWithBodyAsync( + HttpContext http, IPlatformOperatorGate gate, PlatformOperation operation, Func ticketOf, + CancellationToken cancellationToken) + where TBody : class + { + var witness = http.Features.Get()?.Witness; + if (witness is null) + { + return (null, Problem(http, StatusCodes.Status401Unauthorized, "lockey_unauthorized"), null); + } + + var (body, bodyState) = await ReadBodyAsync(http.Request, cancellationToken); + var admission = await gate.AdmitAsync(witness, operation, body is null ? null : ticketOf(body), cancellationToken); + if (!admission.IsAdmitted) + { + return (null, RefusalProblem(http, admission.Refusal), null); + } + + return bodyState == BodyState.NotJson + ? (null, Problem(http, StatusCodes.Status415UnsupportedMediaType, "lockey_unsupported_media_type"), null) + : (body, null, admission.Admission); + } + + private static bool TryState(string? text, out DeliveryInspectionState state) + { + state = DeliveryInspectionState.DeadLettered; + switch (text) + { + case null or "dead_lettered": + return true; + case "terminal_requested": + state = DeliveryInspectionState.TerminalRequested; + return true; + default: + return false; + } + } + + private static bool TryLimit(string? text, out int size) + { + size = DefaultPageSize; + if (text is null) + { + return true; + } + + if (!int.TryParse(text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed)) + { + return false; + } + + size = Math.Clamp(parsed, 1, MaximumPageSize); + return true; + } + + /// A tenant the row names: never the nil value and never the platform sentinel, which no event row can carry. + private static bool IsOperatorRowId(Guid tenant) => tenant != Guid.Empty && tenant != TenantId.PlatformSentinel.Value; +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index ae4826d1..c02d699b 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -68,6 +68,7 @@ internal static WebApplication MapLearnStackPlatformOperator(this WebApplication .ProducesProblem(StatusCodes.Status500InternalServerError) .ProducesProblem(StatusCodes.Status503ServiceUnavailable); MapOnboarding(group); + MapRecovery(group); return app; } diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index adf06d34..4ea9e830 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -438,6 +438,7 @@ public async Task WritePlatformOperatorResultAsync( if (!StronglyTypedId.IsAssigned(entry.TenantId) || entry.ModuleName == "identity" || !PlatformOperations.IsRegistered(admission.Operation) + || !(admission.Operation.RunsInPipeline || admission.Operation.NeedsPlatformRole) || !string.Equals(entry.Operation, admission.Operation.AuditSlug, StringComparison.Ordinal) || !string.Equals(entry.Reason, admission.Operation.ReasonSlug, StringComparison.Ordinal) || entry.ActorUserId is not null @@ -642,6 +643,50 @@ public async Task WriteEventTerminalAsync( } } + /// + public async Task WriteOperatorRecoveryAsync( + AuditEntryDraft entry, + OperatorRecoveryTransition transition, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + RefuseGlobalCapture(); + ArgumentNullException.ThrowIfNull(transition); + transition.EnsureMatches(entry, connection, transaction); + + var operation = transition.Kind switch + { + "replay" => PlatformOperations.DeliveryReplay.AuditSlug, + "reset" => PlatformOperations.DeliveryReset.AuditSlug, + _ => throw new ArgumentException("The recovery transition kind is not supported.", nameof(transition)), + }; + if (!_catalog.TryGetOffPath(operation, out var declared) + || declared.Operation != operation || declared.ModuleName != "platform" + || declared.OperationClass != OperationClass.Must + || declared.OperationType != OperationType.SecurityEvent || declared.EntityType is not null + || entry.Operation != declared.Operation || entry.ModuleName != declared.ModuleName + || entry.OperationClass != declared.OperationClass || entry.OperationType != declared.OperationType) + { + throw new ArgumentException("The recovery audit requires its declared MUST security event.", nameof(entry)); + } + + try + { + await using var command = connection.CreateCommand(); + command.CommandText = InsertSql; + command.Transaction = transaction; + Bind(command.Parameters, entry); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbException failure) + { + throw new AuditWriteFailedException( + "The recovery audit could not be written; its reset must roll back.", failure); + } + } + /// public async Task WriteJobTerminalAsync( AuditEntryDraft entry, diff --git a/backend/src/LearnStack.Infrastructure/Jobs/BackgroundJobPhysicalCapacity.cs b/backend/src/LearnStack.Infrastructure/Jobs/BackgroundJobPhysicalCapacity.cs index b5706488..7a72232e 100644 --- a/backend/src/LearnStack.Infrastructure/Jobs/BackgroundJobPhysicalCapacity.cs +++ b/backend/src/LearnStack.Infrastructure/Jobs/BackgroundJobPhysicalCapacity.cs @@ -16,7 +16,8 @@ public static BackgroundJobPhysicalCapacity Calculate(BackgroundJobInfrastructur var controls = topology.Pools.Values.Count(pool => pool.Kind == BackgroundJobWorkerPoolKind.Control); var invocations = topology.Pools.Values.Sum(pool => BackgroundJobRuntimeOptions.RetainedHardBound(pool.Workers)); // Stock W + four per-pool controls/lifecycle + two schedulers per - // Control pool + shared/bridge/messaging eleven + retained invocation U. + // Control pool + shared/bridge/messaging thirteen + retained invocation U. + // The thirteen include one operator recovery lane in each messaging store. // Each invocation has at most one actual routing, recovery acquisition, // confirmation or checkpoint-history SQL operation, including cleanup. // Step 5 adds one batch renewal slot, two recovery/probe slots and @@ -24,7 +25,7 @@ public static BackgroundJobPhysicalCapacity Calculate(BackgroundJobInfrastructur return new(pools, workers, controls, invocations, // Recurrence has one serialized SQL owner and one native manager // connection, including retained startup/native return and cleanup. - checked(workers + 4 * pools + 2 * controls + 18 + invocations)); + checked(workers + 4 * pools + 2 * controls + 20 + invocations)); } public void Validate(BackgroundJobPhysicalPoolSettings settings) diff --git a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs new file mode 100644 index 00000000..bd64d9d8 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs @@ -0,0 +1,209 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; + +namespace LearnStack.Infrastructure.Messaging; + +/// The operator's fenced replay of one dead-lettered subscriber delivery (ADR-0103 § 2). +public sealed partial class DeliveryDispatchStore +{ + // Every reason a delivery can be dead-lettered with. invalid_envelope is among them so that a fence that names it + // meets its own refusal (NotRecoverable) and not a stale fence: it is the one reason no replay can act on. + private static readonly string[] DeadLetterReasons = + ["unknown_type", "retired_type", "invalid_envelope", "retry_exhausted", "invalid_subscription"]; + + /// + /// Resets exactly one terminal delivery, under the fence the operator read, and writes the MUST result row on the + /// same transaction. The inbox identity, every sibling delivery and the producer row are untouched. + /// + /// + /// The row is locked and compared with the fence first: a mismatch is . + /// A matching fence on a row that is processed, leased, invalid_envelope, no longer an Active ordinary + /// subscription of its stored type, or whose tenant is not serving is + /// . A refusal writes no row and changes nothing. + /// + /// The admission is not for a replay, is stale or was spent. + /// The lane or the database was unavailable, or the commit's outcome is unknown. + /// The MUST row could not be written; nothing changed. + public async Task ReplayAsync( + DeliveryReplayRequest request, PlatformAdmission admission, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(admission); + OperatorRecoveryAdmission.Consume(admission, PlatformOperations.DeliveryReplay, _clock); + if (request.TenantId == Guid.Empty || request.TenantId == TenantId.PlatformSentinel.Value + || request.EventId == Guid.Empty || !OutboxEventRegistry.ValidSubscriptionId(request.SubscriptionId)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotFound); + } + + if (request.ReplayCount < 0 || !DeadLetterReasons.Contains(request.TerminalReason, StringComparer.Ordinal)) + { + // No stored row can carry this fence, so it is stale by construction. + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + try + { + return await ReplayCoreAsync(request, admission, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException + || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + throw new OperatorRecoveryUnavailableException(); + } + } + + private async Task ReplayCoreAsync( + DeliveryReplayRequest request, PlatformAdmission admission, CancellationToken cancellationToken) + { + using var deadline = Deadline(cancellationToken); + await using var ownedConnection = await OpenConnectionAsync(deadline.Token, operatorLane: true).ConfigureAwait(false); + var connection = ownedConnection.Connection; + await using var transaction = await connection.BeginTransactionAsync(deadline.Token).ConfigureAwait(false); + + string type; + bool processed; + bool leased; + DateTimeOffset? deadLettered; + string? reason; + int replayCount; + await using (var rowLock = new NpgsqlCommand($""" + SELECT type, processed_at IS NOT NULL, dead_lettered_at, terminal_reason, replay_count, + locked_by IS NOT NULL OR locked_until IS NOT NULL + FROM event_deliveries WHERE {Identity} FOR UPDATE + """, connection, transaction)) + { + Configure(rowLock); + AddIdentity(rowLock, request.TenantId, request.SubscriptionId, request.EventId); + await using var reader = await rowLock.ExecuteReaderAsync(deadline.Token).ConfigureAwait(false); + if (!await reader.ReadAsync(deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotFound); + } + + type = reader.GetString(0); + processed = reader.GetBoolean(1); + deadLettered = reader.IsDBNull(2) ? null : reader.GetFieldValue(2); + reason = reader.IsDBNull(3) ? null : reader.GetString(3); + replayCount = reader.GetInt32(4); + leased = reader.GetBoolean(5); + } + + if (deadLettered is not { } deadLetteredAt || deadLetteredAt.UtcTicks != request.DeadLetteredAt.UtcTicks + || replayCount != request.ReplayCount || !string.Equals(reason, request.TerminalReason, StringComparison.Ordinal)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + if (processed || leased || reason == "invalid_envelope" + || !_registry.IsActiveOrdinarySubscription(type, request.SubscriptionId) + || !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + } + + OperatorRecoveryTransition witness; + await using (var reset = new NpgsqlCommand($""" + UPDATE event_deliveries SET terminal_reason = NULL, dead_lettered_at = NULL, + attempts = 0, last_error = NULL, locked_by = NULL, locked_until = NULL, + available_after = clock_timestamp(), replay_count = replay_count + 1, + replayed_at = clock_timestamp() + WHERE {Identity} AND processed_at IS NULL AND dead_lettered_at = @dead AND terminal_reason = @reason + AND replay_count = @count AND locked_by IS NULL AND locked_until IS NULL AND type = @type + RETURNING event_id, tenant_id, organization_id, subscription_id, old.replay_count, old.dead_lettered_at, + old.terminal_reason, new.replay_count + """, connection, transaction)) + { + Configure(reset); + AddIdentity(reset, request.TenantId, request.SubscriptionId, request.EventId); + reset.Parameters.AddWithValue("dead", deadLetteredAt); + reset.Parameters.AddWithValue("reason", request.TerminalReason); + reset.Parameters.AddWithValue("count", request.ReplayCount); + reset.Parameters.AddWithValue("type", type); + await using var reader = await reset.ExecuteReaderAsync(deadline.Token).ConfigureAwait(false); + if (!await reader.ReadAsync(deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + witness = RecoveryMint.Replay(connection, transaction, reader, admission); + } + + await WriteRecoveryRowAsync(witness, admission, connection, transaction, deadline.Token).ConfigureAwait(false); + try + { + await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) + { + // COMMIT may have reached PostgreSQL. The change and its row commit together or not at all, so there is + // nothing to repair; the operator inspects the row, whose fence moved if the reset landed. + ownedConnection.RecordCommitFailure(failure); + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + } + + return new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, witness.AfterCount); + } + + private async Task WriteRecoveryRowAsync( + OperatorRecoveryTransition witness, PlatformAdmission admission, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken) + { + await using var scope = _scopes.CreateAsyncScope(); + var audit = scope.ServiceProvider.GetRequiredService(); + var draft = new AuditEntryDraft + { + Id = AuditEntryId.From(_ids.NewUuidV7()), + TenantId = TenantId.From(witness.TenantId), + OrganizationId = witness.OrganizationId is { } organization ? OrganizationId.From(organization) : null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "platform", + Operation = admission.Operation.AuditSlug, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = witness.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = _clock.UtcNow, + Metadata = witness.Metadata, + }; + await audit.WriteOperatorRecoveryAsync(draft, witness, connection, transaction, cancellationToken).ConfigureAwait(false); + } + + private async Task TenantServesAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, CancellationToken cancellationToken) + { + var lifecycle = _lifecycle ?? throw new InvalidOperationException("The tenant lifecycle projection is not configured."); + await using var command = new NpgsqlCommand( + "SELECT status, deleted_at IS NOT NULL, default_organization_id FROM tenants WHERE id = @tenant", connection, transaction); + Configure(command); + command.Parameters.AddWithValue("tenant", tenant); + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + return await reader.ReadAsync(cancellationToken).ConfigureAwait(false) + && lifecycle.AllowsTenant( + reader.GetString(0), reader.GetBoolean(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + BackgroundJobRecipientPolicy.ServingTenants); + } + + /// The store's own minting subtype for the recovery witness; no other type may derive from the seam. + private sealed class RecoveryMint : OperatorRecoveryTransition.MintingSource + { + internal static OperatorRecoveryTransition Replay( + DbConnection connection, DbTransaction transaction, DbDataReader row, PlatformAdmission admission) => + FromReplayUpdate(connection, transaction, row, admission); + } +} diff --git a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.cs b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.cs index f42d747e..11f2d979 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.cs @@ -3,6 +3,7 @@ using System.Data.Common; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Time; using Microsoft.Extensions.DependencyInjection; using Npgsql; @@ -11,7 +12,7 @@ namespace LearnStack.Infrastructure.Messaging; /// Short, database-time fenced dispatcher transitions on its confined role. -public sealed class DeliveryDispatchStore : EventTerminalTransition.MintingSource +public sealed partial class DeliveryDispatchStore : EventTerminalTransition.MintingSource { private const string Incomplete = "processed_at IS NULL AND dead_lettered_at IS NULL"; private const string Normal = Incomplete + " AND terminal_reason IS NULL AND attempts < 6" @@ -40,9 +41,10 @@ public sealed class DeliveryDispatchStore : EventTerminalTransition.MintingSourc private readonly IClock _clock; private readonly IServiceScopeFactory _scopes; private readonly object _connectionGate = new(); - // The main SQL owner and its uncertain-COMMIT reconciliation are the only - // simultaneous source users. Slots are retained through actual disposal. - private readonly OwnedConnection?[] _connections = new OwnedConnection?[2]; + // The main SQL owner and its uncertain-COMMIT reconciliation are the only simultaneous dispatcher users, in + // slots 0 and 1. Slot 2 belongs to the operator recovery owner alone (ADR-0103), so an operator's reset can never + // take the slot the dispatcher's own reconciliation needs. Slots are retained through actual disposal. + private readonly OwnedConnection?[] _connections = new OwnedConnection?[3]; private bool _cleanupUnconfirmed; /// Whether actual connection disposal failed; reading opens nothing. @@ -51,8 +53,11 @@ public bool HasUnconfirmedCleanup get { lock (_connectionGate) return _cleanupUnconfirmed; } } + private readonly BackgroundJobLifecycleProjection? _lifecycle; + public DeliveryDispatchStore(PrivilegedDataSource source, OutboxEventRegistry registry, - DeliveryDispatchOptions options, IGuidFactory ids, IClock clock, IServiceScopeFactory scopes) + DeliveryDispatchOptions options, IGuidFactory ids, IClock clock, IServiceScopeFactory scopes, + BackgroundJobLifecycleProjection? lifecycle = null) { ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(registry); @@ -67,6 +72,7 @@ public DeliveryDispatchStore(PrivilegedDataSource source, OutboxEventRegistry re _ids = ids; _clock = clock; _scopes = scopes; + _lifecycle = lifecycle; } public Task TryClaimAsync(IReadOnlyCollection blockedPartitions, @@ -301,40 +307,7 @@ FROM event_deliveries WHERE {Incomplete} return new(reader.GetInt64(0), reader.GetInt64(1), reader.GetDouble(2)); } - /// Resets exactly one completed terminal Active ordinary subscription; inbox identity is never reset. - public async Task ReplayAsync(Guid tenant, string subscription, Guid eventId, - CancellationToken cancellationToken = default) - { - if (tenant == Guid.Empty || tenant == TenantId.PlatformSentinel.Value || eventId == Guid.Empty - || !OutboxEventRegistry.ValidSubscriptionId(subscription)) return false; - using var deadline = Deadline(cancellationToken); - await using var ownedConnection = await OpenConnectionAsync(deadline.Token).ConfigureAwait(false); - var connection = ownedConnection.Connection; - await using var transaction = await connection.BeginTransactionAsync(deadline.Token).ConfigureAwait(false); - const string replayable = " AND processed_at IS NULL AND dead_lettered_at IS NOT NULL" - + " AND terminal_reason IS NOT NULL AND locked_by IS NULL AND locked_until IS NULL"; - await using var rowLock = new NpgsqlCommand( - $"SELECT type FROM event_deliveries WHERE {Identity}{replayable} FOR UPDATE", connection, transaction); - Configure(rowLock); - AddIdentity(rowLock, tenant, subscription, eventId); - if (await rowLock.ExecuteScalarAsync(deadline.Token).ConfigureAwait(false) is not string type - || !_registry.IsActiveOrdinarySubscription(type, subscription)) return false; - await using var reset = new NpgsqlCommand($""" - UPDATE event_deliveries SET terminal_reason = NULL, dead_lettered_at = NULL, - attempts = 0, last_error = NULL, locked_by = NULL, locked_until = NULL, - available_after = clock_timestamp(), replay_count = replay_count + 1, - replayed_at = clock_timestamp() - WHERE {Identity}{replayable} AND type = @type - """, connection, transaction); - Configure(reset); - AddIdentity(reset, tenant, subscription, eventId); - reset.Parameters.AddWithValue("type", type); - var updated = await reset.ExecuteNonQueryAsync(deadline.Token).ConfigureAwait(false) == 1; - await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); - return updated; - } - - private async ValueTask OpenConnectionAsync(CancellationToken cancellationToken) + private async ValueTask OpenConnectionAsync(CancellationToken cancellationToken, bool operatorLane = false) { BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); OwnedConnection owned; @@ -343,7 +316,9 @@ private async ValueTask OpenConnectionAsync(CancellationToken c { if (_cleanupUnconfirmed) throw new InvalidOperationException("The delivery dispatcher connection cleanup remains unconfirmed."); - var slot = _connections[0] is null ? 0 : _connections[1] is null ? 1 : -1; + var slot = operatorLane + ? _connections[2] is null ? 2 : -1 + : _connections[0] is null ? 0 : _connections[1] is null ? 1 : -1; if (slot < 0) throw new InvalidOperationException("The delivery dispatcher SQL ownership bound was exceeded."); owned = new OwnedConnection(this, slot); diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecovery.cs b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecovery.cs new file mode 100644 index 00000000..4c4f288a --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecovery.cs @@ -0,0 +1,69 @@ +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.Infrastructure.Messaging; + +/// +/// The confined owner of the two fenced operator recovery transitions (ADR-0103 § 4): it holds no credential and no +/// SQL, and reaches the dispatcher's outbox role only through the two stores' own operator lane, behind an +/// the gate minted for exactly that operation. +/// +/// +/// The route holds this interface and never a store, so no HTTP path resolves the dispatcher's store directly. The +/// owner counts every outcome so a replay storm and a fence refusal are visible to a monitoring owner. +/// +public sealed class OperatorRecovery : IOperatorRecovery +{ + private readonly DeliveryDispatchStore _deliveries; + private readonly OutboxDispatchStore _outbox; + + /// Builds the owner over the two stores it is the second writer of. + public OperatorRecovery(DeliveryDispatchStore deliveries, OutboxDispatchStore outbox) + { + ArgumentNullException.ThrowIfNull(deliveries); + ArgumentNullException.ThrowIfNull(outbox); + _deliveries = deliveries; + _outbox = outbox; + } + + /// + public async Task ReplayDeliveryAsync( + PlatformAdmission admission, DeliveryReplayRequest request, CancellationToken cancellationToken = default) + { + try + { + return Counted(PlatformOperations.DeliveryReplay, await _deliveries.ReplayAsync(request, admission, cancellationToken)); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.RecoveryUnavailable(PlatformOperations.DeliveryReplay, failure.CommitOutcomeUnknown); + throw; + } + } + + /// + public async Task ResetOutboxAsync( + PlatformAdmission admission, OutboxResetRequest request, CancellationToken cancellationToken = default) + { + try + { + return Counted(PlatformOperations.DeliveryReset, await _outbox.ResetAsync(request, admission, cancellationToken)); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.RecoveryUnavailable(PlatformOperations.DeliveryReset, failure.CommitOutcomeUnknown); + throw; + } + } + + private static OperatorRecoveryResult Counted(PlatformOperation operation, OperatorRecoveryResult result) + { + PlatformOperatorMetrics.Recovery(operation, result.Outcome); + if (result.Outcome == OperatorRecoveryOutcome.Applied) + { + PlatformOperatorMetrics.Result(operation); + } + + return result; + } +} diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryAdmission.cs b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryAdmission.cs new file mode 100644 index 00000000..40325961 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryAdmission.cs @@ -0,0 +1,24 @@ +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Infrastructure.Messaging; + +/// +/// Spends an operator's admission for one recovery transition: the operation it was minted for, still fresh, and +/// spent once (ADR-0101 § 7, ADR-0103 § 4). +/// +internal static class OperatorRecoveryAdmission +{ + /// Consumes , or throws when it is not for , is stale or spent. + /// The admission cannot be used for this transition. + internal static void Consume(PlatformAdmission admission, PlatformOperation expected, IClock clock) + { + if (!ReferenceEquals(admission.Operation, expected) + || string.IsNullOrEmpty(admission.Operator.CorrelationId) + || (clock.UtcNow - admission.IssuedAt).Duration() > PlatformAdmission.MaximumAge + || !admission.TryConsume()) + { + throw new InvalidOperationException("The operator admission is not valid for this recovery."); + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs new file mode 100644 index 00000000..a67412c8 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs @@ -0,0 +1,201 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; + +namespace LearnStack.Infrastructure.Messaging; + +/// The operator's narrow producer reset of one retry-exhausted outbox row (ADR-0103 § 3). +public sealed partial class OutboxDispatchStore +{ + /// + /// Resets one dead-lettered outbox row whose terminal reason is retry_exhausted, under the fence + /// (attempts, dead_lettered_at), renewing its attempt budget, and writes the MUST result row on the same + /// transaction. Every other reason and every processed row is refused. + /// + /// + /// A publication that already reached a subscriber is absorbed by stable event-id acceptance, which never reopens + /// an existing delivery row, so the reset reaches only subscriptions that have no delivery row yet. A row whose + /// stored type is now retired or unknown would only be dead-lettered again, so it is refused. + /// + /// The admission is not for a reset, is stale or was spent. + /// The lane or the database was unavailable, or the commit's outcome is unknown. + /// The MUST row could not be written; nothing changed. + public async Task ResetAsync( + OutboxResetRequest request, PlatformAdmission admission, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(admission); + OperatorRecoveryAdmission.Consume(admission, PlatformOperations.DeliveryReset, _clock); + if (request.TenantId == Guid.Empty || request.TenantId == TenantId.PlatformSentinel.Value || request.EventId == Guid.Empty) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotFound); + } + + if (request.Attempts < 0) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + try + { + return await ResetCoreAsync(request, admission, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException + || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + throw new OperatorRecoveryUnavailableException(); + } + } + + private async Task ResetCoreAsync( + OutboxResetRequest request, PlatformAdmission admission, CancellationToken cancellationToken) + { + using var deadline = Deadline(cancellationToken); + await using var ownedConnection = await OpenConnectionAsync(deadline.Token, operatorLane: true).ConfigureAwait(false); + var connection = ownedConnection.Connection; + await using var transaction = await connection.BeginTransactionAsync(deadline.Token).ConfigureAwait(false); + + string type; + bool processed; + bool leased; + DateTimeOffset? deadLettered; + string? reason; + int attempts; + await using (var rowLock = new NpgsqlCommand(""" + SELECT type, processed_at IS NOT NULL, dead_lettered_at, terminal_reason, attempts, + locked_by IS NOT NULL OR locked_until IS NOT NULL + FROM outbox_messages WHERE id = @id AND tenant_id = @tenant FOR UPDATE + """, connection, transaction)) + { + Configure(rowLock); + rowLock.Parameters.AddWithValue("id", request.EventId); + rowLock.Parameters.AddWithValue("tenant", request.TenantId); + await using var reader = await rowLock.ExecuteReaderAsync(deadline.Token).ConfigureAwait(false); + if (!await reader.ReadAsync(deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotFound); + } + + type = reader.GetString(0); + processed = reader.GetBoolean(1); + deadLettered = reader.IsDBNull(2) ? null : reader.GetFieldValue(2); + reason = reader.IsDBNull(3) ? null : reader.GetString(3); + attempts = reader.GetInt32(4); + leased = reader.GetBoolean(5); + } + + if (deadLettered is not { } deadLetteredAt || deadLetteredAt.UtcTicks != request.DeadLetteredAt.UtcTicks + || attempts != request.Attempts) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + var disposition = _registry.Resolve(type).Disposition; + if (processed || leased || reason != "retry_exhausted" + || disposition is OutboxEventDisposition.Retired or OutboxEventDisposition.Unknown + || !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + } + + OperatorRecoveryTransition witness; + await using (var reset = new NpgsqlCommand(""" + UPDATE outbox_messages SET terminal_reason = NULL, dead_lettered_at = NULL, attempts = 0, last_error = NULL, + locked_by = NULL, locked_until = NULL, available_after = clock_timestamp() + WHERE id = @id AND tenant_id = @tenant AND processed_at IS NULL AND dead_lettered_at = @dead + AND terminal_reason = 'retry_exhausted' AND attempts = @attempts + AND locked_by IS NULL AND locked_until IS NULL + RETURNING id, tenant_id, organization_id, old.attempts, old.dead_lettered_at, old.terminal_reason, new.attempts + """, connection, transaction)) + { + Configure(reset); + reset.Parameters.AddWithValue("id", request.EventId); + reset.Parameters.AddWithValue("tenant", request.TenantId); + reset.Parameters.AddWithValue("dead", deadLetteredAt); + reset.Parameters.AddWithValue("attempts", request.Attempts); + await using var reader = await reset.ExecuteReaderAsync(deadline.Token).ConfigureAwait(false); + if (!await reader.ReadAsync(deadline.Token).ConfigureAwait(false)) + { + return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + } + + witness = RecoveryMint.Reset(connection, transaction, reader, admission); + } + + await WriteRecoveryRowAsync(witness, admission, connection, transaction, deadline.Token).ConfigureAwait(false); + try + { + await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) + { + // COMMIT may have reached PostgreSQL; the row and its audit commit together or not at all, so the + // operator inspects the row, whose fence moved if the reset landed. + ownedConnection.RecordCommitFailure(failure); + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + } + + return new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, witness.AfterCount); + } + + private async Task WriteRecoveryRowAsync( + OperatorRecoveryTransition witness, PlatformAdmission admission, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken) + { + await using var scope = _scopes.CreateAsyncScope(); + var audit = scope.ServiceProvider.GetRequiredService(); + var draft = new AuditEntryDraft + { + Id = AuditEntryId.From(_ids.NewUuidV7()), + TenantId = TenantId.From(witness.TenantId), + OrganizationId = witness.OrganizationId is { } organization ? OrganizationId.From(organization) : null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "platform", + Operation = admission.Operation.AuditSlug, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = witness.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = _clock.UtcNow, + Metadata = witness.Metadata, + }; + await audit.WriteOperatorRecoveryAsync(draft, witness, connection, transaction, cancellationToken).ConfigureAwait(false); + } + + private async Task TenantServesAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, CancellationToken cancellationToken) + { + var lifecycle = _lifecycle ?? throw new InvalidOperationException("The tenant lifecycle projection is not configured."); + await using var command = new NpgsqlCommand( + "SELECT status, deleted_at IS NOT NULL, default_organization_id FROM tenants WHERE id = @tenant", connection, transaction); + Configure(command); + command.Parameters.AddWithValue("tenant", tenant); + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + return await reader.ReadAsync(cancellationToken).ConfigureAwait(false) + && lifecycle.AllowsTenant( + reader.GetString(0), reader.GetBoolean(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + BackgroundJobRecipientPolicy.ServingTenants); + } + + /// The store's own minting subtype for the recovery witness; no other type may derive from the seam. + private sealed class RecoveryMint : OperatorRecoveryTransition.MintingSource + { + internal static OperatorRecoveryTransition Reset( + DbConnection connection, DbTransaction transaction, DbDataReader row, PlatformAdmission admission) => + FromResetUpdate(connection, transaction, row, admission); + } +} diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.cs b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.cs index 4e56227b..0985f6a4 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.cs @@ -3,6 +3,7 @@ using System.Data.Common; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Time; using Microsoft.Extensions.DependencyInjection; using Npgsql; @@ -11,7 +12,7 @@ namespace LearnStack.Infrastructure.Messaging; /// Short, database-time fenced dispatcher transitions on its confined role. -public sealed class OutboxDispatchStore : EventTerminalTransition.MintingSource +public sealed partial class OutboxDispatchStore : EventTerminalTransition.MintingSource { private const string Incomplete = "processed_at IS NULL AND dead_lettered_at IS NULL"; private const string Normal = Incomplete + " AND terminal_reason IS NULL AND attempts < 6" @@ -33,9 +34,10 @@ public sealed class OutboxDispatchStore : EventTerminalTransition.MintingSource private readonly IClock _clock; private readonly IServiceScopeFactory _scopes; private readonly object _connectionGate = new(); - // The main SQL owner and its uncertain-COMMIT reconciliation are the only - // simultaneous source users. Slots are retained through actual disposal. - private readonly OwnedConnection?[] _connections = new OwnedConnection?[2]; + // The main SQL owner and its uncertain-COMMIT reconciliation are the only simultaneous dispatcher users, in + // slots 0 and 1. Slot 2 belongs to the operator recovery owner alone (ADR-0103), so an operator's reset can never + // take the slot the dispatcher's own reconciliation needs. Slots are retained through actual disposal. + private readonly OwnedConnection?[] _connections = new OwnedConnection?[3]; private bool _cleanupUnconfirmed; /// Whether actual connection disposal failed; reading opens nothing. @@ -44,8 +46,11 @@ public bool HasUnconfirmedCleanup get { lock (_connectionGate) return _cleanupUnconfirmed; } } + private readonly BackgroundJobLifecycleProjection? _lifecycle; + public OutboxDispatchStore(PrivilegedDataSource source, OutboxEventRegistry registry, - OutboxDispatchOptions options, IGuidFactory ids, IClock clock, IServiceScopeFactory scopes) + OutboxDispatchOptions options, IGuidFactory ids, IClock clock, IServiceScopeFactory scopes, + BackgroundJobLifecycleProjection? lifecycle = null) { ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(registry); @@ -60,6 +65,7 @@ public OutboxDispatchStore(PrivilegedDataSource source, OutboxEventRegistry regi _ids = ids; _clock = clock; _scopes = scopes; + _lifecycle = lifecycle; } public Task TryClaimAsync(IReadOnlyCollection blockedPartitions, @@ -283,7 +289,7 @@ FROM outbox_messages WHERE {Incomplete} return new(reader.GetInt64(0), reader.GetInt64(1), reader.GetDouble(2)); } - private async ValueTask OpenConnectionAsync(CancellationToken cancellationToken) + private async ValueTask OpenConnectionAsync(CancellationToken cancellationToken, bool operatorLane = false) { BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); OwnedConnection owned; @@ -292,7 +298,9 @@ private async ValueTask OpenConnectionAsync(CancellationToken c { if (_cleanupUnconfirmed) throw new InvalidOperationException("The outbox dispatcher connection cleanup remains unconfirmed."); - var slot = _connections[0] is null ? 0 : _connections[1] is null ? 1 : -1; + var slot = operatorLane + ? _connections[2] is null ? 2 : -1 + : _connections[0] is null ? 0 : _connections[1] is null ? 1 : -1; if (slot < 0) throw new InvalidOperationException("The outbox dispatcher SQL ownership bound was exceeded."); owned = new OwnedConnection(this, slot); diff --git a/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.Designer.cs b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.Designer.cs new file mode 100644 index 00000000..2d794cac --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.Designer.cs @@ -0,0 +1,29 @@ +// +using LearnStack.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace LearnStack.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(PlatformDbContext))] + [Migration("20261120120000_grant_platform_delivery_inspection")] + partial class grant_platform_delivery_inspection + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.cs b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.cs new file mode 100644 index 00000000..90f1b0ca --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261120120000_grant_platform_delivery_inspection.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Infrastructure.Persistence.Migrations +{ + /// + /// ADR-0103: the platform role reads the metadata of dead-lettered and pending-terminal rows and quarantined jobs + /// through named columns, so the database refuses what an inspection must not return. + /// + public partial class grant_platform_delivery_inspection : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // The role held table-wide SELECT on outbox_messages for the purge of Phase 11, which needs only DELETE and + // the columns its predicate reads. A column grant added beside the table grant would exclude nothing. + migrationBuilder.Sql(""" + REVOKE SELECT ON public.outbox_messages FROM learnstack_platform; + GRANT SELECT (id, tenant_id, organization_id, occurred_at, type, processed_at, attempts, last_error, + available_after, locked_until, terminal_reason, dead_lettered_at) + ON public.outbox_messages TO learnstack_platform; + GRANT SELECT (tenant_id, subscription_id, event_id, organization_id, occurred_at, type, processed_at, + attempts, last_error, available_after, locked_until, terminal_reason, dead_lettered_at, + replay_count, replayed_at) + ON public.event_deliveries TO learnstack_platform; + GRANT SELECT (id, tenant_id, organization_id, definition_key, profile, queue, capacity_group, + original_due_at, created_at, phase, normal_attempts, finalize_attempts, available_after, + ownership_kind, ownership_until, attempt_deadline, probe_after, unsuccessful_probes, + last_error, quarantine_reason, terminal_reason, processed_at, dead_lettered_at, + finalization_status, finalization_reason, business_finalization_incomplete, + wake_generation) + ON public.background_jobs TO learnstack_platform; + GRANT SELECT (tenant_id, capacity_group, job_id, attempt_id, reserved_at, released_at, release_reason) + ON public.background_job_reservations TO learnstack_platform; + + CREATE INDEX ix_outbox_messages_dead_lettered + ON public.outbox_messages (dead_lettered_at, id) WHERE dead_lettered_at IS NOT NULL; + CREATE INDEX ix_event_deliveries_dead_lettered + ON public.event_deliveries (dead_lettered_at, tenant_id, subscription_id, event_id) + WHERE dead_lettered_at IS NOT NULL; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + throw new NotSupportedException("The platform role's column grants require a reviewed forward migration."); + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs new file mode 100644 index 00000000..5234a8d7 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs @@ -0,0 +1,247 @@ +using System.Data.Common; +using System.Globalization; +using System.Text; +using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Infrastructure.PlatformOperator; + +/// +/// The metadata-only operator inspection of dead-lettered and pending-terminal outbox rows and deliveries and of +/// quarantined jobs (ADR-0103 § 1). +/// +/// +/// +/// The database bounds the projection. Each page runs in one entered platform scope, on the platform role, +/// whose column grants exclude every envelope, parameter, plan, outcome and causal column: a statement that named +/// one would be refused by PostgreSQL, so the projection does not rest on this file's discipline. The scope's entry +/// row, naming the inspection operation, is the audit; the scope reads and changes nothing, so it writes no result +/// row and ends by disposal. +/// +/// +/// Cursors are keyset positions. A cursor names the resource, the state and the last row's ordering key, and +/// carries no authority: it can move a page within what the operator may already read. +/// +/// +public sealed class DeliveryInspection(IPlatformAdminScope scope, OutboxEventRegistry registry) : IDeliveryInspection +{ + private const int MaximumLimit = 100; + + private const string OutboxColumns = "id, tenant_id, organization_id, occurred_at, type, attempts, last_error, " + + "available_after, locked_until, terminal_reason, dead_lettered_at, processed_at"; + + private const string DeliveryColumns = "tenant_id, subscription_id, event_id, organization_id, occurred_at, type, attempts, " + + "last_error, available_after, locked_until, terminal_reason, dead_lettered_at, replay_count, replayed_at, processed_at"; + + /// + public Task?> InspectOutboxAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) + { + var (where, order, byDeadLetter) = state == DeliveryInspectionState.DeadLettered + ? ("dead_lettered_at IS NOT NULL AND processed_at IS NULL", "dead_lettered_at", true) + : ("processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL", "available_after", false); + return PageAsync( + admission, "outbox." + state, cursor, limit, cancellationToken, + (after, key, size) => new Statement( + $"SELECT {OutboxColumns} FROM outbox_messages WHERE {where}" + + (after is null ? string.Empty : $" AND ({order}, id) > (@after, @key)") + + $" ORDER BY {order}, id LIMIT @size", + [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, size)]), + reader => MapOutbox(reader), + row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, + row => row.EventId.ToString("D"), + key => Guid.TryParse(key, out _)); + } + + /// + public Task?> InspectDeliveriesAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) + { + var (where, order, byDeadLetter) = state == DeliveryInspectionState.DeadLettered + ? ("dead_lettered_at IS NOT NULL AND processed_at IS NULL", "dead_lettered_at", true) + : ("processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL", "available_after", false); + return PageAsync( + admission, "delivery." + state, cursor, limit, cancellationToken, + (after, key, size) => + { + var parts = key?.Split('|'); + var parameters = KeyParameters(after, null, Guid.Empty, size); + if (parts is { Length: 3 } && Guid.TryParse(parts[0], out var tenant) && Guid.TryParse(parts[2], out var eventId)) + { + parameters.Add(new PlatformSqlParameter("tenant", tenant)); + parameters.Add(new PlatformSqlParameter("subscription", parts[1])); + parameters.Add(new PlatformSqlParameter("event", eventId)); + } + + return new Statement( + $"SELECT {DeliveryColumns} FROM event_deliveries WHERE {where}" + + (after is null ? string.Empty : $" AND ({order}, tenant_id, subscription_id, event_id) > (@after, @tenant, @subscription, @event)") + + $" ORDER BY {order}, tenant_id, subscription_id, event_id LIMIT @size", + parameters); + }, + reader => MapDelivery(reader), + row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, + row => $"{row.TenantId:D}|{row.SubscriptionId}|{row.EventId:D}", + key => key.Split('|') is { Length: 3 } parts && Guid.TryParse(parts[0], out _) && Guid.TryParse(parts[2], out _) + && OutboxEventRegistry.ValidSubscriptionId(parts[1])); + } + + /// + public Task?> InspectJobsAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => + PageAsync( + admission, "job.quarantined", cursor, limit, cancellationToken, + (after, key, size) => new Statement( + """ + SELECT j.id, j.tenant_id, j.organization_id, j.definition_key, j.profile, j.queue, j.capacity_group, + j.created_at, j.phase, j.normal_attempts, j.finalize_attempts, j.quarantine_reason, j.last_error, + j.ownership_until, j.probe_after, j.unsuccessful_probes, j.finalization_status, + j.business_finalization_incomplete, + (SELECT count(*) FROM background_job_reservations r + WHERE r.tenant_id = j.tenant_id AND r.job_id = j.id AND r.released_at IS NULL), + (SELECT count(*) FROM background_job_reservations r + WHERE r.tenant_id = j.tenant_id AND r.capacity_group = j.capacity_group AND r.released_at IS NULL) + FROM background_jobs j WHERE j.phase = 'quarantined' + """ + + (after is null ? string.Empty : " AND (j.created_at, j.id) > (@after, @key)") + + " ORDER BY j.created_at, j.id LIMIT @size", + [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, size)]), + reader => MapJob(reader), + row => row.CreatedAt.UtcTicks, + row => row.JobId.ToString("D"), + key => Guid.TryParse(key, out _)); + + private async Task?> PageAsync( + PlatformAdmission admission, + string scopeKey, + string? cursor, + int limit, + CancellationToken cancellationToken, + Func statement, + Func map, + Func ticksOf, + Func keyOf, + Func keyIsValid) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, PlatformOperations.DeliveryInspect)) + { + throw new ArgumentException("The admission is not for a delivery inspection.", nameof(admission)); + } + + var size = Math.Clamp(limit, 1, MaximumLimit); + DateTimeOffset? after = null; + string? key = null; + if (cursor is not null) + { + if (!TryDecode(cursor, scopeKey, out var ticks, out key) || !keyIsValid(key)) + { + return null; + } + + after = new DateTimeOffset(ticks, TimeSpan.Zero); + } + + await using var handle = await scope.EnterAsync(admission, cancellationToken).ConfigureAwait(false); + var built = statement(after, key, size + 1); + var rows = await handle.QueryAsync(built.Sql, built.Parameters, map, cancellationToken).ConfigureAwait(false); + var items = rows.Take(size).ToList(); + var next = rows.Count > size && items.Count > 0 + ? Encode(scopeKey, ticksOf(items[^1]), keyOf(items[^1])) + : null; + return new InspectionPage(items, next); + } + + private static List KeyParameters(DateTimeOffset? after, string? key, Guid id, int size) + { + var parameters = new List { new("size", size) }; + if (after is { } at) + { + parameters.Add(new PlatformSqlParameter("after", at)); + if (key is not null) + { + parameters.Add(new PlatformSqlParameter("key", id)); + } + } + + return parameters; + } + + private OutboxMessageInspection MapOutbox(DbDataReader reader) + { + var type = reader.GetString(4); + var reason = reader.IsDBNull(9) ? null : reader.GetString(9); + var lockedUntil = reader.IsDBNull(8) ? (DateTimeOffset?)null : reader.GetFieldValue(8); + var deadLettered = reader.IsDBNull(10) ? (DateTimeOffset?)null : reader.GetFieldValue(10); + var disposition = registry.Resolve(type); + return new OutboxMessageInspection( + reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), disposition.EventTypeLabel, + reader.GetFieldValue(3), reader.GetInt32(5), reader.IsDBNull(6) ? null : reader.GetString(6), + reader.GetFieldValue(7), lockedUntil, reason, deadLettered, + Actionable: deadLettered is not null && reason == "retry_exhausted" && reader.IsDBNull(11) && lockedUntil is null + && disposition.Disposition is not (OutboxEventDisposition.Retired or OutboxEventDisposition.Unknown)); + } + + private EventDeliveryInspection MapDelivery(DbDataReader reader) + { + var type = reader.GetString(5); + var subscription = reader.GetString(1); + var reason = reader.IsDBNull(10) ? null : reader.GetString(10); + var lockedUntil = reader.IsDBNull(9) ? (DateTimeOffset?)null : reader.GetFieldValue(9); + var deadLettered = reader.IsDBNull(11) ? (DateTimeOffset?)null : reader.GetFieldValue(11); + return new EventDeliveryInspection( + reader.GetGuid(0), subscription, reader.GetGuid(2), reader.IsDBNull(3) ? null : reader.GetGuid(3), + registry.Resolve(type).EventTypeLabel, reader.GetFieldValue(4), reader.GetInt32(6), + reader.IsDBNull(7) ? null : reader.GetString(7), reader.GetFieldValue(8), lockedUntil, reason, + deadLettered, reader.GetInt32(12), reader.IsDBNull(13) ? null : reader.GetFieldValue(13), + Actionable: deadLettered is not null && reader.IsDBNull(14) && lockedUntil is null && reason != "invalid_envelope" + && registry.IsActiveOrdinarySubscription(type, subscription)); + } + + private static QuarantinedJobInspection MapJob(DbDataReader reader) => new( + reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), reader.GetString(3), + reader.GetString(4), reader.GetString(5), reader.IsDBNull(6) ? null : reader.GetString(6), + reader.GetFieldValue(7), reader.GetString(8), reader.GetInt32(9), reader.GetInt32(10), + reader.IsDBNull(11) ? null : reader.GetString(11), reader.IsDBNull(12) ? null : reader.GetString(12), + reader.IsDBNull(13) ? null : reader.GetFieldValue(13), + reader.IsDBNull(14) ? null : reader.GetFieldValue(14), reader.GetInt32(15), + reader.IsDBNull(16) ? null : reader.GetString(16), reader.GetBoolean(17), + checked((int)reader.GetInt64(18)), checked((int)reader.GetInt64(19))); + + private static string Encode(string scopeKey, long ticks, string key) => + Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join('~', "v1", scopeKey, ticks.ToString(CultureInfo.InvariantCulture), key))) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static bool TryDecode(string cursor, string scopeKey, out long ticks, out string key) + { + ticks = 0; + key = string.Empty; + if (cursor.Length is 0 or > 512) + { + return false; + } + + try + { + var padded = cursor.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + ((4 - padded.Length % 4) % 4), '='); + var parts = Encoding.UTF8.GetString(Convert.FromBase64String(padded)).Split('~', 4); + if (parts.Length != 4 || parts[0] != "v1" || parts[1] != scopeKey + || !long.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out ticks) + || ticks < 0 || ticks > DateTimeOffset.MaxValue.Ticks) + { + return false; + } + + key = parts[3]; + return key.Length > 0; + } + catch (FormatException) + { + return false; + } + } + + private sealed record Statement(string Sql, IReadOnlyList Parameters); +} diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs index d702796b..6542e569 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActCatalog.cs @@ -19,8 +19,9 @@ public sealed class PlatformOperatorActCatalog private readonly FrozenDictionary _acts; /// - /// Builds the catalog; every operation must be a registered one that needs no platform role, and none may be the - /// controlled issuer rebind, which is an offline act on its own role and never a pipeline act (ADR-0104). + /// Builds the catalog; every operation must be a registered pipeline act on the application role. The controlled + /// issuer rebind (ADR-0104) and the recovery transitions (ADR-0103) each run on a confined role of their own and + /// are never pipeline acts. /// public PlatformOperatorActCatalog(IEnumerable> acts) { @@ -28,8 +29,7 @@ public PlatformOperatorActCatalog(IEnumerable pair.Key.IsAbstract || !PlatformOperations.IsRegistered(pair.Value.Operation) - || pair.Value.Operation.NeedsPlatformRole - || ReferenceEquals(pair.Value.Operation, PlatformOperations.IdentityAuthorityRebind))) + || !pair.Value.Operation.RunsInPipeline)) { throw new ArgumentException("The operator act catalog needs registered operations that use the application role."); } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs index e8d9c780..a3381073 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs @@ -49,7 +49,7 @@ public async Task ExecuteAsync( { ArgumentNullException.ThrowIfNull(admission); ArgumentNullException.ThrowIfNull(request); - if (!PlatformOperations.IsRegistered(admission.Operation) || admission.Operation.NeedsPlatformRole + if (!PlatformOperations.IsRegistered(admission.Operation) || !admission.Operation.RunsInPipeline || !acts.TryGet(request.GetType(), out var act) || !ReferenceEquals(act.Operation, admission.Operation) || !StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel) { diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index 7a250d62..c11551d2 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -29,6 +29,9 @@ public static class PlatformOperatorMetrics /// Acts refused with 503 because a MUST row could not be written, by operation. public const string AuditFailureCounterName = "learnstack_platform_operator_audit_failures_total"; + /// Recovery transitions by operation and outcome (ADR-0103 § 10). + public const string RecoveryCounterName = "learnstack_platform_operator_recoveries_total"; + /// Issuer metadata or key fetches that failed or were refused (no label). public const string MetadataFailureCounterName = "learnstack_platform_operator_metadata_failures_total"; @@ -46,6 +49,9 @@ public static class PlatformOperatorMetrics private static readonly Counter Acts = Meter.CreateCounter(ActCounterName, description: "Operator onboarding acts by operation and outcome."); + private static readonly Counter Recoveries = + Meter.CreateCounter(RecoveryCounterName, description: "Operator recovery transitions by operation and outcome."); + private static readonly Counter AuditFailures = Meter.CreateCounter(AuditFailureCounterName, description: "Operator acts refused because the MUST row was not durable."); @@ -101,6 +107,25 @@ public static void Act(PlatformOperation operation, PlatformOperatorActOutcome o _ => "failed", })); + /// + /// Counts one recovery transition by how it ended: applied, stale_fence, not_recoverable or + /// not_found. A fence refusal is its own label so a monitoring owner can see a replay storm. + /// + public static void Recovery(PlatformOperation operation, OperatorRecoveryOutcome outcome) => + Recoveries.Add(1, new KeyValuePair("operation", operation.AuditSlug), + new KeyValuePair("outcome", outcome switch + { + OperatorRecoveryOutcome.Applied => "applied", + OperatorRecoveryOutcome.StaleFence => "stale_fence", + OperatorRecoveryOutcome.NotRecoverable => "not_recoverable", + _ => "not_found", + })); + + /// Counts a recovery the owner could not finish: unavailable, or commit_unknown when it may have landed. + public static void RecoveryUnavailable(PlatformOperation operation, bool commitOutcomeUnknown) => + Recoveries.Add(1, new KeyValuePair("operation", operation.AuditSlug), + new KeyValuePair("outcome", commitOutcomeUnknown ? "commit_unknown" : "unavailable")); + /// Counts an act that was refused because its MUST row could not be written. public static void AuditFailed(PlatformOperation operation) => AuditFailures.Add(1, new KeyValuePair("operation", operation.AuditSlug)); diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs index a5eeeba6..2fbe33a5 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs @@ -35,7 +35,7 @@ internal IDisposable Enter(PlatformAdmission admission, ITenantContext context) ArgumentNullException.ThrowIfNull(admission); ArgumentNullException.ThrowIfNull(context); if (!CanIssue || _frame is not null || !PlatformOperations.IsRegistered(admission.Operation) - || admission.Operation.NeedsPlatformRole) + || !admission.Operation.RunsInPipeline) { throw new InvalidOperationException("Operator act provenance is invalid."); } diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index 25341d7f..9a84c011 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -204,6 +204,25 @@ Task WriteIdentityRebindResultAsync( CancellationToken cancellationToken = default) => throw new InvalidOperationException("This audit store cannot write an identity rebind result."); + /// + /// Inserts an operator's MUST recovery row on the live transaction of the fenced reset it describes + /// (ADR-0103 § 5). + /// + /// + /// A witness-bound method like the terminal write, for the second writer of dispatcher status: the + /// binds the row to the admitted operation, its closed reason, the operator's + /// attribution and the fence before and after. The row names the real event tenant and carries no actor and no + /// ticket. The operation must be declared off-path as MUST/SecurityEvent. Any mismatch or write failure requires + /// the caller to roll the reset back. This seam opens and commits no transaction. + /// + Task WriteOperatorRecoveryAsync( + AuditEntryDraft entry, + OperatorRecoveryTransition transition, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + throw new InvalidOperationException("This audit store cannot write an operator recovery row."); + /// Inserts a MUST terminal audit on the successful transition's live transaction. /// /// The producer transition store is the only caller in P02b-2. The operation diff --git a/backend/src/LearnStack.SharedKernel/Audit/OperatorRecoveryTransition.cs b/backend/src/LearnStack.SharedKernel/Audit/OperatorRecoveryTransition.cs new file mode 100644 index 00000000..545d7583 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Audit/OperatorRecoveryTransition.cs @@ -0,0 +1,210 @@ +using System.Buffers; +using System.Data; +using System.Data.Common; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.SharedKernel.Audit; + +/// +/// The immutable result of one operator's fenced reset of a dead-lettered row, in its live transaction +/// (ADR-0103 § 5). +/// +/// +/// +/// Construction is private and its protected minting seam is confined to the two dispatcher stores by the +/// production architecture census, as the terminal witness's is. It is a separate witness because the terminal one +/// demands the system actor, a null reason and fixed metadata, so it cannot carry an operator: this one binds the +/// row to the admitted operation, the closed reason, the admitted operator's attribution and the fence the +/// returned row showed before and after. It names the real event tenant and carries no ticket, because a tenant can +/// read the row. +/// +/// +public sealed class OperatorRecoveryTransition +{ + private static readonly Regex SubscriptionGrammar = new( + @"\A[a-z][a-z0-9]*\.[a-z][a-z0-9-]*\.v[1-9][0-9]*\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); + + private readonly DbConnection _connection; + private readonly DbTransaction _transaction; + private readonly PlatformAdmission _admission; + + private OperatorRecoveryTransition( + DbConnection connection, DbTransaction transaction, DbDataReader returnedRow, PlatformAdmission admission, bool replay) + { + if (connection.State != ConnectionState.Open || !ReferenceEquals(transaction.Connection, connection)) + { + throw new ArgumentException("A recovery transition requires the caller's live transaction."); + } + + var expected = replay ? PlatformOperations.DeliveryReplay : PlatformOperations.DeliveryReset; + if (!ReferenceEquals(admission.Operation, expected) || string.IsNullOrEmpty(admission.Operator.CorrelationId)) + { + throw new ArgumentException("The admission is not for this recovery operation."); + } + + if (returnedRow.FieldCount != (replay ? 8 : 7)) + { + throw new ArgumentException("The recovery UPDATE must return its complete bound row."); + } + + _connection = connection; + _transaction = transaction; + _admission = admission; + Kind = replay ? "replay" : "reset"; + EventId = returnedRow.GetGuid(0); + TenantId = returnedRow.GetGuid(1); + OrganizationId = returnedRow.IsDBNull(2) ? null : returnedRow.GetGuid(2); + var next = 3; + SubscriptionId = replay ? returnedRow.GetString(next++) : null; + BeforeCount = returnedRow.GetInt32(next++); + BeforeDeadLetteredAt = returnedRow.GetFieldValue(next++); + BeforeReason = returnedRow.GetString(next++); + AfterCount = returnedRow.GetInt32(next); + + if (EventId == Guid.Empty || TenantId == Guid.Empty + || TenantId == Identifiers.TenantId.PlatformSentinel.Value || OrganizationId == Guid.Empty + || BeforeCount < 0 || AfterCount < 0 + || (replay + ? SubscriptionId is null || !SubscriptionGrammar.IsMatch(SubscriptionId) + || BeforeReason is not ("unknown_type" or "retired_type" or "retry_exhausted" or "invalid_subscription") + || AfterCount != BeforeCount + 1 + : BeforeReason != "retry_exhausted" || AfterCount != 0)) + { + throw new ArgumentException("The recovery UPDATE returned invalid transition identity."); + } + + CorrelationId = admission.Operator.CorrelationId; + Metadata = ComposeMetadata(); + } + + /// Either replay (a subscriber delivery) or reset (a producer row). + public string Kind { get; } + + /// The event identity: the outbox row id, which a delivery keeps. + public Guid EventId { get; } + + /// The real tenant the stored row names. + public Guid TenantId { get; } + + /// The organization the stored row names, when it names one. + public Guid? OrganizationId { get; } + + /// The subscription of a replayed delivery, and null for a reset. + public string? SubscriptionId { get; } + + /// The fence's count before: replay_count of a delivery or attempts of a producer row. + public int BeforeCount { get; } + + /// The fence's timestamp before. + public DateTimeOffset BeforeDeadLetteredAt { get; } + + /// The terminal reason the row carried before. + public string BeforeReason { get; } + + /// The fence's count after. + public int AfterCount { get; } + + /// The admitted correlation id the row carries. + public string CorrelationId { get; } + + /// The exact metadata text the row must carry. + public string Metadata { get; } + + /// Refuses a draft or transaction that does not describe this exact transition. + public void EnsureMatches(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction) + { + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + if (connection.State != ConnectionState.Open || !ReferenceEquals(transaction.Connection, connection)) + { + throw new ArgumentException("A recovery transition requires the caller's live transaction.", nameof(entry)); + } + + if (!ReferenceEquals(_connection, connection) || !ReferenceEquals(_transaction, transaction) + || !entry.Id.IsInitialized() || entry.Id.Value == Guid.Empty + || !entry.TenantId.IsInitialized() || entry.TenantId.Value != TenantId + || (entry.OrganizationId is { } organization && !organization.IsInitialized()) + || entry.OrganizationId?.Value != OrganizationId + || !string.Equals(entry.Operation, _admission.Operation.AuditSlug, StringComparison.Ordinal) + || !string.Equals(entry.Reason, _admission.Operation.ReasonSlug, StringComparison.Ordinal) + || !string.Equals(entry.Metadata, Metadata, StringComparison.Ordinal) + || !string.Equals(entry.CorrelationId, CorrelationId, StringComparison.Ordinal) + || entry.ActorUserId is not null || entry.ActorEmail is not null + || entry.Outcome != AuditOutcome.Success || entry.ErrorKey is not null + || entry.OperationClass != OperationClass.Must || entry.OperationType != OperationType.SecurityEvent + || entry.EntityType is not null || entry.EntityId is not null + || entry.BeforeState is not null || entry.AfterState is not null || entry.Changes is not null + || entry.IpAddress is not null || entry.UserAgent is not null) + { + throw new ArgumentException("The recovery audit draft does not match its live transition.", nameof(entry)); + } + } + + /// The only construction capability; its production subtypes and call sites are closed. +#pragma warning disable CA1034 // Nesting permits private witness construction without SharedKernel friend assemblies. + public abstract class MintingSource +#pragma warning restore CA1034 + { + /// Confines subtyping to the dispatcher stores' own nested classes. + protected MintingSource() { } + + /// Reads the actual eight-column result of the successful fenced subscriber reset. + protected static OperatorRecoveryTransition FromReplayUpdate( + DbConnection connection, DbTransaction transaction, DbDataReader returnedRow, PlatformAdmission admission) + { + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + ArgumentNullException.ThrowIfNull(returnedRow); + ArgumentNullException.ThrowIfNull(admission); + return new OperatorRecoveryTransition(connection, transaction, returnedRow, admission, replay: true); + } + + /// Reads the actual seven-column result of the successful fenced producer reset. + protected static OperatorRecoveryTransition FromResetUpdate( + DbConnection connection, DbTransaction transaction, DbDataReader returnedRow, PlatformAdmission admission) + { + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + ArgumentNullException.ThrowIfNull(returnedRow); + ArgumentNullException.ThrowIfNull(admission); + return new OperatorRecoveryTransition(connection, transaction, returnedRow, admission, replay: false); + } + } + + private string ComposeMetadata() + { + var buffer = new ArrayBufferWriter(); + using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + writer.WritePropertyName("operator"); + writer.WriteRawValue(PlatformOperatorAttribution.From(_admission).ToOperatorJson()); + writer.WriteString("event_id", EventId); + if (SubscriptionId is not null) + { + writer.WriteString("subscription_id", SubscriptionId); + } + + var count = Kind == "replay" ? "replay_count" : "attempts"; + writer.WriteStartObject("fence"); + writer.WriteStartObject("before"); + writer.WriteNumber(count, BeforeCount); + writer.WriteString("dead_lettered_at", BeforeDeadLetteredAt.UtcDateTime.ToString("O", CultureInfo.InvariantCulture)); + writer.WriteString("terminal_reason", BeforeReason); + writer.WriteEndObject(); + writer.WriteStartObject("after"); + writer.WriteNumber(count, AfterCount); + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + return Encoding.UTF8.GetString(buffer.WrittenSpan); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/IDeliveryInspection.cs b/backend/src/LearnStack.SharedKernel/Platform/IDeliveryInspection.cs new file mode 100644 index 00000000..8eb05482 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IDeliveryInspection.cs @@ -0,0 +1,66 @@ +namespace LearnStack.SharedKernel.Platform; + +/// Which terminal state of a dead-lettered or pending row an inspection lists (ADR-0103 § 1). +public enum DeliveryInspectionState +{ + /// The row is dead-lettered: its terminal request committed, and a recovery may act on it. + DeadLettered = 1, + + /// A terminal request is recorded and its commit is not: the state is shown and is not actionable. + TerminalRequested, +} + +/// One page of an inspection, with the opaque cursor of the next page when there is one. +/// The row projection. +/// The rows of this page, at most the requested limit. +/// The cursor of the next page, or null on the last page. +public sealed record InspectionPage(IReadOnlyList Items, string? NextCursor); + +/// +/// An outbox row's metadata and the fence a producer reset needs: and +/// . The event type is the registry's label, never stored text, and no envelope column is read. +/// +public sealed record OutboxMessageInspection( + Guid EventId, Guid TenantId, Guid? OrganizationId, string EventType, DateTimeOffset OccurredAt, int Attempts, + string? LastError, DateTimeOffset AvailableAfter, DateTimeOffset? LockedUntil, string? TerminalReason, + DateTimeOffset? DeadLetteredAt, bool Actionable); + +/// +/// A subscriber delivery's metadata and the fence a replay needs: , +/// and . +/// +public sealed record EventDeliveryInspection( + Guid TenantId, string SubscriptionId, Guid EventId, Guid? OrganizationId, string EventType, DateTimeOffset OccurredAt, + int Attempts, string? LastError, DateTimeOffset AvailableAfter, DateTimeOffset? LockedUntil, string? TerminalReason, + DateTimeOffset? DeadLetteredAt, int ReplayCount, DateTimeOffset? ReplayedAt, bool Actionable); + +/// A quarantined job with its reservation occupancy. Nothing here can release or requeue it (ADR-0103 § 6). +public sealed record QuarantinedJobInspection( + Guid JobId, Guid TenantId, Guid? OrganizationId, string DefinitionKey, string Profile, string Queue, + string? CapacityGroup, DateTimeOffset CreatedAt, string Phase, int NormalAttempts, int FinalizeAttempts, + string? QuarantineReason, string? LastError, DateTimeOffset? OwnershipUntil, DateTimeOffset? ProbeAfter, + int UnsuccessfulProbes, string? FinalizationStatus, bool BusinessFinalizationIncomplete, int HeldReservations, + int GroupOccupancy); + +/// +/// The metadata-only operator inspection of asynchronous work (ADR-0103 § 1): each page runs in an entered platform +/// scope on the platform role's column grants, which the database enforces, so the entry row is its audit. +/// +/// +/// A malformed or foreign cursor answers null, which the route reports as a validation failure. The scope's own +/// refusals are thrown as the scope throws them. +/// +public interface IDeliveryInspection +{ + /// Lists outbox rows in , oldest first. + Task?> InspectOutboxAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default); + + /// Lists subscriber deliveries in , oldest first. + Task?> InspectDeliveriesAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default); + + /// Lists quarantined jobs with their reservation occupancy, oldest first. + Task?> InspectJobsAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs new file mode 100644 index 00000000..0d4c80bd --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs @@ -0,0 +1,77 @@ +namespace LearnStack.SharedKernel.Platform; + +/// +/// The fence an operator read at inspection and presents with a subscriber replay: the delivery's replay count, the +/// instant it was dead-lettered and its terminal reason (ADR-0103 § 2). +/// +/// The delivery's tenant. +/// The delivery's subscription. +/// The delivery's event. +/// The replay count the inspection showed. +/// The dead-letter instant the inspection showed, to the microsecond. +/// The terminal reason the inspection showed. +public sealed record DeliveryReplayRequest( + Guid TenantId, string SubscriptionId, Guid EventId, int ReplayCount, DateTimeOffset DeadLetteredAt, string TerminalReason); + +/// The fence an operator presents with a producer reset: the attempt count and the dead-letter instant (ADR-0103 § 3). +/// The outbox row's tenant. +/// The outbox row's identifier, which is the event's. +/// The attempt count the inspection showed. +/// The dead-letter instant the inspection showed, to the microsecond. +public sealed record OutboxResetRequest(Guid TenantId, Guid EventId, int Attempts, DateTimeOffset DeadLetteredAt); + +/// How an operator recovery ended. +public enum OperatorRecoveryOutcome +{ + /// The row was reset, and its result row committed with it. + Applied = 1, + + /// The row no longer shows the fence the operator presented: another act or the dispatcher moved it. + StaleFence, + + /// The fence holds but the state is not one a reset may act on; nothing changed. + NotRecoverable, + + /// No such row exists, or it is outside what an operator may reach. + NotFound, +} + +/// The end of one recovery and the count the row now carries when it was applied. +/// How it ended. +/// The fence's count after an applied reset: the new replay count, or zero attempts. +public sealed record OperatorRecoveryResult(OperatorRecoveryOutcome Outcome, int? CountAfter = null); + +/// +/// The recovery owner could not finish and nothing is known to be wrong with the request: the credential or the pool +/// is unavailable, the owner's one lane is busy, or the commit's outcome is unknown (ADR-0103 § 5). +/// +/// The message is fixed and carries no address, credential or row value. +public sealed class OperatorRecoveryUnavailableException : Exception +{ + /// Builds the refusal. + /// Whether the transition's COMMIT may have reached the database. + public OperatorRecoveryUnavailableException(bool commitOutcomeUnknown = false) + : base("The operator recovery owner is unavailable.") => CommitOutcomeUnknown = commitOutcomeUnknown; + + /// Whether the commit may have landed, so the operator inspects the row before repeating the request. + public bool CommitOutcomeUnknown { get; } +} + +/// +/// The confined owner of the two fenced recovery transitions (ADR-0103 § 2 to § 5): it consumes the operator's +/// admission and makes the change on the dispatcher's outbox-role credential, with a MUST row on the same transaction. +/// +public interface IOperatorRecovery +{ + /// Resets one dead-lettered subscriber delivery under its fence. + /// The owner could not finish. + /// The MUST row could not be written; nothing changed. + Task ReplayDeliveryAsync( + PlatformAdmission admission, DeliveryReplayRequest request, CancellationToken cancellationToken = default); + + /// Resets one dead-lettered producer row, whose terminal reason is retry exhaustion, under its fence. + /// The owner could not finish. + /// The MUST row could not be written; nothing changed. + Task ResetOutboxAsync( + PlatformAdmission admission, OutboxResetRequest request, CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index 7e7297e2..dfff9e11 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -2,6 +2,22 @@ namespace LearnStack.SharedKernel.Platform; +/// Where an operator act runs: the one place its effect is made, and so which owner may take its admission. +public enum PlatformOperationExecutor +{ + /// A pipeline act on the application role, run by the operator act executor (ADR-0102). + Pipeline = 1, + + /// A read or write in the platform scope, on the BYPASSRLS platform role (ADR-0101). + PlatformScope, + + /// The offline tool, on its own confined role (ADR-0104). + OfflineTool, + + /// The confined recovery owner, on the dispatcher's outbox role (ADR-0103). + RecoveryOwner, +} + /// One closed registry entry: what an operator act is, and what it needs. /// /// The reason is this entry's slug and never caller text, so the audit reason column @@ -11,7 +27,7 @@ namespace LearnStack.SharedKernel.Platform; public sealed record PlatformOperation { internal PlatformOperation( - string auditSlug, string reasonSlug, PermissionDefinition permission, bool needsPlatformRole, + string auditSlug, string reasonSlug, PermissionDefinition permission, PlatformOperationExecutor executor, string? attemptAuditSlug = null) { ArgumentException.ThrowIfNullOrWhiteSpace(auditSlug); @@ -30,7 +46,7 @@ internal PlatformOperation( AuditSlug = auditSlug; ReasonSlug = reasonSlug; Permission = permission; - NeedsPlatformRole = needsPlatformRole; + Executor = executor; AttemptAuditSlug = attemptAuditSlug; } @@ -49,8 +65,14 @@ internal PlatformOperation( /// The Platform permission an operator must hold, evaluated per act. public PermissionDefinition Permission { get; } + /// Where the act runs, which decides the one owner that may consume its admission. + public PlatformOperationExecutor Executor { get; } + /// Whether the act enters the platform scope (the BYPASSRLS role). - public bool NeedsPlatformRole { get; } + public bool NeedsPlatformRole => Executor == PlatformOperationExecutor.PlatformScope; + + /// Whether the operator act executor runs the act through the pipeline on the application role. + public bool RunsInPipeline => Executor == PlatformOperationExecutor.Pipeline; } /// The closed set of operator operations (ADR-0101 § 7). @@ -58,39 +80,64 @@ public static class PlatformOperations { /// Toggle a declared killswitch (ADR-0101 § 13). public static PlatformOperation KillswitchToggle { get; } = new( - "tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true); + "tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, + PlatformOperationExecutor.PlatformScope); /// Provision a Tenant and its default Organization (ADR-0102 § 2). public static PlatformOperation TenantProvision { get; } = new( - "tenancy.tenant.create", "tenant_provision", PlatformPermissions.TenantWrite, false); + "tenancy.tenant.create", "tenant_provision", PlatformPermissions.TenantWrite, PlatformOperationExecutor.Pipeline); /// Map a host to a Tenant (ADR-0102 § 2, § 4). public static PlatformOperation HostMap { get; } = new( - "tenancy.hostmapping.write", "host_map", PlatformPermissions.TenantWrite, false); + "tenancy.hostmapping.write", "host_map", PlatformPermissions.TenantWrite, PlatformOperationExecutor.Pipeline); /// Create one finite Role template (ADR-0102 § 2). public static PlatformOperation RoleInitialize { get; } = new( - "identity.role.initialize", "role_initialize", PlatformPermissions.TenantBootstrapWrite, false); + "identity.role.initialize", "role_initialize", PlatformPermissions.TenantBootstrapWrite, + PlatformOperationExecutor.Pipeline); /// Create the first tenant-wide administrator Membership (ADR-0102 § 7). public static PlatformOperation FirstAdminCreate { get; } = new( - "identity.membership.create_first_admin", "first_admin_create", PlatformPermissions.TenantBootstrapWrite, false); + "identity.membership.create_first_admin", "first_admin_create", PlatformPermissions.TenantBootstrapWrite, + PlatformOperationExecutor.Pipeline); /// Create a replacement administrator for a Tenant that has none (ADR-0102 § 8). public static PlatformOperation AdminRecover { get; } = new( - "identity.membership.recover_admin", "admin_recover", PlatformPermissions.TenantBootstrapWrite, false); + "identity.membership.recover_admin", "admin_recover", PlatformPermissions.TenantBootstrapWrite, + PlatformOperationExecutor.Pipeline); /// /// Rebind the identity authority's issuer from the offline tool, which neither enters the platform scope nor /// runs through the pipeline and writes an intent row and a result row of its own role (ADR-0104 § 8). /// public static PlatformOperation IdentityAuthorityRebind { get; } = new( - "identity.authority.rebind", "issuer_rebind", PlatformPermissions.IdentityAuthorityAdmin, false, - attemptAuditSlug: "identity.authority.rebind_attempt"); + "identity.authority.rebind", "issuer_rebind", PlatformPermissions.IdentityAuthorityAdmin, + PlatformOperationExecutor.OfflineTool, attemptAuditSlug: "identity.authority.rebind_attempt"); + + /// + /// Inspect dead-lettered and pending-terminal deliveries and quarantined jobs: metadata only, in the platform + /// scope on column grants, audited by the scope's entry row (ADR-0103 § 1). + /// + public static PlatformOperation DeliveryInspect { get; } = new( + "platform.delivery.inspect", "delivery_inspect", PlatformPermissions.DeliveryRead, + PlatformOperationExecutor.PlatformScope); + + /// Reset one dead-lettered subscriber delivery under the fence read at inspection (ADR-0103 § 2). + public static PlatformOperation DeliveryReplay { get; } = new( + "platform.delivery.replay", "delivery_replay", PlatformPermissions.DeliveryWrite, + PlatformOperationExecutor.RecoveryOwner); + + /// Reset one dead-lettered producer row whose reason is retry exhaustion (ADR-0103 § 3). + public static PlatformOperation DeliveryReset { get; } = new( + "platform.delivery.reset", "delivery_reset", PlatformPermissions.DeliveryWrite, + PlatformOperationExecutor.RecoveryOwner); /// Every registered operation. public static IReadOnlyList All { get; } = - [KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover, IdentityAuthorityRebind]; + [ + KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover, + IdentityAuthorityRebind, DeliveryInspect, DeliveryReplay, DeliveryReset, + ]; /// Whether is one of the registered instances. public static bool IsRegistered(PlatformOperation? operation) => diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs index 5b704e6d..6174fc6d 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -36,9 +36,17 @@ public static class PlatformPermissions public static PermissionDefinition IdentityAuthorityAdmin { get; } = new(PermissionScope.Platform, "platform.identity_authority.admin"); + /// Inspect the metadata of dead-lettered deliveries and quarantined jobs (ADR-0103). + public static PermissionDefinition DeliveryRead { get; } = + new(PermissionScope.Platform, "platform.delivery.read"); + + /// Replay one dead-lettered subscriber delivery and reset one dead-lettered producer row (ADR-0103). + public static PermissionDefinition DeliveryWrite { get; } = + new(PermissionScope.Platform, "platform.delivery.write"); + /// Every registered Platform permission. public static IReadOnlyList All { get; } = - [KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin]; + [KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin, DeliveryRead, DeliveryWrite]; /// Finds a registered Platform permission by its key. public static bool TryGet(string? key, out PermissionDefinition definition) diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 6c83f9f5..9efea395 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -130,6 +130,15 @@ public void Describe(IAuditCatalogBuilder builder) "platform.delivery.dead_letter", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.job.dead_letter", OperationType.SecurityEvent, OperationClass.Must) + // The three operator recovery operations of ADR-0103: an inspection is audited by the platform scope's + // entry row, which names this slug as its operation, and the two transitions write their own MUST row + // on the outbox-role transaction that makes the change. + .DeclareOffPath( + "platform.delivery.inspect", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.delivery.replay", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.delivery.reset", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "tenancy.tenant_assertion.reject", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index b3ecca7a..0fe5ee4d 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -516,7 +516,7 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0101 and ADR-0104 authorize thirteen writes and no update; + // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0101, ADR-0103 and ADR-0104 authorize fourteen writes and no update; // another method would make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) @@ -525,7 +525,7 @@ public void IAuditStore_Exposes_No_Update_Method() "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync", "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync", - "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync"); + "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync", "WriteOperatorRecoveryAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs index 0af20f60..2289f69a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs @@ -32,11 +32,25 @@ public sealed partial class OutboxDispatchConventionTests + "::CreateRuntime(System.IServiceProvider)"; private static string RuntimePreallocateId => InfrastructureAssembly + ":System.Void " + JobRuntime + "::PreallocateOwners(Hangfire.PostgreSql.PostgreSqlStorage)"; - private static IEnumerable MessagingStoreConsumerIds(string store) => - [ - BoundaryApi + ":System.Void " + MessagingLifetime + "::.ctor(" + store + ")", - BoundaryApi + ":System.Threading.Tasks.Task " + MessagingLifetime + "::ObserveExecutionAsync(System.Threading.Tasks.Task)", - ]; + private static IEnumerable MessagingStoreConsumerIds(string store) + { + // ADR-0103: the operator recovery owner is the one DI consumer of each store beside the processors, and it + // reaches only the store's own operator lane. + const string Result = "System.Threading.Tasks.Task`1 "; + return + [ + BoundaryApi + ":System.Void " + MessagingLifetime + "::.ctor(" + store + ")", + BoundaryApi + ":System.Threading.Tasks.Task " + MessagingLifetime + "::ObserveExecutionAsync(System.Threading.Tasks.Task)", + InfrastructureAssembly + ":System.Void " + OperatorRecoveryOwner + "::.ctor(" + DeliveryStore + "," + Store + ")", + InfrastructureAssembly + ":" + Result + OperatorRecoveryOwner + (store == DeliveryStore + ? "::ReplayDeliveryAsync(LearnStack.SharedKernel.Platform.PlatformAdmission," + + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest,System.Threading.CancellationToken)" + : "::ResetOutboxAsync(LearnStack.SharedKernel.Platform.PlatformAdmission," + + "LearnStack.SharedKernel.Platform.OutboxResetRequest,System.Threading.CancellationToken)"), + ]; + } + + private const string OperatorRecoveryOwner = "LearnStack.Infrastructure.Messaging.OperatorRecovery"; private static bool IsDeclaredOwner(string owner, TypeDefinition type) => type.Methods.Any(method => MethodId(method) == owner); diff --git a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs index e0b684b7..8c8b4650 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs @@ -185,7 +185,7 @@ public void Delivery_SQL_census_rejects_quoted_CTE_helper_overload_missing_and_p "TRUNCATE another_table, event_deliveries", "MERGE INTO event_deliveries USING x ON true WHEN MATCHED THEN DELETE" }) AssertMutation(census, "an unauthorized subscriber SQL writer", () => AddSqlProbe(module, sql), DeliverySqlOffenders); var store = census.Types[(InfrastructureAssembly, DeliveryStore)]; - foreach (var name in new[] { "ReplayAsync", "UnrelatedSqlHelper" }) + foreach (var name in new[] { "ReplayCoreAsync", "UnrelatedSqlHelper" }) AssertMutation(census, "an extra SQL helper or overload", () => { var method = AddSqlMethod(store, name, "UPDATE event_deliveries SET attempts=0"); @@ -297,7 +297,8 @@ private static SortedSet DeliverySqlOffenders(ProductionCensus census) ("LearnStack.Infrastructure.Messaging.PostgresInboxGuard", "TryClaimAsync"), (DeliveryCompletionType, "FenceAsync"), (DeliveryStore, "AcquireAsync"), (DeliveryStore, "UpdateAsync"), - (DeliveryStore, "TryTerminalizeAsync"), (DeliveryStore, "ReplayAsync"), + // ADR-0103: the operator's fenced replay is the second writer of subscriber status. + (DeliveryStore, "TryTerminalizeAsync"), (DeliveryStore, "ReplayCoreAsync"), }) { if (!types.TryGetValue((InfrastructureAssembly, typeName), out var type)) @@ -459,7 +460,13 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc var storeConstructor = RequireBoundaryMethod(offenders, store, ".ctor", "System.Void", MethodAttributes.Public, BoundaryGuardedSource, "LearnStack.Infrastructure.Messaging.OutboxEventRegistry", "LearnStack.Infrastructure.Messaging.DeliveryDispatchOptions", "LearnStack.SharedKernel.Identifiers.IGuidFactory", - "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory"); + "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory", + "LearnStack.SharedKernel.Jobs.BackgroundJobLifecycleProjection"); + // The public replay is the operator's entry and holds no connection; the core below it owns the one. + RequireBoundaryMethod(offenders, store, "ReplayAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Public, + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation); string[] storeAcquisitions = [ RequireBoundaryMethod(offenders, store, "AcquireAsync", "System.Threading.Tasks.Task`1<" + DeliveryClaimType + ">", MethodAttributes.Private, @@ -471,11 +478,14 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc RequireBoundaryMethod(offenders, store, "IsDurablyTerminalAsync", BoundaryBooleanTask, MethodAttributes.Private, DeliveryClaimType), RequireBoundaryMethod(offenders, store, "ReadSnapshotAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Public, BoundaryStrings, BoundaryCancellation), - RequireBoundaryMethod(offenders, store, "ReplayAsync", BoundaryBooleanTask, MethodAttributes.Public, - "System.Guid", "System.String", "System.Guid", BoundaryCancellation), + RequireBoundaryMethod(offenders, store, "ReplayCoreAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Private, + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", - "System.Threading.Tasks.ValueTask`1<" + DeliveryStore + "/OwnedConnection>", MethodAttributes.Private, BoundaryCancellation); + "System.Threading.Tasks.ValueTask`1<" + DeliveryStore + "/OwnedConnection>", MethodAttributes.Private, + BoundaryCancellation, "System.Boolean"); CheckSourceFieldAccess(offenders, census, store, storeConstructor, [storeReader]); CheckCleanupConnectionOwner(offenders, census, store, storeReader, storeAcquisitions); var expected = new[] @@ -500,7 +510,8 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc && !(stateMachines.Contains(Key(field.DeclaringType)) && field.Name == "<>4__this")).ToArray(); CheckSet(offenders, "privileged delivery store holders", fields.Select(field => TypeId(field.DeclaringType) + ":" + field.Name), [TypeId(worker) + ":_store", InfrastructureAssembly + ":" + DeliveryStore + "/OwnedConnection:P", - BoundaryApi + ":" + MessagingLifetime + ":_deliveryStore"]); + BoundaryApi + ":" + MessagingLifetime + ":_deliveryStore", + InfrastructureAssembly + ":" + OperatorRecoveryOwner + ":_deliveries"]); if (fields.Any(field => !field.IsPrivate || !field.IsInitOnly && !(field.DeclaringType.FullName == DeliveryStore + "/OwnedConnection" && field.Name == "P"))) offenders.Add("Delivery store holders must be private readonly or the exact construction-only cleanup capture"); diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index 351e5aef..212ff6ad 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -541,7 +541,10 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(InfrastructureAssembly, LifecycleInvitationSmtpOwner, "ExecuteSqlAsync", LifecycleInvitationSmtpSqlParameters), Owner(InfrastructureAssembly, Store, "AcquireAsync"), Owner(InfrastructureAssembly, Store, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "AcquireAsync"), Owner(InfrastructureAssembly, DeliveryStore, "UpdateAsync"), - Owner(InfrastructureAssembly, DeliveryStore, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "ReplayAsync"), + // ADR-0103: the operator's fenced replay and reset each own one short transaction of their own on the + // dispatcher role, never business completion. + Owner(InfrastructureAssembly, DeliveryStore, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "ReplayCoreAsync"), + Owner(InfrastructureAssembly, Store, "ResetCoreAsync"), // Routing publishes a claim only after this owned operation acknowledges COMMIT and joins cleanup. Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobRoutingStore", "TryClaimOwnedAsync"), // Bridge transport hints own short privileged transactions, never business completion. diff --git a/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs new file mode 100644 index 00000000..2d19848f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs @@ -0,0 +1,165 @@ +using FluentAssertions; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// ADR-0103: the operator recovery witness is minted only from the two stores' fenced resets and written once each. +public sealed partial class OutboxDispatchConventionTests +{ + private const string RecoveryWitness = "LearnStack.SharedKernel.Audit.OperatorRecoveryTransition"; + private const string RecoverySource = RecoveryWitness + "/MintingSource"; + private const string RecoveryReplayMint = "FromReplayUpdate"; + private const string RecoveryResetMint = "FromResetUpdate"; + private const string RecoveryWrite = "WriteOperatorRecoveryAsync"; + private const string RecoveryMintSubtype = "/RecoveryMint"; + private static readonly string[] RecoveryMintParameters = + [ + "System.Data.Common.DbConnection", "System.Data.Common.DbTransaction", + "System.Data.Common.DbDataReader", "LearnStack.SharedKernel.Platform.PlatformAdmission", + ]; + private static readonly string[] RecoveryWriteParameters = + [ + "LearnStack.SharedKernel.Audit.AuditEntryDraft", RecoveryWitness, + "System.Data.Common.DbConnection", "System.Data.Common.DbTransaction", + "System.Threading.CancellationToken", + ]; + + /// + /// ADR-0103 § 5: the second writer of dispatcher status mints its witness from the actual returned row of its + /// fenced UPDATE, and the audit port's recovery write has exactly the two dispatcher callers. PostgreSQL tests + /// separately prove that the live result and the draft agree. + /// + [Fact] + public void Operator_Recovery_Audit_Identity_Is_Row_Bound() + { + using var census = ProductionCensus.Read(); + RecoveryOffenders(census).Should().BeEmpty( + "Fix: keep the immutable private recovery witness, its two nested store minting subtypes and the " + + "recovery writer and its call sites closed; keep row and transaction identity checks in the witness"); + } + + [Fact] + public void Operator_recovery_census_detects_extra_derivers_constructors_and_callers() + { + using var census = ProductionCensus.Read(); + var source = census.Types[(KernelAssembly, RecoverySource)]; + var factory = source.Methods.Single(method => method.Name == RecoveryReplayMint); + var constructor = census.Types[(KernelAssembly, RecoveryWitness)].Methods.Single(method => method.IsConstructor && !method.IsStatic); + var port = census.Types[(KernelAssembly, AuditPort)]; + var write = port.Methods.Single(method => method.Name == RecoveryWrite); + var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); + + AssertMutation(census, "a second minting subtype in another production assembly", () => + { + var type = AddProbe(application, "AdditionalRecoveryMintingSource"); + type.BaseType = application.ImportReference(source); + return () => application.Types.Remove(type); + }, RecoveryOffenders); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) + { + AssertMutation(census, "a cross-assembly mint helper using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryMintCaller", factory, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a direct private witness constructor call", () => + AddCallProbe(application, "AdditionalRecoveryConstructor", constructor, OpCodes.Newobj), RecoveryOffenders); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt }) + { + AssertMutation(census, "an extra recovery writer caller using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryWriter", write, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a helper on the sanctioned store type", () => + { + var type = census.Types[(InfrastructureAssembly, Store)]; + var method = AddCall(type, "UnrelatedRecoveryHelper", factory, OpCodes.Call); + return () => type.Methods.Remove(method); + }, RecoveryOffenders); + } + + private static SortedSet RecoveryOffenders(ProductionCensus census) + { + var offenders = new SortedSet(StringComparer.Ordinal); + var types = census.Types; + foreach (var key in new[] { (KernelAssembly, RecoveryWitness), (KernelAssembly, RecoverySource), + (InfrastructureAssembly, Store), (InfrastructureAssembly, DeliveryStore), + (InfrastructureAssembly, Store + RecoveryMintSubtype), (InfrastructureAssembly, DeliveryStore + RecoveryMintSubtype), + (KernelAssembly, AuditPort), (AuditAssembly, AuditStore) }) + { + if (!types.ContainsKey(key)) offenders.Add("Missing production subject: " + key.Item2); + } + + if (offenders.Count != 0) return offenders; + + var witness = types[(KernelAssembly, RecoveryWitness)]; + var source = types[(KernelAssembly, RecoverySource)]; + var port = types[(KernelAssembly, AuditPort)]; + var auditStore = types[(AuditAssembly, AuditStore)]; + var subtypes = new[] { types[(InfrastructureAssembly, Store + RecoveryMintSubtype)], types[(InfrastructureAssembly, DeliveryStore + RecoveryMintSubtype)] }; + + var constructors = witness.Methods.Where(method => method.IsConstructor && !method.IsStatic).ToArray(); + if (!witness.IsSealed || witness.BaseType?.FullName != "System.Object") offenders.Add(RecoveryWitness + ": must be sealed with no custom base"); + if (constructors.Length != 1 || constructors.Any(method => !method.IsPrivate + || !ParametersMatch(method, [.. RecoveryMintParameters, "System.Boolean"]))) + offenders.Add(RecoveryWitness + ": requires exactly one private live-reader constructor"); + if (witness.Fields.All(field => field.IsStatic) || witness.Fields.Any(field => !field.IsStatic && !field.IsInitOnly)) + offenders.Add(RecoveryWitness + ": instance fields must be nonempty and readonly"); + if (witness.Properties.Count == 0 || witness.Properties.Any(property => property.SetMethod is not null)) + offenders.Add(RecoveryWitness + ": properties must be nonempty and getter-only"); + if (!source.IsNestedPublic || !source.IsAbstract || source.IsSealed) + offenders.Add(RecoverySource + ": requires the public abstract nested minting capability"); + if (source.Methods.Where(method => method.IsConstructor && !method.IsStatic).Any(method => !method.IsFamily)) + offenders.Add(RecoverySource + ": constructors must be protected"); + if (witness.Module.Assembly.CustomAttributes.Any(attribute => + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.InternalsVisibleToAttribute")) + offenders.Add(KernelAssembly + ": friend assemblies reopen restricted authority"); + + var factories = source.Methods.Where(method => method.Name is RecoveryReplayMint or RecoveryResetMint).ToArray(); + if (factories.Length != 2 || factories.Select(method => method.Name).Distinct(StringComparer.Ordinal).Count() != 2 + || factories.Any(method => !method.IsFamily || !method.IsStatic || method.ReturnType.FullName != RecoveryWitness + || !ParametersMatch(method, RecoveryMintParameters))) + offenders.Add(RecoverySource + ": requires the two protected static live-reader mint signatures"); + if (subtypes.Any(type => !type.IsNestedPrivate || !type.IsSealed)) + offenders.Add("The recovery minting subtypes must be private sealed nested classes of their stores"); + + CheckSet(offenders, "recovery minting subtypes", types.Values.Where(type => Derives(type, source, types)).Select(TypeId), + subtypes.Select(TypeId)); + CheckSet(offenders, "recovery witness-producing methods", types.Values.SelectMany(type => type.Methods) + .Where(method => method.ReturnType.FullName == RecoveryWitness).Select(MethodId), + factories.Select(MethodId).Concat(subtypes.SelectMany(type => type.Methods.Where(method => method.Name is "Replay" or "Reset") + .Select(MethodId)))); + + var writers = types.Values.Where(type => !type.IsInterface && !type.IsAbstract && Derives(type, port, types)).ToArray(); + CheckSet(offenders, "audit store implementations", writers.Select(TypeId), [TypeId(auditStore)]); + var declarations = types.Values.Where(type => SameType(type, port) || Derives(type, port, types)) + .SelectMany(type => type.Methods).Where(method => method.Name == RecoveryWrite).ToArray(); + CheckSet(offenders, "recovery audit declarations", declarations.Select(method => TypeId(method.DeclaringType) + "." + method.Name), + [TypeId(port) + "." + RecoveryWrite, TypeId(auditStore) + "." + RecoveryWrite]); + foreach (var method in declarations.Where(method => method.ReturnType.FullName != "System.Threading.Tasks.Task" + || !ParametersMatch(method, RecoveryWriteParameters))) + offenders.Add(MethodId(method) + ": wrong recovery write signature"); + + var sites = CallSites(census).ToArray(); + CheckSet(offenders, "recovery witness constructor call sites", sites.Where(site => site.Target.Name == ".ctor" + && SameType(site.Target.DeclaringType, witness)).Select(site => site.Owner), factories.Select(MethodId)); + foreach (var (mint, wrapper, store) in new[] { (RecoveryReplayMint, "Replay", DeliveryStore), (RecoveryResetMint, "Reset", Store) }) + { + var subtype = types[(InfrastructureAssembly, store + RecoveryMintSubtype)]; + CheckSet(offenders, mint + " call sites", sites.Where(site => site.Target.Name == mint + && (SameType(site.Target.DeclaringType, source) || Derives(site.Target.DeclaringType, source, types))) + .Select(site => site.Owner), subtype.Methods.Where(method => method.Name == wrapper).Select(MethodId)); + var core = types[(InfrastructureAssembly, store)].Methods.Where(method => method.Name is "ReplayCoreAsync" or "ResetCoreAsync").ToArray(); + CheckSet(offenders, wrapper + " wrapper call sites", sites.Where(site => site.Target.Name == wrapper + && SameType(site.Target.DeclaringType, subtype)).Select(site => site.Owner), core.Select(MethodId)); + } + + var recoveryRows = types[(InfrastructureAssembly, Store)].Methods.Concat(types[(InfrastructureAssembly, DeliveryStore)].Methods) + .Where(method => method.Name == "WriteRecoveryRowAsync").ToArray(); + CheckSet(offenders, "recovery audit call sites", sites.Where(site => site.Target.Name == RecoveryWrite + && (SameType(site.Target.DeclaringType, port) || Derives(site.Target.DeclaringType, port, types))) + .Select(site => site.Owner), recoveryRows.Select(MethodId)); + return offenders; + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs index 350fdfb3..9bd65ca5 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs @@ -658,7 +658,13 @@ private static SortedSet CredentialOffenders(ProductionCensus census) var storeConstructor = RequireBoundaryMethod(offenders, store, ".ctor", "System.Void", MethodAttributes.Public, BoundaryGuardedSource, "LearnStack.Infrastructure.Messaging.OutboxEventRegistry", "LearnStack.Infrastructure.Messaging.OutboxDispatchOptions", "LearnStack.SharedKernel.Identifiers.IGuidFactory", - "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory"); + "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory", + "LearnStack.SharedKernel.Jobs.BackgroundJobLifecycleProjection"); + // The public reset is the operator's entry and holds no connection; the core below it owns the one. + RequireBoundaryMethod(offenders, store, "ResetAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Public, + "LearnStack.SharedKernel.Platform.OutboxResetRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation); string[] storeAcquisitions = [ RequireBoundaryMethod(offenders, store, "AcquireAsync", "System.Threading.Tasks.Task`1<" + BoundaryClaim + ">", MethodAttributes.Private, @@ -670,9 +676,14 @@ private static SortedSet CredentialOffenders(ProductionCensus census) RequireBoundaryMethod(offenders, store, "IsDurablyTerminalAsync", BoundaryBooleanTask, MethodAttributes.Private, "System.Guid"), RequireBoundaryMethod(offenders, store, "ReadSnapshotAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Public, BoundaryStrings, BoundaryCancellation), + RequireBoundaryMethod(offenders, store, "ResetCoreAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Private, + "LearnStack.SharedKernel.Platform.OutboxResetRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", - "System.Threading.Tasks.ValueTask`1<" + Store + "/OwnedConnection>", MethodAttributes.Private, BoundaryCancellation); + "System.Threading.Tasks.ValueTask`1<" + Store + "/OwnedConnection>", MethodAttributes.Private, + BoundaryCancellation, "System.Boolean"); CheckSourceFieldAccess(offenders, census, store, storeConstructor, [storeReader]); CheckCleanupConnectionOwner(offenders, census, store, storeReader, storeAcquisitions); if (storeFactory is not null) CheckStoreConsumers(offenders, census, outboxRoot, storeFactory); @@ -719,7 +730,8 @@ private static void CheckStoreConsumers(SortedSet offenders, ProductionC && field.FieldType.FullName == Store)).ToArray(); CheckSet(offenders, "privileged store fields", fields.Select(field => TypeId(field.DeclaringType) + ":" + field.Name), [TypeId(worker) + ":_store", InfrastructureAssembly + ":" + Store + "/OwnedConnection:P", - BoundaryApi + ":" + MessagingLifetime + ":_outboxStore"]); + BoundaryApi + ":" + MessagingLifetime + ":_outboxStore", + InfrastructureAssembly + ":" + OperatorRecoveryOwner + ":_outbox"]); foreach (var field in fields) if (!field.IsPrivate || !field.IsInitOnly && !(field.DeclaringType.FullName == Store + "/OwnedConnection" && field.Name == "P")) offenders.Add(field.FullName + ": store capability must remain private and readonly or the exact construction-only cleanup capture"); diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs index ae2c13b2..79400494 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs @@ -372,6 +372,8 @@ private static SortedSet OutboxSqlOffenders(ProductionCensus census) { ("LearnStack.Infrastructure.Messaging.PostgresOutbox", "EnqueueAsync"), (Store, "AcquireAsync"), (Store, "UpdateAsync"), (Store, "TryTerminalizeAsync"), + // ADR-0103: the operator's fenced producer reset is the second writer of dispatcher status. + (Store, "ResetCoreAsync"), ("LearnStack.Infrastructure.Persistence.Migrations.add_outbox_dispatch_state", "Up"), }) { diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 6efbe692..32d0dbe0 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -262,6 +262,7 @@ public void Only_The_Operator_Services_Hold_The_Platform_Scope() ScopeFile, CompositionFile, KillswitchWriterFile, + DeliveryInspectionFile, ], "each new operator service is added here deliberately, with its denied proof"); } @@ -283,9 +284,38 @@ public void Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act() "each new caller of an operator act is added here deliberately, with its denied proof"); } + [Fact] + public void Only_The_Recovery_Routes_And_Their_Owners_Name_The_Operator_Recovery_And_Inspection_Ports() + { + // ADR-0103: the two fenced transitions and the inspection are reachable from the recovery routes alone. The + // files that name a port are the port, its one implementation, the registration beside the source it enters and + // the routes, and nothing else: a second caller is a second route to a reset, added here with its denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "IOperatorRecovery", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IOperatorRecovery.cs", + "LearnStack.Infrastructure/Messaging/OperatorRecovery.cs", + "LearnStack.Api/Composition/OutboxCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs", + ], + "each new caller of a recovery transition is added here deliberately, with its denied proof"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IDeliveryInspection", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IDeliveryInspection.cs", + DeliveryInspectionFile, + "LearnStack.Api/Composition/PersistenceCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs", + ], + "each new caller of the inspection is added here deliberately, with its denied proof"); + } + private const string KillswitchWriterFile = "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; + private const string DeliveryInspectionFile = + "LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs"; + [Fact] public void Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer() { diff --git a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs index 35c2ac4d..acf57053 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs @@ -52,8 +52,11 @@ private static void CheckCleanupConnectionOwner(SortedSet offenders, Pro RequireBoundaryMethod(offenders, owner, "RecordCommitFailure", "System.Void", MethodAttributes.Assembly, "System.Exception"); RequireBoundaryMethod(offenders, owner, "ConfirmCommitOutcome", "System.Void", MethodAttributes.Assembly); var terminal = callers.Single(caller => caller.Contains("::TryTerminalizeAsync(", StringComparison.Ordinal)); + // ADR-0103: the operator's reset or replay core records its own uncertain COMMIT once. + var recovery = callers.Single(caller => caller.Contains("::ReplayCoreAsync(", StringComparison.Ordinal) + || caller.Contains("::ResetCoreAsync(", StringComparison.Ordinal)); CheckCallers(owner, "get_Slot", [release, release, retain]); - CheckCallers(owner, "RecordCommitFailure", [terminal, terminal]); + CheckCallers(owner, "RecordCommitFailure", [terminal, terminal, recovery]); CheckCallers(owner, "ConfirmCommitOutcome", [terminal]); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs index 60c4bb24..187d3121 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs @@ -13,8 +13,19 @@ internal static class BackgroundJobGrantExpectations _ => "DELETE,SELECT", }))); + /// The metadata of a job an operator may inspect: no parameter, plan, trace, causal or capability column. + public const string PlatformJobMetadataColumns = + "id tenant_id organization_id definition_key profile queue capacity_group original_due_at created_at phase " + + "normal_attempts finalize_attempts available_after ownership_kind ownership_until attempt_deadline probe_after " + + "unsuccessful_probes last_error quarantine_reason terminal_reason processed_at dead_lettered_at " + + "finalization_status finalization_reason business_finalization_incomplete wake_generation"; + public static string[] Columns(string role, string table, string privilege, IEnumerable allColumns) { + // ADR-0103: the platform role reads every reservation column, and nothing else of the job tables is exposed to it + // beyond the named metadata of background_jobs below. + if (privilege == "SELECT" && role == "learnstack_platform" && table == "background_job_reservations") + return allColumns.ToArray(); if (privilege == "SELECT" && (role == "learnstack_app" && SchemaTableClasses.JobTenant.Contains(table) || role == "learnstack_outbox_admin" && table is "background_job_capacity" or "background_job_reservations" @@ -26,6 +37,7 @@ public static string[] Columns(string role, string table, string privilege, IEnu "id tenant_id organization_id definition_key profile queue capacity_group parameters original_due_at traceparent causal_actor_user_id causation_event_id parent_job_id recipient_id", ("learnstack_app", "background_jobs", "UPDATE") => "phase normal_attempts finalize_attempts current_attempt_id attempt_deadline plan plan_fingerprint prepared_at operation_id final_outcome_attempt_id finalization_status finalization_reason processed_at terminal_reason dead_lettered_at", + ("learnstack_platform", "background_jobs", "SELECT") => PlatformJobMetadataColumns, ("learnstack_app", "background_job_attempts", "INSERT") => "id tenant_id organization_id job_id stage ordinal admission_token deadline final_outcome_attempt_id", ("learnstack_app", "background_job_attempts", "UPDATE") => diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs index 1f64104e..48475f33 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs @@ -25,8 +25,8 @@ public sealed partial class BackgroundJobRuntimeFacadeTests(SchemaFixture schema private static BackgroundJobRuntimeFixture Fixture => BackgroundJobRuntimeFixture.Shared; [Theory] - [InlineData(false, 3, 4, 1, 16, 52)] - [InlineData(true, 8, 32, 6, 64, 158)] + [InlineData(false, 3, 4, 1, 16, 54)] + [InlineData(true, 8, 32, 6, 64, 160)] public async Task Direct_real_composition_uses_one_pool_manifest_and_joins_all_owners_before_source_disposal( bool maximum, int pools, int workers, int controls, int invocations, int connections) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs index 141eb7ca..23efe2fb 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs @@ -7,7 +7,10 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Messaging; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Time; +using LearnStack.Modules.Tenancy.Infrastructure.Jobs; +using LearnStack.Tests.Fixtures; using LearnStack.Tools.Seeder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; @@ -256,7 +259,7 @@ public async Task Completed_sixth_attempt_with_inert_lease_is_excluded_from_reco (await store.TryClaimAsync(NoBlocked)).Should().BeNull(); (await store.TryClaimTerminalAsync(NoBlocked)).Should().BeNull(); (await store.FailAsync(claim, DeliveryFailureReason.UnknownOutcome)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeFalse(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().NotBe(OperatorRecoveryOutcome.Applied); (await test.InboxCountAsync()).Should().Be(1); } @@ -429,14 +432,15 @@ public async Task Replay_resets_only_exact_active_terminal_tuple_and_keeps_compl var id = await test.InsertAsync(); await test.InsertAsync(id, Second); var store = test.Store(); - var terminal = await TestDatabase.RequestTerminalAsync(store); + var terminal = await TestDatabase.RequestTerminalAsync(store, DeliveryTerminalReason.RetryExhausted); // Mark only sibling completed through the actual app completion grant. await test.CompleteAsync(id, Second, inbox: true); var sibling = await test.ReadAsync(id, Second); (await store.TryTerminalizeAsync(terminal, AttemptTrace)).Should().BeTrue(); - (await store.ReplayAsync(SchemaFixture.TenantB, First, id)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, Second, id)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeTrue(); + (await ReplayAsync(store, test, SchemaFixture.TenantB, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + (await ReplayAsync(store, test, SchemaFixture.TenantA, Second, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence, + "the sibling completed, so it shows no dead-letter instant for a fence to match"); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); var reset = await test.ReadAsync(id); reset.Attempts.Should().Be(0); reset.Error.Should().BeNull(); @@ -452,7 +456,7 @@ public async Task Replay_resets_only_exact_active_terminal_tuple_and_keeps_compl fresh.SubscriptionId.Should().Be(First); fresh.Token.Should().NotBe(terminal.Token); fresh.Attempts.Should().Be(1); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeFalse(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); } [Fact] @@ -466,7 +470,7 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c var store = test.Store(); for (var index = 0; index < 4; index++) { - var terminal = await TestDatabase.RequestTerminalAsync(store); + var terminal = await TestDatabase.RequestTerminalAsync(store, DeliveryTerminalReason.RetryExhausted); (await store.TryTerminalizeAsync(terminal, AttemptTrace)).Should().BeTrue(); } (await store.TryClaimAsync(NoBlocked)).Should().BeNull(); @@ -477,7 +481,7 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c foreach (var row in new[] { target, sibling, foreign, unrelated }) row.DeadLettered.Should().NotBeNull("every control must itself satisfy the terminal replay state predicate"); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeTrue(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); var reset = await test.ReadAsync(id); reset.Attempts.Should().Be(0); @@ -493,28 +497,265 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c (await test.ReadAsync(unrelatedId)).Should().Be(unrelated); } + private static PlatformAdmission ReplayAdmission(DateTimeOffset? issuedAt = null, PlatformOperation? operation = null) => + TestPlatformAdmissions.Admission( + operation ?? PlatformOperations.DeliveryReplay, null, + correlationId: "00-recovery-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt ?? Occurred); + + /// A replay under the fence the row shows now, as an operator would present what inspection returned. + private static async Task ReplayAsync( + DeliveryDispatchStore store, TestDatabase test, Guid tenant, string subscription, Guid id, + Func? change = null, PlatformAdmission? admission = null) + { + var row = await test.TryReadAsync(id, subscription, tenant); + var request = new DeliveryReplayRequest( + tenant, subscription, id, row?.ReplayCount ?? 0, row?.DeadLettered ?? DateTimeOffset.UnixEpoch, + row?.TerminalReason ?? "retry_exhausted"); + return await store.ReplayAsync(change?.Invoke(request) ?? request, admission ?? ReplayAdmission()); + } + + private const string DeadLetter = "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"; + [Theory] - [InlineData("pending")] - [InlineData("privileged")] - [InlineData("unknown")] - [InlineData("retired")] - [InlineData("requested")] - [InlineData("live")] - public async Task Replay_refuses_nonadmitted_or_unfinished_state(string state) + [InlineData("pending", "retry_exhausted")] + [InlineData("privileged", "retry_exhausted")] + [InlineData("unknown", "unknown_type")] + [InlineData("retired", "retired_type")] + [InlineData("active", "invalid_envelope")] + public async Task Replay_refuses_a_matching_fence_on_a_state_a_reset_may_not_act_on(string state, string reason) { await using var test = await TestDatabase.CreateAsync(schema.Postgres); var subscription = state == "pending" ? Pending : state == "privileged" ? Privileged : First; var type = state is "unknown" or "retired" ? state : TypeIdentity; var id = await test.InsertAsync(subscription: subscription, type: type); - await test.UpdateAsync(id, subscription, state switch - { - "live" => "locked_by = '11111111-1111-4111-8111-111111111111', locked_until = clock_timestamp() + interval '1 hour'", - "requested" => "terminal_reason = 'invalid_envelope'", - _ => "terminal_reason = 'invalid_envelope', dead_lettered_at = clock_timestamp()", - }); + await test.UpdateAsync(id, subscription, $"terminal_reason = '{reason}', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); var before = await test.ReadAsync(id, subscription); - (await test.Store().ReplayAsync(SchemaFixture.TenantA, subscription, id)).Should().BeFalse(); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, subscription, id); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable, state); (await test.ReadAsync(id, subscription)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty("a refusal writes no row"); + } + + [Theory] + [InlineData("live")] + [InlineData("requested")] + public async Task Replay_treats_a_row_that_is_not_dead_lettered_as_a_stale_fence(string state) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, state == "live" + ? "locked_by = '11111111-1111-4111-8111-111111111111', locked_until = clock_timestamp() + interval '1 hour'" + : "terminal_reason = 'retry_exhausted'"); + var before = await test.ReadAsync(id); + + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + + [Fact] + public async Task Replay_under_the_current_fence_resets_the_row_writes_one_operator_row_and_returns_it_to_the_dispatcher() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.UpdateAsync(id, First, DeadLetter); + var store = test.Store(); + var admission = ReplayAdmission(); + + var result = await ReplayAsync(store, test, SchemaFixture.TenantA, First, id, admission: admission); + + result.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 1)); + var row = await test.ReadAsync(id); + (row.Attempts, row.TerminalReason, row.DeadLettered, row.Error, row.Token, row.ReplayCount).Should().Be((0, null, null, null, null, 1)); + var audit = (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle().Which; + audit.Tenant.Should().Be(SchemaFixture.TenantA); + audit.Organization.Should().Be(SchemaFixture.OrgA1); + audit.ActorIsNull.Should().BeTrue("an operator is not a user"); + audit.Reason.Should().Be("delivery_replay"); + audit.Class.Should().Be("Must"); + audit.Type.Should().Be("SecurityEvent"); + audit.Correlation.Should().Be(admission.Operator.CorrelationId); + var metadata = JsonNode.Parse(audit.Metadata)!.AsObject(); + metadata.Select(pair => pair.Key).Should().BeEquivalentTo(["operator", "event_id", "subscription_id", "fence"]); + metadata["operator"]!.AsObject().ContainsKey("ticket").Should().BeFalse("a tenant can read this row, and the ticket never rides on one"); + metadata["event_id"]!.GetValue().Should().Be(id); + metadata["subscription_id"]!.GetValue().Should().Be(First); + metadata["fence"]!["before"]!["replay_count"]!.GetValue().Should().Be(0); + metadata["fence"]!["before"]!["dead_lettered_at"]!.GetValue().Should().Be("2026-10-01T12:00:00.1234560Z"); + metadata["fence"]!["before"]!["terminal_reason"]!.GetValue().Should().Be("retry_exhausted"); + metadata["fence"]!["after"]!["replay_count"]!.GetValue().Should().Be(1); + var fresh = (await store.TryClaimAsync(NoBlocked))!; + fresh.EventId.Should().Be(id); + fresh.Attempts.Should().Be(1, "the dispatcher claims the reset row once, with a renewed budget"); + } + + [Theory] + [InlineData("count")] + [InlineData("reason")] + [InlineData("instant-after-one-microsecond")] + [InlineData("instant-before-one-microsecond")] + [InlineData("instant-whole-millisecond")] + public async Task Replay_with_any_part_of_the_fence_changed_is_stale_and_changes_nothing(string change) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, request => change switch + { + "count" => request with { ReplayCount = request.ReplayCount + 1 }, + "reason" => request with { TerminalReason = "unknown_type" }, + "instant-after-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(10) }, + "instant-before-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-10) }, + _ => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-1234560 + 1230000) }, + }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence, "the fence is the instant to the microsecond, not to a coarser unit"); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + + [Fact] + public async Task Replay_of_a_delivery_whose_tenant_is_not_serving_is_not_recoverable() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + + (await test.ReadAsync(id)).Should().Be(before); + await test.SetTenantStatusAsync("Active"); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task A_failed_operator_audit_write_rolls_the_replay_back_and_the_spent_admission_cannot_retry() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + var admission = ReplayAdmission(); + await test.AuditGrantAsync(false); + + var attempt = () => ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, admission: admission); + + await attempt.Should().ThrowAsync(); + (await test.ReadAsync(id)).Should().Be(before, "the MUST row and the reset commit together or not at all"); + await test.AuditGrantAsync(true); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + var again = () => ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, admission: admission); + await again.Should().ThrowAsync("an admission is spent when it is used"); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task Replay_refuses_an_admission_for_another_operation_or_a_stale_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + var store = test.Store(); + + foreach (var admission in new[] + { + ReplayAdmission(operation: PlatformOperations.DeliveryReset), + ReplayAdmission(operation: PlatformOperations.IdentityAuthorityRebind), + ReplayAdmission(issuedAt: Occurred.AddSeconds(-31)), + }) + { + var act = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, id, admission: admission); + await act.Should().ThrowAsync(); + } + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task The_operator_lane_is_its_own_slot_so_a_busy_operator_never_costs_the_dispatcher_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var first = await test.InsertAsync(); + var second = await test.InsertAsync(); + await test.UpdateAsync(first, First, DeadLetter); + await test.UpdateAsync(second, First, DeadLetter); + var store = test.Store(); + + // Hold the first row's lock, so the first replay waits inside the operator lane. + await using var holder = await test.Dispatch.OpenConnectionAsync(); + await using var holding = await holder.BeginTransactionAsync(); + await using (var hold = new NpgsqlCommand( + "SELECT 1 FROM event_deliveries WHERE tenant_id = @tenant AND subscription_id = @subscription AND event_id = @event FOR UPDATE", + holder, holding)) + { + hold.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + hold.Parameters.AddWithValue("subscription", First); + hold.Parameters.AddWithValue("event", first); + await hold.ExecuteScalarAsync(); + } + + var waiting = ReplayAsync(store, test, SchemaFixture.TenantA, First, first); + await test.WaitForLockWaitAsync(); + + var busy = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, second); + await busy.Should().ThrowAsync("one operator call at a time per store"); + (await store.ReadSnapshotAsync(NoBlocked)).Should().NotBeNull("the dispatcher's own slots are untouched"); + + await holding.CommitAsync(); + (await waiting).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, second)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the lane is free again once the first call ends"); + } + + [Fact] + public async Task A_replay_whose_commit_acknowledgement_is_lost_is_unknown_and_a_repeat_is_a_stale_fence() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var fence = await test.ReadAsync(id); + await using var proxy = new CommitResponseDroppingProxy(test.OutboxConnectionString, rejectReconciliationConnections: false); + await using var source = OutboxDispatcherDataSource.Build(proxy.ConnectionString); + + var attempt = () => ReplayAsync(test.Store(source: source), test, SchemaFixture.TenantA, First, id); + + (await attempt.Should().ThrowAsync()).Which.CommitOutcomeUnknown.Should().BeTrue(); + proxy.DroppedCommitResponses.Should().Be(1); + (await test.ReadAsync(id)).ReplayCount.Should().Be(1, "the commit landed although its answer did not"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle(); + var repeat = await test.Store().ReplayAsync( + new DeliveryReplayRequest(SchemaFixture.TenantA, First, id, fence.ReplayCount, fence.DeadLettered!.Value, "retry_exhausted"), + ReplayAdmission()); + repeat.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + } + + [Fact] + public async Task Replay_leaves_every_other_row_inbox_and_the_producer_byte_identical() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.InsertAsync(id, Second); + var other = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + await test.UpdateAsync(id, Second, DeadLetter); + await test.UpdateAsync(other, First, DeadLetter); + var sibling = await test.ReadAsync(id, Second); + var unrelated = await test.ReadAsync(other); + var inbox = await test.InboxCountAsync(); + + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + + (await test.ReadAsync(id, Second)).Should().Be(sibling, "another subscription of the same event is its own row"); + (await test.ReadAsync(other)).Should().Be(unrelated, "another event is another row"); + (await test.InboxCountAsync()).Should().Be(inbox, "inbox identity is never reset"); } [Theory] @@ -572,6 +813,8 @@ public sealed class PrivilegedHandler : IIntegrationEventHandler private sealed record Row(int Attempts, string? Token, DateTimeOffset? LockedUntil, DateTimeOffset Available, DateTimeOffset? Processed, string? TerminalReason, DateTimeOffset? DeadLettered, string? Error, int ReplayCount, DateTimeOffset? Replayed); + private sealed record OperatorAuditRow(Guid Tenant, Guid? Organization, bool ActorIsNull, string Operation, + string? Reason, string Correlation, string Metadata, string Class, string Type); private sealed record AuditRow(Guid Tenant, Guid? Organization, Guid Actor, string Operation, string Type, string Class, string Correlation, string Metadata); @@ -605,6 +848,7 @@ INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row VALUES (@tenant, 'delivery-store', 'Delivery store', 'Trial', now(), @actor, 0); INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) VALUES (@organization, @tenant, 'hq', 'HQ', 'Active', now(), @actor, 0); + UPDATE tenants SET default_organization_id = @organization WHERE id = @tenant; """, ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), ("actor", UserId.SystemActor.Value)); await transaction.CommitAsync(); return test; @@ -616,7 +860,8 @@ public DeliveryDispatchStore Store(NpgsqlDataSource? source = null, Func source ?? Dispatch), Registry(), new DeliveryDispatchOptions(), new SystemGuidFactory(), new FixedClock(Occurred), decorate is null ? _provider.GetRequiredService() - : new DecoratingScopes(_provider.GetRequiredService(), decorate)); + : new DecoratingScopes(_provider.GetRequiredService(), decorate), + BackgroundJobLifecycleProjectionDeclaration.Create()); public async Task InsertAsync(Guid? id = null, string subscription = First, string? type = null, Guid? organization = null, string? partition = null, Guid? tenant = null, DateTimeOffset? occurred = null) @@ -646,6 +891,10 @@ INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization } public async Task ReadAsync(Guid id, string subscription = First, Guid? tenant = null, + CancellationToken cancellationToken = default) => + (await TryReadAsync(id, subscription, tenant, cancellationToken)).Should().NotBeNull().And.Subject.As(); + + public async Task TryReadAsync(Guid id, string subscription = First, Guid? tenant = null, CancellationToken cancellationToken = default) { await using var connection = await Dispatch.OpenConnectionAsync(cancellationToken); @@ -656,7 +905,7 @@ public async Task ReadAsync(Guid id, string subscription = First, Guid? ten """, connection); Bind(command, id, subscription, tenant); await using var row = await command.ExecuteReaderAsync(cancellationToken); - (await row.ReadAsync(cancellationToken)).Should().BeTrue(); + if (!await row.ReadAsync(cancellationToken)) return null; return new(row.GetInt32(0), Text(row, 1), Time(row, 2), row.GetFieldValue(3), Time(row, 4), Text(row, 5), Time(row, 6), Text(row, 7), row.GetInt32(8), Time(row, 9)); } @@ -687,10 +936,11 @@ public async Task NowAsync(CancellationToken cancellationToken = await row.ReadAsync(cancellationToken); return row.GetFieldValue(0); } - public static async Task RequestTerminalAsync(DeliveryDispatchStore store) + public static async Task RequestTerminalAsync( + DeliveryDispatchStore store, DeliveryTerminalReason reason = DeliveryTerminalReason.InvalidEnvelope) { var claim = (await store.TryClaimAsync(NoBlocked))!; - (await store.RequestTerminalAsync(claim, DeliveryTerminalReason.InvalidEnvelope)).Should().BeTrue(); + (await store.RequestTerminalAsync(claim, reason)).Should().BeTrue(); return (await store.TryClaimTerminalAsync(NoBlocked))!; } public async Task CompleteAsync(Guid id, string subscription, bool inbox) @@ -727,6 +977,37 @@ private async Task CountAsync(string sql) await using var command = new NpgsqlCommand(sql, connection, transaction); return (long)(await command.ExecuteScalarAsync())!; } + public async Task SetTenantStatusAsync(string status) + { + await using var connection = await _app.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.ExecuteAsync(connection, transaction, + "UPDATE tenants SET status = @status WHERE id = @tenant", + ("status", status), ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + public async Task> ReadOperatorAuditAsync(string operation) + { + await using var connection = await _app.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.SetSettingAsync(connection, transaction, "app.scope", "tenant"); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, organization_id, actor_user_id IS NULL, operation, reason, correlation_id, + metadata::text, operation_class, operation_type + FROM audit_log WHERE operation = @operation ORDER BY timestamp + """, connection, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var row = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await row.ReadAsync()) + rows.Add(new(row.GetGuid(0), row.IsDBNull(1) ? null : row.GetGuid(1), row.GetBoolean(2), row.GetString(3), + row.IsDBNull(4) ? null : row.GetString(4), row.GetString(5), row.GetString(6), row.GetString(7), row.GetString(8))); + return rows; + } + public async Task ReadAuditAsync() { await using var connection = await _app.OpenConnectionAsync(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs new file mode 100644 index 00000000..78236604 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs @@ -0,0 +1,270 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Messaging; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Messaging; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The operator's metadata-only inspection of dead-lettered work against a real database and the real platform +/// scope (ADR-0103 § 1): its pages, its cursors, the one entry row each page writes and what the platform role's +/// column grants refuse. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DeliveryInspectionTests(SchemaFixture schema) +{ + private const string Subscription = "test.inspect.v1"; + private static readonly string KnownType = typeof(InspectionEvent).AssemblyQualifiedName!; + + [Fact] + public async Task A_page_lists_dead_lettered_outbox_rows_oldest_first_with_the_fence_and_pages_by_cursor() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var ids = new[] { Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7() }; + for (var index = 0; index < ids.Length; index++) + await proof.OutboxAsync(ids[index], $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index + 1} 12:00:00.123456+00'"); + await proof.OutboxAsync(Guid.CreateVersion7(), "processed_at = now()"); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted'"); + + var first = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 2); + var second = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 2); + + first.Items.Select(row => row.EventId).Should().Equal(ids[0], ids[1]); + first.NextCursor.Should().NotBeNull(); + second!.Items.Select(row => row.EventId).Should().Equal([ids[2]], "a page after the last row holds only it"); + second.NextCursor.Should().BeNull(); + var row = first.Items[0]; + row.TenantId.Should().Be(SchemaFixture.TenantA); + row.Attempts.Should().Be(6); + row.TerminalReason.Should().Be("retry_exhausted"); + row.DeadLetteredAt!.Value.UtcTicks.Should().Be(new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero).AddTicks(1234560).UtcTicks, + "the fence instant comes back to the microsecond"); + row.EventType.Should().Be("InspectionEvent", "the registry's label stands for the stored type text"); + row.Actionable.Should().BeTrue(); + } + + [Fact] + public async Task A_terminal_requested_row_is_listed_and_never_actionable() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var id = Guid.CreateVersion7(); + await proof.OutboxAsync(id, "attempts = 6, terminal_reason = 'retry_exhausted'"); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); + + var page = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 10); + + var row = page!.Items.Should().ContainSingle().Which; + row.EventId.Should().Be(id); + row.DeadLetteredAt.Should().BeNull(); + row.Actionable.Should().BeFalse("its state is shown and a reset is not offered"); + } + + [Fact] + public async Task Deliveries_show_the_replay_fence_and_mark_what_a_replay_could_act_on() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var replayable = Guid.CreateVersion7(); + var envelope = Guid.CreateVersion7(); + await proof.DeliveryAsync(replayable, Subscription, "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.5+00', replay_count = 2, replayed_at = now()"); + await proof.DeliveryAsync(envelope, Subscription, "terminal_reason = 'invalid_envelope', dead_lettered_at = '2026-10-02 12:00:00+00'"); + + var page = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + + page!.Items.Select(row => row.EventId).Should().Equal(replayable, envelope); + page.Items[0].Should().Match(row => row.ReplayCount == 2 && row.TerminalReason == "retry_exhausted" + && row.SubscriptionId == Subscription && row.Actionable && row.EventType == "InspectionEvent"); + page.Items[1].Actionable.Should().BeFalse("an envelope that is invalid cannot become valid"); + } + + [Fact] + public async Task Quarantined_jobs_list_with_their_reservation_occupancy_and_no_parameters() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var job = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA); + await using (var dispatcher = await PostgresFixture.OpenAsync(proof.Database.OutboxConnectionString)) + await SchemaQueries.ExecuteAsync(dispatcher, null, + "UPDATE background_jobs SET phase = 'quarantined', quarantine_reason = 'unknown_outcome' WHERE id = @id", ("id", job.Value)); + + var page = await proof.Inspection.InspectJobsAsync(proof.Admission(), null, 10); + + var row = page!.Items.Should().ContainSingle().Which; + row.JobId.Should().Be(job.Value); + row.Phase.Should().Be("quarantined"); + row.QuarantineReason.Should().Be("unknown_outcome"); + row.DefinitionKey.Should().Be("fixture.unknown.v1"); + row.HeldReservations.Should().Be(0); + JsonSerializer.Serialize(row).Should().NotContain("parameters", "no envelope or parameter column is read"); + } + + [Fact] + public async Task Each_page_writes_one_entry_row_naming_the_inspection_and_no_result_row_and_the_scope_changes_nothing() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); + var admission = proof.Admission("INC-103"); + + await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, null, 10); + + var rows = await proof.AuditAsync(admission.Operator.CorrelationId!); + var entry = rows.Should().ContainSingle("the scope reads and changes nothing, so it writes no result row").Which; + entry.Operation.Should().Be(PlatformAdminScope.EnterOperation); + entry.Reason.Should().Be("delivery_inspect"); + entry.Metadata.Should().Contain("INC-103", "a sentinel-tenant row is unreadable to every tenant, so it carries the ticket"); + } + + [Fact] + public async Task A_malformed_or_foreign_cursor_answers_null_and_enters_no_scope() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var admission = proof.Admission(); + + (await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, "not-a-cursor", 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("v1~outbox.DeadLettered~1~x")), 10)).Should().BeNull("a cursor of another resource is refused"); + + (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should().BeEmpty(); + } + + [Fact] + public async Task The_platform_role_cannot_select_an_excluded_column_of_any_inspected_table() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + + foreach (var sql in new[] + { + "SELECT payload FROM outbox_messages", "SELECT correlation_id FROM outbox_messages", + "SELECT locked_by FROM outbox_messages", "SELECT * FROM outbox_messages", + "SELECT payload FROM event_deliveries", "SELECT correlation_id FROM event_deliveries", + "SELECT locked_by FROM event_deliveries", "SELECT * FROM event_deliveries", + "SELECT parameters FROM background_jobs", "SELECT plan FROM background_jobs", + "SELECT traceparent FROM background_jobs", "SELECT operation_id FROM background_jobs", + "SELECT ownership_token FROM background_jobs", "SELECT * FROM background_jobs", + }) + { + await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sql)).Should() + .ThrowAsync(sql).Where(failure => failure.SqlState == PostgresErrorCodes.InsufficientPrivilege, sql); + } + + await SchemaQueries.ExecuteAsync(platform, null, "SELECT id, attempts, dead_lettered_at FROM outbox_messages"); + await SchemaQueries.ExecuteAsync(platform, null, "SELECT job_id, released_at FROM background_job_reservations"); + } + + [IntegrationEventPartition(nameof(TenantId), tenantWide: true)] + public sealed record InspectionEvent : IntegrationEventBase + { + public override string Topic => "learnstack.test.inspection"; + public override string PartitionKey => TenantId.ToString("D"); + } + + public sealed class InspectionHandler : IIntegrationEventHandler + { + public Task HandleAsync(InspectionEvent fact, CancellationToken cancellationToken) => Task.CompletedTask; + } + + private sealed class Proof : IAsyncDisposable + { + private readonly PostgresFixture _postgres; + private readonly NpgsqlDataSource _platform; + + private Proof(PostgresFixture postgres, DisposableSchemaDatabase database) + { + _postgres = postgres; + Database = database; + _platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + var handlers = IntegrationEventHandlerRegistry.FromServiceDescriptors( + [ServiceDescriptor.Scoped, InspectionHandler>()]); + var registry = OutboxEventRegistry.Create( + [OutboxEventRegistration.Required(typeof(InspectionEvent), [OutboxSubscriptionManifest.Active(Subscription, typeof(InspectionHandler))], + "declared.previous.inspection")], [], handlers, [typeof(InspectionEvent).Assembly]); + var scope = new PlatformAdminScope( + new PrivilegedDataSource(() => _platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + AuditStoreScopeFactory(), new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + Inspection = new DeliveryInspection(scope, registry); + } + + internal DisposableSchemaDatabase Database { get; } + + internal DeliveryInspection Inspection { get; } + + internal static async Task CreateAsync(PostgresFixture postgres) + { + var proof = new Proof(postgres, await DisposableSchemaDatabase.CreateAsync(postgres)); + await proof.SqlAsync($""" + INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row_version) + VALUES ('{SchemaFixture.TenantA}', 'inspection', 'Inspection', 'Trial', now(), '{UserId.SystemActor.Value}', 0); + INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) + VALUES ('{SchemaFixture.OrgA1}', '{SchemaFixture.TenantA}', 'hq', 'HQ', 'Active', now(), '{UserId.SystemActor.Value}', 0); + UPDATE tenants SET default_organization_id = '{SchemaFixture.OrgA1}' WHERE id = '{SchemaFixture.TenantA}'; + """); + return proof; + } + + internal PlatformAdmission Admission(string? ticket = null) => TestPlatformAdmissions.Admission( + PlatformOperations.DeliveryInspect, ticket, correlationId: "00-inspect-" + Guid.NewGuid().ToString("N")); + + internal Task OutboxAsync(Guid id, string assignments) => SqlAsync($""" + INSERT INTO outbox_messages (id, tenant_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, payload) + VALUES ('{id}', '{SchemaFixture.TenantA}', '{SchemaFixture.OrgA1}', '2026-10-01 12:00:00+00', 'c', '{KnownType}', 'learnstack.test.inspection', 'k', '[]'::jsonb); + UPDATE outbox_messages SET {assignments} WHERE id = '{id}'; + """); + + internal Task DeliveryAsync(Guid id, string subscription, string assignments) => SqlAsync($""" + INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, payload) + VALUES ('{SchemaFixture.TenantA}', '{subscription}', '{id}', '{SchemaFixture.OrgA1}', '2026-10-01 12:00:00+00', 'c', '{KnownType}', 'learnstack.test.inspection', 'k', '[]'::jsonb); + UPDATE event_deliveries SET {assignments} WHERE event_id = '{id}'; + """); + + internal async Task> AuditAsync(string correlation) + { + await using var connection = await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT operation, reason, metadata::text FROM audit_log WHERE correlation_id = @c ORDER BY timestamp", (NpgsqlConnection)connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List<(string, string?, string)>(); + while (await reader.ReadAsync()) rows.Add((reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1), reader.GetString(2))); + return rows; + } + + private Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); + + public async ValueTask DisposeAsync() + { + await _platform.DisposeAsync(); + await Database.DisposeAsync(); + } + + private static IServiceScopeFactory AuditStoreScopeFactory() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's row is written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs index 3cd0673e..d20c60e4 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs @@ -40,6 +40,14 @@ INSERT INTO event_deliveries "terminal_reason", "dead_lettered_at", "replay_count", "replayed_at", ]; + /// ADR-0103: the metadata an operator inspects, with no envelope, causal, routing or lease-token column. + private static readonly string[] PlatformInspectionColumns = + [ + "tenant_id", "subscription_id", "event_id", "organization_id", "occurred_at", "type", "processed_at", + "attempts", "last_error", "available_after", "locked_until", "terminal_reason", "dead_lettered_at", + "replay_count", "replayed_at", + ]; + private static readonly string[] SchedulerReadColumns = [ "tenant_id", "subscription_id", "event_id", "organization_id", "occurred_at", @@ -88,7 +96,10 @@ AND relname IN ('inbox_messages','event_deliveries') } await context.Database.MigrateAsync(); - (await InventoryAsync(database.MigrationConnectionString)).Should().Equal(before); + // The database was built at this migration and brought to the head, so what later migrations add to these two + // tables (the platform role's inspection grants and the dead-letter index, ADR-0103) is not a difference. + (await InventoryAsync(database.MigrationConnectionString)).Where(item => !AddedAfterTheLedger(item)) + .Should().Equal(before); await using var restored = await PostgresFixture.OpenAsync(database.AppConnectionString); await using var restoredTransaction = await restored.BeginTransactionAsync(); await AnnounceAsync(restored, restoredTransaction, SchemaFixture.TenantA); @@ -134,6 +145,7 @@ SELECT column_name FROM information_schema.columns ("learnstack_app", "INSERT") => AcceptanceColumns.ToList(), ("learnstack_app", "UPDATE") => ["processed_at"], ("learnstack_outbox_admin", "SELECT") => SchedulerReadColumns.ToList(), + ("learnstack_platform", "SELECT") => PlatformInspectionColumns.ToList(), ("learnstack_outbox_admin", "UPDATE") => SchedulingColumns.ToList(), _ => [], }; @@ -905,6 +917,10 @@ SELECT column_name FROM information_schema.column_privileges return result; } + private static bool AddedAfterTheLedger(string item) => + item.StartsWith("grant:event_deliveries:learnstack_platform:", StringComparison.Ordinal) + || item.Contains("ix_event_deliveries_dead_lettered", StringComparison.Ordinal); + private static async Task> InventoryAsync(string connectionString) { await using var owner = await PostgresFixture.OpenAsync(connectionString); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index b2286e3a..16eabbb5 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -221,8 +221,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() { (tenancy, "20261029112940_guard_retained_tenancy_defaults", TenancyReversibleHead, "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), - (platform, "20261105020229_lock_invitation_envelope_parent", PlatformReversibleHead, - "20261110013140_add_custom_field_protected_receipts", "Retained custom field receipts require a reviewed forward migration."), + (platform, "20261110013140_add_custom_field_protected_receipts", PlatformReversibleHead, + "20261120120000_grant_platform_delivery_inspection", "The platform role's column grants require a reviewed forward migration."), (identity, "20261119140000_add_operator_subject_resolver", IdentityReversibleHead, "20261120090000_add_identity_authority_rebind", "The issuer-rebind storage requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs index 79e30fc9..1149b998 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs @@ -11,7 +11,10 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Messaging; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Time; +using LearnStack.Modules.Tenancy.Infrastructure.Jobs; +using LearnStack.Tests.Fixtures; using LearnStack.Tools.Seeder; using MediatR; using Microsoft.Extensions.DependencyInjection; @@ -938,12 +941,246 @@ public sealed record DispatchEventV1 : IntegrationEventBase public override string PartitionKey => SubjectId.ToString("D"); } + private const string DeadLetterRetryExhausted = + "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"; + + private static PlatformAdmission ResetAdmission(DateTimeOffset? issuedAt = null, PlatformOperation? operation = null) => + TestPlatformAdmissions.Admission( + operation ?? PlatformOperations.DeliveryReset, null, + correlationId: "00-recovery-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt ?? Occurred); + + /// A reset under the fence the row shows now, as an operator would present what inspection returned. + private static async Task ResetAsync( + OutboxDispatchStore store, TestDatabase test, Guid id, Func? change = null, + PlatformAdmission? admission = null, Guid? tenant = null) + { + var row = await test.ReadAsync(id); + var request = new OutboxResetRequest(tenant ?? SchemaFixture.TenantA, id, row.Attempts, row.DeadLetteredAt ?? DateTimeOffset.UnixEpoch); + return await store.ResetAsync(change?.Invoke(request) ?? request, admission ?? ResetAdmission()); + } + + [Fact] + public async Task Reset_under_the_current_fence_renews_the_budget_writes_one_operator_row_and_returns_the_row_to_the_dispatcher() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.SetStateAsync(id, DeadLetterRetryExhausted + ", last_error = 'terminal:retry_exhausted:closed'"); + var store = test.Store(); + var admission = ResetAdmission(); + + var result = await ResetAsync(store, test, id, admission: admission); + + result.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 0)); + var row = await test.ReadAsync(id); + (row.Attempts, row.TerminalReason, row.DeadLetteredAt, row.LastError, row.Token, row.LockedUntil, row.ProcessedAt) + .Should().Be((0, null, null, null, null, null, null)); + var audit = (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle().Which; + audit.Tenant.Should().Be(SchemaFixture.TenantA); + audit.ActorIsNull.Should().BeTrue(); + audit.Reason.Should().Be("delivery_reset"); + audit.Class.Should().Be("Must"); + audit.Type.Should().Be("SecurityEvent"); + audit.Correlation.Should().Be(admission.Operator.CorrelationId); + var metadata = JsonNode.Parse(audit.Metadata)!.AsObject(); + metadata.Select(pair => pair.Key).Should().BeEquivalentTo(["operator", "event_id", "fence"]); + metadata["operator"]!.AsObject().ContainsKey("ticket").Should().BeFalse(); + metadata["event_id"]!.GetValue().Should().Be(id); + metadata["fence"]!["before"]!["attempts"]!.GetValue().Should().Be(6); + metadata["fence"]!["before"]!["dead_lettered_at"]!.GetValue().Should().Be("2026-10-01T12:00:00.1234560Z"); + metadata["fence"]!["before"]!["terminal_reason"]!.GetValue().Should().Be("retry_exhausted"); + metadata["fence"]!["after"]!["attempts"]!.GetValue().Should().Be(0); + var claim = (await store.TryClaimAsync(NoBlockedPartitions))!; + claim.Id.Should().Be(id); + claim.Attempts.Should().Be(1, "the six-attempt budget is renewed, and the runbook says so"); + (await test.DeliveryRowCountAsync()).Should().Be(0, "a producer reset writes no delivery row: acceptance reaches subscriptions on the next dispatch"); + } + + [Theory] + [InlineData("attempts")] + [InlineData("instant-after-one-microsecond")] + [InlineData("instant-before-one-microsecond")] + public async Task Reset_with_any_part_of_the_fence_changed_is_stale_and_changes_nothing(string change) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + + var result = await ResetAsync(test.Store(), test, id, request => change switch + { + "attempts" => request with { Attempts = request.Attempts + 1 }, + "instant-after-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(10) }, + _ => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-10) }, + }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + + [Theory] + [InlineData("unknown_type")] + [InlineData("retired_type")] + [InlineData("invalid_envelope")] + public async Task Reset_refuses_every_reason_but_retry_exhaustion(string reason) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, $"terminal_reason = '{reason}', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); + var before = await test.ReadAsync(id); + + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + + [Theory] + [InlineData("pending")] + [InlineData("processed")] + public async Task Reset_treats_a_row_that_is_not_dead_lettered_as_a_stale_fence(string state) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, state == "pending" ? "attempts = 6, terminal_reason = 'retry_exhausted'" : "processed_at = now()"); + var before = await test.ReadAsync(id); + + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task Reset_of_a_row_whose_type_the_registry_no_longer_knows_is_not_recoverable() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var gone = await test.InsertAsync(type: "No.Such.Type, Nowhere"); + var retired = await test.InsertAsync(type: "retired.type"); + foreach (var id in new[] { gone, retired }) + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var registry = OutboxEventRegistry.Create( + [OutboxEventRegistration.IntentionallyUnsubscribed(typeof(DispatchEventV1))], ["retired.type"], + IntegrationEventHandlerRegistry.Discover(), [typeof(DispatchEventV1).Assembly]); + + foreach (var id in new[] { gone, retired }) + { + var before = await test.ReadAsync(id); + (await ResetAsync(test.Store(registry), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable, + "a reset would only dead-letter the row again with a second MUST row"); + (await test.ReadAsync(id)).Should().Be(before); + } + } + + [Fact] + public async Task Reset_names_the_tenant_and_a_row_of_another_tenant_or_a_missing_one_is_not_found() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var store = test.Store(); + + (await ResetAsync(store, test, id, tenant: SchemaFixture.TenantB)).Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + (await store.ResetAsync(new OutboxResetRequest(SchemaFixture.TenantA, Guid.CreateVersion7(), 6, Occurred), ResetAdmission())) + .Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task Reset_of_a_row_whose_tenant_is_not_serving_is_not_recoverable_until_it_serves_again() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + + (await test.ReadAsync(id)).Should().Be(before); + await test.SetTenantStatusAsync("Active"); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task A_failed_operator_audit_write_rolls_the_reset_back_and_the_spent_admission_cannot_retry() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var admission = ResetAdmission(); + await test.AuditInsertGrantAsync(false); + + var attempt = () => ResetAsync(test.Store(), test, id, admission: admission); + + await attempt.Should().ThrowAsync(); + (await test.ReadAsync(id)).Should().Be(before); + await test.AuditInsertGrantAsync(true); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + var again = () => ResetAsync(test.Store(), test, id, admission: admission); + await again.Should().ThrowAsync(); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task Reset_refuses_an_admission_for_another_operation_or_a_stale_one_and_leaves_every_other_row_alone() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + var other = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetStateAsync(other, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var untouched = await test.ReadAsync(other); + var store = test.Store(); + + foreach (var admission in new[] + { + ResetAdmission(operation: PlatformOperations.DeliveryReplay), + ResetAdmission(operation: PlatformOperations.IdentityAuthorityRebind), + ResetAdmission(issuedAt: Occurred.AddSeconds(-31)), + }) + { + var act = () => ResetAsync(store, test, id, admission: admission); + await act.Should().ThrowAsync(); + } + + (await test.ReadAsync(id)).Should().Be(before); + (await ResetAsync(store, test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await test.ReadAsync(other)).Should().Be(untouched, "another dead-lettered row is not the one the fence names"); + } + + [Fact] + public async Task A_reset_whose_commit_acknowledgement_is_lost_is_unknown_and_a_repeat_is_a_stale_fence() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var fence = await test.ReadAsync(id); + await using var proxy = new CommitResponseDroppingProxy(test.OutboxConnectionString, rejectReconciliationConnections: false); + await using var source = OutboxDispatcherDataSource.Build(proxy.ConnectionString); + + var attempt = () => ResetAsync(test.Store(dispatchSource: source), test, id); + + (await attempt.Should().ThrowAsync()).Which.CommitOutcomeUnknown.Should().BeTrue(); + (await test.ReadAsync(id)).Attempts.Should().Be(0, "the commit landed although its answer did not"); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle(); + var repeat = await test.Store().ResetAsync( + new OutboxResetRequest(SchemaFixture.TenantA, id, fence.Attempts, fence.DeadLetteredAt!.Value), ResetAdmission()); + repeat.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + } + private sealed record Row( Guid Id, int Attempts, string? Token, DateTimeOffset? LockedUntil, DateTimeOffset AvailableAfter, DateTimeOffset? ProcessedAt, string? TerminalReason, DateTimeOffset? DeadLetteredAt, string? LastError, string Type, string Payload, string? Metadata); + private sealed record OperatorAuditRow( + Guid Tenant, bool ActorIsNull, string Operation, string? Reason, string Correlation, string Metadata, string Class, string Type); + private sealed record AuditRow( Guid Tenant, Guid? Organization, Guid Actor, string Module, string Operation, string Type, string Class, string Outcome, string? Reason, string Correlation, string Metadata); @@ -986,7 +1223,8 @@ public OutboxDispatchStore Store( new PrivilegedDataSource(() => dispatchSource ?? DispatchSource), registry ?? EligibleRegistry(), new OutboxDispatchOptions(), new SystemGuidFactory(), clock ?? new FixedClock(Occurred), decorate is null ? Provider.GetRequiredService() - : new DecoratingScopeFactory(Provider.GetRequiredService(), decorate)); + : new DecoratingScopeFactory(Provider.GetRequiredService(), decorate), + BackgroundJobLifecycleProjectionDeclaration.Create()); public async Task InsertAsync( Guid? id = null, Guid? organization = null, int attempts = 0, @@ -1100,6 +1338,42 @@ public async Task AuditCountAsync(Guid? tenant = null) return (long)(await command.ExecuteScalarAsync())!; } + public async Task SetTenantStatusAsync(string status) + { + await using var connection = await _appSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.ExecuteAsync(connection, transaction, + "UPDATE tenants SET status = @status WHERE id = @tenant", ("status", status), ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + public async Task DeliveryRowCountAsync() + { + await using var connection = await DispatchSource.OpenConnectionAsync(); + await using var command = new NpgsqlCommand("SELECT count(*) FROM event_deliveries", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + public async Task> ReadOperatorAuditAsync(string operation) + { + await using var connection = await _appSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.SetSettingAsync(connection, transaction, "app.organization_id", SchemaFixture.OrgA1.ToString("D")); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, actor_user_id IS NULL, operation, reason, correlation_id, metadata::text, operation_class, operation_type + FROM audit_log WHERE operation = @operation ORDER BY timestamp + """, connection, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + rows.Add(new(reader.GetGuid(0), reader.GetBoolean(1), reader.GetString(2), Text(reader, 3), reader.GetString(4), + reader.GetString(5), reader.GetString(6), reader.GetString(7))); + return rows; + } + public async Task ReadAuditAsync() { await using var connection = await _appSource.OpenConnectionAsync(); @@ -1151,6 +1425,7 @@ INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row VALUES (@tenant, 'dispatch-probe', 'Dispatch probe', 'Trial', now(), @actor, 0); INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) VALUES (@organization, @tenant, 'hq', 'HQ', 'Active', now(), @actor, 0); + UPDATE tenants SET default_organization_id = @organization WHERE id = @tenant; """, ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), ("actor", UserId.SystemActor.Value)); await transaction.CommitAsync(); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs index 9c25e5c9..e2e5f41e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs @@ -1398,7 +1398,8 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi // that lets anything enter EnterPlatformAdminScope at all. "learnstack_platform platform_killswitches DELETE,INSERT,SELECT,UPDATE", "learnstack_platform platform_host_to_tenant DELETE,INSERT,SELECT,UPDATE", - "learnstack_platform outbox_messages DELETE,SELECT", + // ADR-0103: the purge keeps its DELETE; the table-wide SELECT is gone, and the inspection reads named columns. + "learnstack_platform outbox_messages DELETE", "learnstack_platform idempotency_keys DELETE,SELECT", "learnstack_app tenant_content_types DELETE,INSERT,SELECT,UPDATE", "learnstack_app tenant_level_taxonomies DELETE,INSERT,SELECT,UPDATE", diff --git a/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs index d4707ef6..0bb4e88c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs @@ -1261,13 +1261,7 @@ INSERT INTO outbox_messages } finally { - await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); - await using var cleanup = new NpgsqlCommand( - "DELETE FROM outbox_messages WHERE correlation_id = @correlation", - (NpgsqlConnection)platform); - cleanup.Parameters.AddWithValue("correlation", correlation); - await cleanup.ExecuteNonQueryAsync(); + await DeleteOutboxAsync(correlation); } } @@ -1632,21 +1626,21 @@ INSERT INTO outbox_messages """, ("tenant", SchemaFixture.TenantA), ("correlation", correlation)); + // The platform role no longer reads correlation_id (ADR-0103 limits it to inspection metadata), and the dispatcher + // role cannot delete, so a test's own rows are removed by the container's superuser and counted by the dispatcher + // role, which reads the table across tenants. private async Task DeleteOutboxAsync(string correlation) { - await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); - await using var cleanup = new NpgsqlCommand( - "DELETE FROM outbox_messages WHERE correlation_id = @correlation", - (NpgsqlConnection)platform); - cleanup.Parameters.AddWithValue("correlation", correlation); - await cleanup.ExecuteNonQueryAsync(); + System.Text.RegularExpressions.Regex.IsMatch(correlation, "^[0-9A-Za-z-]+$").Should().BeTrue( + "the cleanup statement embeds only a generated identifier"); + await _schema.Postgres.ExecuteAsSuperuserAsync( + $"DELETE FROM outbox_messages WHERE correlation_id = '{correlation}'"); } private async Task CountOutboxAsync(string correlation) { await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); + _schema.Postgres.OutboxConnectionString); await using var command = new NpgsqlCommand( "SELECT count(*) FROM outbox_messages WHERE correlation_id = @correlation", (NpgsqlConnection)platform); diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index 461c3306..4cd7a817 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -45,6 +45,8 @@ public sealed class PlatformOperatorHttpTests : IAsyncLifetime private TenantAuthenticationIssuer _operator = null!; private PlatformOperatorApiFactory _factory = null!; private RecordingToggle _toggle = null!; + private RecordingRecovery _recovery = null!; + private RecordingInspection _inspection = null!; private HttpClient _client = null!; public async Task InitializeAsync() @@ -52,7 +54,14 @@ public async Task InitializeAsync() _tenant = await TenantAuthenticationIssuer.StartAsync(); _operator = await TenantAuthenticationIssuer.StartAsync(); _toggle = new RecordingToggle(); - _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject); + _recovery = new RecordingRecovery(); + _inspection = new RecordingInspection(); + _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => + { + registrations.AddSingleton(_recovery); + registrations.AddScoped(_ => _inspection); + }); _client = _factory.CreateClient(); } @@ -460,11 +469,20 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum .Should().BeTrue(); put.GetProperty("responses").TryGetProperty("409", out _).Should().BeFalse("a switch toggle never answers a refused state"); - // Every onboarding act is a PUT with its own body, the same status set, and a 409 for the state it refuses. + // Every act has its own body, the same status set, and a 409 for the state it refuses. An inspection is a + // read: it has no body and nothing to refuse, so it answers no 409. foreach (var route in OperatorRoutes.Where(route => !route.Contains("killswitches", StringComparison.Ordinal))) { - var act = root.GetProperty("paths").GetProperty(route).GetProperty("put"); + var act = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)); act.GetProperty("security").GetArrayLength().Should().Be(1, route); + if (VerbOf(route) == "get") + { + act.TryGetProperty("requestBody", out _).Should().BeFalse("a read carries no body: " + route); + act.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "500", "503"], route); + continue; + } + act.GetProperty("requestBody").GetProperty("content").GetProperty("application/json") .GetProperty("schema").ValueKind.Should().NotBe(JsonValueKind.Undefined, route); act.GetProperty("responses").EnumerateObject().Select(response => response.Name) @@ -478,7 +496,7 @@ public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Docum var schemas = root.GetProperty("components").GetProperty("schemas"); string[] RequiredOf(string route) { - var schema = root.GetProperty("paths").GetProperty(route).GetProperty("put").GetProperty("requestBody") + var schema = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("requestBody") .GetProperty("content").GetProperty("application/json").GetProperty("schema"); if (schema.TryGetProperty("$ref", out var reference)) { @@ -494,13 +512,224 @@ string[] RequiredOf(string route) RequiredOf("/api/platform/v1/tenants/{tenantId}/roles/{roleId}").Should().Contain(["builtInKey", "capabilityScope"]); RequiredOf("/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}").Should().Contain(["roleId", "providerSubject"]); RequiredOf("/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}").Should().Contain(["roleId", "providerSubject"]); + RequiredOf("/api/platform/v1/asynchronous-work/event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay") + .Should().Contain(["replayCount", "deadLetteredAt", "terminalReason"]); + RequiredOf("/api/platform/v1/asynchronous-work/outbox-messages/{tenantId}/{eventId}/reset") + .Should().Contain(["attempts", "deadLetteredAt"]); foreach (var route in OperatorRoutes) { - root.GetProperty("paths").GetProperty(route).GetProperty("put").GetProperty("responses").EnumerateObject() + root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("responses").EnumerateObject() .Select(response => response.Name).Should().Contain(["413", "429"], route); } } + private const string Work = "/api/platform/v1/asynchronous-work"; + private const string RowTenant = "019a1929-5450-7bbb-8df1-516e8e002501"; + private const string RowEvent = "019a1929-5450-7bbb-8df1-516e8e002502"; + private const string RowSubscription = "orders.notify.v1"; + private const string ReplayPath = Work + "/event-deliveries/" + RowTenant + "/" + RowSubscription + "/" + RowEvent + "/replay"; + private const string ResetPath = Work + "/outbox-messages/" + RowTenant + "/" + RowEvent + "/reset"; + private const string ReplayBody = """{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00.1234560Z","terminalReason":"retry_exhausted","ticket":"CHG-103"}"""; + private const string ResetBody = """{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.1234560Z","ticket":"CHG-103"}"""; + + [Fact] + public async Task An_Inspection_Passes_Its_Parameters_On_Clamps_The_Limit_And_Answers_The_Page_Envelope() + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?state=terminal_requested&limit=500&cursor=abc&ticket=CHG-1", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _inspection.Calls.Should().ContainSingle().Which; + call.Resource.Should().Be("outbox"); + call.State.Should().Be(DeliveryInspectionState.TerminalRequested); + call.Cursor.Should().Be("abc"); + call.Limit.Should().Be(100, "a limit above the maximum is clamped, as Standard 04 says"); + call.Admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryInspect); + call.Admission.Ticket.Should().Be("CHG-1"); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next-cursor\"").And.Contain("\"hasNext\":true"); + } + + [Theory] + [InlineData("state=bogus")] + [InlineData("limit=abc")] + [InlineData("limit=-1")] + [InlineData("limit=1.5")] + [InlineData("ticket=has%20space")] + public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failure_Before_Any_Scope(string query) + { + var response = await Call(HttpMethod.Get, Work + "/event-deliveries?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _inspection.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Cursor_The_Service_Refuses_Is_A_Validation_Failure_And_A_Failed_Audit_Write_Is_A_Retryable_503() + { + _inspection.RefuseCursor = true; + (await Call(HttpMethod.Get, Work + "/quarantined-jobs?cursor=forged", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + _inspection.RefuseCursor = false; + _inspection.Failure = new AuditWriteFailedException("forced"); + var response = await Call(HttpMethod.Get, Work + "/quarantined-jobs", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + } + + [Theory] + [InlineData("GET", Work + "/outbox-messages")] + [InlineData("GET", Work + "/event-deliveries")] + [InlineData("GET", Work + "/quarantined-jobs")] + [InlineData("POST", ReplayPath)] + [InlineData("POST", ResetPath)] + public async Task An_Operator_Without_The_Delivery_Grants_Is_Forbidden_Whatever_The_Request_Carries_And_Nothing_Is_Called(string verb, string path) + { + var response = await Call(new HttpMethod(verb), path, Sign(("sub", "someone-else")), verb == "POST" ? "not json" : null); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _inspection.Calls.Should().BeEmpty("admission is refused before any scope is entered"); + _recovery.Calls.Should().BeEmpty("admission is refused before any outbox-role connection is opened"); + } + + [Fact] + public async Task A_Replay_Carries_The_Fence_To_The_Microsecond_Under_An_Admission_For_Exactly_That_Operation() + { + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, request) = _recovery.Calls.Should().ContainSingle().Which; + admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryReplay); + admission.Ticket.Should().Be("CHG-103"); + var replay = request.Should().BeOfType().Which; + replay.TenantId.Should().Be(Guid.Parse(RowTenant)); + replay.EventId.Should().Be(Guid.Parse(RowEvent)); + replay.SubscriptionId.Should().Be(RowSubscription); + replay.ReplayCount.Should().Be(2); + replay.TerminalReason.Should().Be("retry_exhausted"); + replay.DeadLetteredAt.UtcTicks.Should().Be(new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero).AddTicks(1234560).UtcTicks); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain("\"outcome\":\"applied\"").And.Contain("\"countAfter\":1").And.Contain("\"correlationId\""); + } + + [Fact] + public async Task A_Reset_Carries_Its_Fence_Under_An_Admission_For_The_Reset_Operation() + { + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, request) = _recovery.Calls.Should().ContainSingle().Which; + admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryReset); + var reset = request.Should().BeOfType().Which; + (reset.TenantId, reset.EventId, reset.Attempts).Should().Be((Guid.Parse(RowTenant), Guid.Parse(RowEvent), 6)); + } + + [Theory] + [InlineData("""{}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00Z"}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"not a date","terminalReason":"retry_exhausted"}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00Z","terminalReason":"retry_exhausted","ticket":"has space"}""")] + public async Task A_Replay_Body_That_Cannot_Be_A_Fence_Is_A_Validation_Failure_And_Nothing_Is_Called(string body) + { + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _recovery.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("/event-deliveries/not-a-guid/orders.notify.v1/" + RowEvent + "/replay")] + [InlineData("/event-deliveries/" + RowTenant + "/Not.A.Subscription/" + RowEvent + "/replay")] + [InlineData("/event-deliveries/00000000-0000-0000-0000-000000000000/orders.notify.v1/" + RowEvent + "/replay")] + [InlineData("/event-deliveries/" + RowTenant + "/orders.notify.v1/00000000-0000-0000-0000-000000000000/replay")] + public async Task A_Replay_Route_Naming_No_Real_Row_Is_Refused_Without_Calling_The_Owner(string suffix) + { + var response = await Call(HttpMethod.Post, Work + suffix, Valid(), ReplayBody); + + response.StatusCode.Should().BeOneOf(HttpStatusCode.BadRequest, HttpStatusCode.NotFound); + _recovery.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData(OperatorRecoveryOutcome.StaleFence, HttpStatusCode.Conflict, "lockey_stale_fence")] + [InlineData(OperatorRecoveryOutcome.NotRecoverable, HttpStatusCode.Conflict, "lockey_not_recoverable")] + [InlineData(OperatorRecoveryOutcome.NotFound, HttpStatusCode.NotFound, "not_found")] + public async Task A_Refused_Recovery_Answers_Its_Status_With_The_Reason_On_The_Field_It_Concerns( + OperatorRecoveryOutcome outcome, HttpStatusCode status, string expected) + { + _recovery.Result = new OperatorRecoveryResult(outcome); + + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(status); + (await response.Content.ReadAsStringAsync()).Should().Contain(expected); + } + + [Fact] + public async Task A_Stale_Fence_And_A_Refused_State_Name_Different_Fields_Under_One_Status_Code() + { + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + var stale = await (await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody)).Content.ReadAsStringAsync(); + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + var state = await (await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody)).Content.ReadAsStringAsync(); + + stale.Should().Contain("\"code\":\"business_rule_violation\"").And.Contain("\"fence\""); + state.Should().Contain("\"code\":\"business_rule_violation\"").And.Contain("\"state\""); + } + + [Fact] + public async Task An_Owner_That_Cannot_Finish_Or_Whose_Commit_Is_Unknown_Or_Whose_Audit_Failed_Is_A_Retryable_503_With_Its_Own_Reason() + { + foreach (var (failure, reason) in new (Exception, string)[] + { + (new OperatorRecoveryUnavailableException(), "dependency_unavailable"), + (new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true), "outcome_unknown"), + (new AuditWriteFailedException("forced"), "audit_unavailable"), + }) + { + _recovery.Failure = failure; + + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); + response.Headers.RetryAfter.Should().NotBeNull(reason); + (await response.Content.ReadAsStringAsync()).Should().Contain(reason); + } + } + + [Fact] + public async Task An_Act_Without_A_Body_Or_With_The_Wrong_Media_Type_Is_Answered_As_A_Problem_Only_To_A_Granted_Operator() + { + (await Call(HttpMethod.Post, ResetPath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var wrongType = new HttpRequestMessage(HttpMethod.Post, ResetPath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent(ResetBody, System.Text.Encoding.UTF8, "text/plain"), + }; + + (await _client.SendAsync(wrongType)).StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + _recovery.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task The_Production_Composition_Resolves_The_Recovery_Owner_And_The_Inspection_Over_The_Real_Stores() + { + // The doubles above replace both ports, so this builds the host the way production does and asks for them: a + // registration that is missing or cannot be constructed would otherwise surface only on the first operator call. + await using var production = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject); + using var client = production.CreateClient(); + + using var scope = production.Services.CreateScope(); + scope.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + scope.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); + scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); + await Task.CompletedTask; + } + private static readonly string[] OperatorRoutes = [ "/api/platform/v1/killswitches/{key}", @@ -509,8 +738,18 @@ string[] RequiredOf(string route) "/api/platform/v1/tenants/{tenantId}/roles/{roleId}", "/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}", "/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}", + "/api/platform/v1/asynchronous-work/outbox-messages", + "/api/platform/v1/asynchronous-work/event-deliveries", + "/api/platform/v1/asynchronous-work/quarantined-jobs", + "/api/platform/v1/asynchronous-work/event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay", + "/api/platform/v1/asynchronous-work/outbox-messages/{tenantId}/{eventId}/reset", ]; + /// The verb each operator route answers: reads are GET, recovery acts are POST, the rest are idempotent PUTs. + private static string VerbOf(string route) => route.Contains("/asynchronous-work/", StringComparison.Ordinal) + ? route.EndsWith("/replay", StringComparison.Ordinal) || route.EndsWith("/reset", StringComparison.Ordinal) ? "post" : "get" + : "put"; + [Fact] public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() { @@ -544,7 +783,7 @@ public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_S } [Fact] - public void The_Operator_Surface_Is_Exactly_The_Six_Authorized_Put_Endpoints_Under_Its_Prefix() + public void The_Operator_Surface_Is_Exactly_The_Eleven_Authorized_Endpoints_Under_Its_Prefix() { // The tenant surface census excludes this surface by exact type (it has its own scheme), so // its population is closed here instead: every routed endpoint under /api/platform (whatever @@ -560,12 +799,13 @@ public void The_Operator_Surface_Is_Exactly_The_Six_Authorized_Put_Endpoints_Und endpoints.Select(endpoint => endpoint.RoutePattern.RawText).Should().BeEquivalentTo( OperatorRoutes.Select(route => route.Replace("{tenantId}", "{tenantId:guid}").Replace("{roleId}", "{roleId:guid}") - .Replace("{membershipId}", "{membershipId:guid}")), + .Replace("{membershipId}", "{membershipId:guid}").Replace("{eventId}", "{eventId:guid}")), "the operator population is closed: a new route is a reviewed act with its own policy, grant and audit slug"); foreach (var endpoint in endpoints) { var route = endpoint.RoutePattern.RawText; - endpoint.Metadata.GetMetadata()!.HttpMethods.Should().Equal(["PUT"], route); + endpoint.Metadata.GetMetadata()!.HttpMethods.Should().Equal( + [VerbOf(route!.Replace(":guid", string.Empty)).ToUpperInvariant()], route); endpoint.Metadata.GetOrderedMetadata() .Select(data => data.Policy).Should().Contain(PlatformOperatorAuthentication.PolicyName, "an operator endpoint without the authenticated-operator policy would admit an anonymous caller: " + route); @@ -692,6 +932,13 @@ private sealed class MovableClock(DateTimeOffset start) : LearnStack.SharedKerne public void Advance(TimeSpan by) => UtcNow += by; } + private async Task Call(HttpMethod method, string path, string token, string? json = null) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + token } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return await _client.SendAsync(request); + } + private async Task Put(string token, string json) { using var request = new HttpRequestMessage(HttpMethod.Put, Path) @@ -732,6 +979,53 @@ public Task ToggleAsync( } } + private sealed class RecordingRecovery : IOperatorRecovery + { + public List<(PlatformAdmission Admission, object Request)> Calls { get; } = []; + public OperatorRecoveryResult Result { get; set; } = new(OperatorRecoveryOutcome.Applied, 1); + public Exception? Failure { get; set; } + + public Task ReplayDeliveryAsync( + PlatformAdmission admission, DeliveryReplayRequest request, CancellationToken cancellationToken = default) => + Record(admission, request); + + public Task ResetOutboxAsync( + PlatformAdmission admission, OutboxResetRequest request, CancellationToken cancellationToken = default) => + Record(admission, request); + + private Task Record(PlatformAdmission admission, object request) + { + Calls.Add((admission, request)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Result); + } + } + + private sealed class RecordingInspection : IDeliveryInspection + { + public List<(PlatformAdmission Admission, string Resource, DeliveryInspectionState? State, string? Cursor, int Limit)> Calls { get; } = []; + public bool RefuseCursor { get; set; } + public Exception? Failure { get; set; } + + public Task?> InspectOutboxAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "outbox", state, cursor, limit); + + public Task?> InspectDeliveriesAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "delivery", state, cursor, limit); + + public Task?> InspectJobsAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "job", null, cursor, limit); + + private Task?> Page(PlatformAdmission admission, string resource, DeliveryInspectionState? state, string? cursor, int limit) + { + Calls.Add((admission, resource, state, cursor, limit)); + if (Failure is not null) return Task.FromException?>(Failure); + return Task.FromResult?>(RefuseCursor ? null : new InspectionPage([], "next-cursor")); + } + } + private sealed class PlatformOperatorApiFactory( TenantAuthenticationIssuer tenant, TenantAuthenticationIssuer @operator, @@ -751,6 +1045,8 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); builder.UseSetting("PlatformOperator:Grants:0:Subject", grantSubject); builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", PlatformPermissions.KillswitchWrite.Key); + builder.UseSetting("PlatformOperator:Grants:0:Permissions:1", PlatformPermissions.DeliveryRead.Key); + builder.UseSetting("PlatformOperator:Grants:0:Permissions:2", PlatformPermissions.DeliveryWrite.Key); } builder.ConfigureTestServices(registrations => diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs index 0464317b..ed0e050f 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs @@ -8,7 +8,7 @@ namespace LearnStack.Tests.Unit.Infrastructure.Jobs; public sealed class BackgroundJobPhysicalCapacityTests { [Fact] - public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_requires_52_connections() + public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_requires_54_connections() { var capacity = BackgroundJobPhysicalCapacity.Calculate(BackgroundJobInfrastructureRegistry.CreateDefault()); capacity.Pools.Should().Be(3); @@ -16,18 +16,18 @@ public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_ capacity.ControlPools.Should().Be(1); capacity.InvocationOwners.Should().Be(16); capacity.RecurrenceConnections.Should().Be(2); - capacity.RequiredConnections.Should().Be(52); + capacity.RequiredConnections.Should().Be(54); } [Fact] - public void Maximum_valid_control_multiplicity_requires_158_connections() + public void Maximum_valid_control_multiplicity_requires_160_connections() { var capacity = BackgroundJobPhysicalCapacity.Calculate(Topology(6)); capacity.Pools.Should().Be(8); capacity.Workers.Should().Be(32); capacity.ControlPools.Should().Be(6); capacity.InvocationOwners.Should().Be(64); - capacity.RequiredConnections.Should().Be(158); + capacity.RequiredConnections.Should().Be(160); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 5a9c8ec1..2f074e81 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -160,7 +160,7 @@ public async Task An_Unregistered_Operation_Is_Refused() // A lookalike is not the registered instance, however identical its content. var lookalike = typeof(PlatformOperation).GetConstructors( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] - .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true, null]); + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, PlatformOperationExecutor.PlatformScope, null]); (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), (PlatformOperation)lookalike, null)) .Refusal.Should().Be(PlatformRefusal.UnknownOperation); @@ -184,7 +184,7 @@ public async Task Entry_With_An_Unregistered_Operation_Never_Touches_The_Credent var scope = Build(out var dataSource); var lookalike = typeof(PlatformOperation).GetConstructors( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] - .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, true, null]); + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, PlatformOperationExecutor.PlatformScope, null]); var act = async () => await scope.EnterAsync( TestPlatformAdmissions.Admission((PlatformOperation)lookalike), CancellationToken.None); diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs index 7c522514..4933f038 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs @@ -13,8 +13,9 @@ private sealed record Request; [Fact] public void The_Rebind_Operation_Is_Not_A_Pipeline_Act_Even_Though_It_Needs_No_Platform_Role() { - // NeedsPlatformRole is false for the rebind, which is what the executor admits; only the catalog keeps it out. + // NeedsPlatformRole is false for the rebind; what keeps it out is that it does not run in the pipeline. PlatformOperations.IdentityAuthorityRebind.NeedsPlatformRole.Should().BeFalse(); + PlatformOperations.IdentityAuthorityRebind.RunsInPipeline.Should().BeFalse(); var act = () => new PlatformOperatorActCatalog( [new KeyValuePair(typeof(Request), new PlatformOperatorAct(PlatformOperations.IdentityAuthorityRebind))]); @@ -22,6 +23,41 @@ public void The_Rebind_Operation_Is_Not_A_Pipeline_Act_Even_Though_It_Needs_No_P act.Should().Throw(); } + [Theory] + [MemberData(nameof(NonPipelineOperations))] + public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_Catalog(PlatformOperation operation) + { + operation.RunsInPipeline.Should().BeFalse(); + + var act = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(operation))]); + + act.Should().Throw(); + } + + public static TheoryData NonPipelineOperations() => new() + { + PlatformOperations.KillswitchToggle, + PlatformOperations.IdentityAuthorityRebind, + PlatformOperations.DeliveryInspect, + PlatformOperations.DeliveryReplay, + PlatformOperations.DeliveryReset, + }; + + [Fact] + public void Every_Registered_Operation_Runs_In_Exactly_One_Place_And_Only_The_Scope_Needs_The_Platform_Role() + { + foreach (var operation in PlatformOperations.All) + { + operation.NeedsPlatformRole.Should().Be(operation.Executor == PlatformOperationExecutor.PlatformScope, operation.AuditSlug); + operation.RunsInPipeline.Should().Be(operation.Executor == PlatformOperationExecutor.Pipeline, operation.AuditSlug); + } + + PlatformOperations.DeliveryReplay.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); + PlatformOperations.DeliveryReset.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); + PlatformOperations.DeliveryInspect.Executor.Should().Be(PlatformOperationExecutor.PlatformScope); + } + [Fact] public void An_Onboarding_Operation_Is_Still_Accepted() { diff --git a/docs/architecture/15-event-and-outbox.md b/docs/architecture/15-event-and-outbox.md index 0cc4fd0c..d8e302c4 100644 --- a/docs/architecture/15-event-and-outbox.md +++ b/docs/architecture/15-event-and-outbox.md @@ -691,7 +691,10 @@ Normal publication excludes that row permanently. The terminalizer writes on one fenced transaction, retaining the envelope for investigation. Audit failure retains terminal work for retry without publication; completed terminal rows leave pending gauges. A far-future availability time is never a terminal marker. -Phase 03 must decide producer reset/fencing before any operator replay endpoint. +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) decides it: a +narrow operator reset admits only a `retry_exhausted` row under the fence +`(attempts, dead_lettered_at)`, renews its six-attempt budget and writes a MUST row on +the same transaction. Every other reason is refused. ### Subscriber side — dispatch succeeded, handling did not @@ -707,8 +710,12 @@ It refuses pending terminalization, completed business deliveries and Pending, privileged, unknown or retired subscriptions. The reset clears attempts, bounded error and terminal state, invalidates old ownership and makes that tuple due. The scheduler later invokes only its executor, never `PublishAsync`. Completed siblings -remain inbox deduplicated; a completed inbox is never reset. Phase 03 owns operator -permission, HTTP routes and the separately decided producer replay contract. +remain inbox deduplicated; a completed inbox is never reset. Operator replay is +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)'s fenced +transition: the request carries `(replay_count, dead_lettered_at, terminal_reason)` +as the inspection showed it, `invalid_envelope` is always refused, the tenant must be +serving, and the MUST row commits with the reset. The producer reset is a separate +request with its own fence. P02b-8 owns erasure inventory, Phase 03 privileged redaction and Phase 11 retention purge. diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index b45d0d26..2c71bd15 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -505,10 +505,14 @@ remains in the phase Status block. grants, immutable-fact treatment, dependency/deletion order, replay/deduplication floor and evidence of completion. No such authority or policy is chosen by this inventory. Ordinary SystemActor delivery and dispatcher credentials supply none. -- `learnstack_platform` has no grants on inbox, delivery or LearnStack job - tables. `BYPASSRLS` bypasses policies, not SQL privileges, no-delete triggers or - write-once facts. Any required authority change needs its own bounded decision - and migration before the writer ships. +- `learnstack_platform` has no grant on inbox or delivery payloads, a job's + parameters or plan, or any outbox envelope column. It reads named metadata columns + of `outbox_messages`, `event_deliveries`, `background_jobs` and + `background_job_reservations` for the operator inspection of + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), and keeps + `DELETE` on `outbox_messages` for the retention purge. `BYPASSRLS` bypasses policies, + not SQL privileges, no-delete triggers or write-once facts. Any further authority + change needs its own bounded decision and migration before the writer ships. - Live/uncertain effects, reservation accounting, immutable execution evidence, monotonic progress and same-transaction MUST audit remain intact. Erasure, elapsed time and operator authority prove neither quiescence nor permission to diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index 7bbf680f..06ef6642 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -265,7 +265,12 @@ registers `platform.delivery.dead_letter`, both off-path under Tenancy. The subscriber witness binds the actual tenant/subscription/event tuple and uses a validated attempt trace without causal-envelope or payload SELECT. Outcome success describes terminal state, not publication. Producer terminal audit omits invalid -causal fields in favor of a fresh validated attempt trace. +causal fields in favor of a fresh validated attempt trace. The operator's reset of a +dead-lettered row is a sibling seam, `WriteOperatorRecoveryAsync` +([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)): its witness +carries the admitted operator and the fence before and after, the row names the real +event tenant with no actor and no ticket, and the outbox role needs no new policy arm +because it bypasses row security and already holds `INSERT`. Absent optional causal IDs are valid and do not alone invalidate the stored trace. Closed terminal values use bounded metadata; `Reason` stays for platform entry. Audit failure retains terminal work for retry without delivery; uncertain COMMIT diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md index 89aea658..03dddd4a 100644 --- a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -243,3 +243,79 @@ follow. - [Event and Outbox](../architecture/15-event-and-outbox.md), [Data Protection](../architecture/23-data-protection.md) - [Phase 03](../roadmap/phase-03-identity-admin.md): G14, D13, C15 + +## Amendment 1 — Implementation contract of the recovery owner (2026-11-20) + +Step 4 of the platform-authority packet implements the decision. Each item below fixes +something the Decision left open or states where the code meets it; items 2, 3 and 4 +correct a statement the code could not satisfy as written. None of them changes the +Decision's choice of option, its two transitions, its permissions or its refusal of job +recovery. + +1. **Where the code lives.** The owner is `OperatorRecovery`, a singleton behind + `IOperatorRecovery`. It holds the two dispatcher stores and no credential, so the + credential census gains no reader and no keyed binding. `ReplayAsync` stays on + `DeliveryDispatchStore` with its new signature, and `ResetAsync` is new on + `OutboxDispatchStore`; both are partial-class files, and neither store's claim, fail + or terminalize code changed. Each store gained a third connection slot, reserved for + the operator lane: the dispatcher's own two slots (the main owner and its + uncertain-COMMIT reconciliation) are never taken by an operator, a second concurrent + operator call on a store is refused as unavailable instead of waiting, and the + physical-capacity ledger grows by the two lanes, from 52 to 54 for the default + topology and from 158 to 160 for the maximum. +2. **The platform role already read `outbox_messages` whole.** § 1 says a migration + gives the role `SELECT` on named columns so that the database refuses the rest. The + role held table-wide `SELECT` and `DELETE` there since the first platform migration, + so a column grant beside it would exclude nothing. The migration revokes the + table-wide `SELECT`, grants twelve named columns, keeps `DELETE` for the retention + purge that Phase 11 owns (its predicate reads only granted columns), and grants named + columns on the other three tables: fifteen on `event_deliveries`, twenty-seven on + `background_jobs` and every column of `background_job_reservations`. No envelope, + parameter, plan, outcome, causal, trace, lease-token or operation-key column is among + them. It adds two partial indexes on the dead-lettered rows, because no index served + that scan. The canonical SQL is in Database Standards, and the platform-role tests + that read `correlation_id` moved to the owner and dispatcher roles. +3. **One witness class with two kinds, and no audit DDL.** § 5 says a new witness kind, + and the carrier disclosures say two. The code has one sibling class, + `OperatorRecoveryTransition`, whose protected minting seam is subtyped only by a + private nested class in each of the two stores and whose two factories are the replay + and the reset. It is not a third factory on the terminal witness, whose census pins + two. One new `IAuditStore` method, `WriteOperatorRecoveryAsync`, writes the row, + which makes fourteen writes. The outbox role already holds `INSERT` on `audit_log` + and bypasses row security, so no policy arm or grant changed: the binding of the row + to the real event tenant is the witness's, which composes the exact `metadata` (the + operator attribution, the event and subscription, and the fence before and after) and + refuses a draft that differs. +4. **The error vocabulary.** The API's status map is closed and answers an unknown + top-level code with `500`, so `stale_fence` and `not_recoverable` are not codes. A + stale fence is `409` `business_rule_violation` with the reason `lockey_stale_fence` + on the field `fence`, and a refused state is `409` with `lockey_not_recoverable` on + the field `state`, as the onboarding acts already answer. A missing row is `404`. A + MUST row that cannot be written, an unavailable lane or database, and a commit whose + answer was lost are `503` with `Retry-After`, the last with its own reason + `outcome_unknown`. +5. **"The event's tenant is Active."** The test is the lifecycle projection the + dispatcher role already reads, read in the same transaction as the reset: the tenant + is not deleted, has its default organization and is Trial or Active, which is the + serving-tenant meaning the job runtime uses. Suspended and Archived tenants are + refused. A producer reset also refuses a row whose stored type the registry has since + retired or no longer knows, because a reset would only dead-letter it again with a + second MUST row. +6. **Inspection.** Each page is one entered platform scope on the platform role's column + grants, so the scope's entry row, which names `platform.delivery.inspect` and carries + the ticket and the operator's attribution, is the audit. The scope reads and changes + nothing, so it writes no result row and ends by disposal; the slug is still declared + off-path, because the scope refuses an operation that is not. Pages are keyset + cursors bound to their resource and state, 1 to 100 rows, and a cursor carries no + authority. The fence timestamp is the stored microsecond, returned and compared + exactly. +7. **An unknown COMMIT is not reconciled automatically.** A reset and its row commit + together, so a lost answer leaves nothing to repair: the operator inspects, and the + fence of a landed reset has moved, so a repeat answers `409` on the fence. The + runbook says so. +8. **Signals.** `learnstack_platform_operator_recoveries_total{operation,outcome}` + counts each transition as applied, stale fence, not recoverable, not found, + unavailable or commit unknown, so a replay storm is visible. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/glossary.md b/docs/glossary.md index fb892757..4ca3a1f7 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -13,7 +13,8 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | | **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | -| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act runs in the platform scope; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | +| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act and an inspection run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | +| **Operator recovery** | The operator's inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and its two fenced transitions: a **replay** resets one dead-lettered subscriber delivery and a **producer reset** resets one retry-exhausted outbox row, which renews its six-attempt budget. Each transition carries a **fence**, the state the operator read at inspection (for a replay the replay count, the dead-letter instant to the microsecond and the terminal reason; for a reset the attempts and the instant), and is refused with a stale-fence conflict when the row no longer shows it. It writes a MUST audit row on the same transaction. Job recovery and a dashboard do not exist ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md), [runbook](runbooks/operator-recovery.md)). | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | | **Org Admin** | A user with administrative rights inside a single organization within a tenant. | @@ -482,7 +483,7 @@ and recurrence definitions remain empty. | **Integration-event subscription** | One explicitly identified consumer reaction, independent of handler class or assembly. Its stable `{module}.{subscription}.v{N}` ID versions deduplication semantics, not event schema or built-in revision. Renaming needs a migration/replay decision; a handler refactor preserves identity. [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#subscriber-acceptance-and-inbox-ownership) owns the exact grammar. | | **Subscription readiness** | Construction-free Pending, Active or IntentionallyUnsubscribed declaration in `OutboxEventRegistry`, the closed resolver of declared concrete contracts, compatible aliases and retired identities. Any required Pending subscription holds its contract/aliases before acquisition and validation. Active requires a real registered handler; intentional absence is explicit, never inferred from zero discovered handlers. Accepted P02b-2 policy under [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md). | | **Outbox lease** | Paired `locked_by` / `locked_until` fields; the former holds a fresh canonical UUID acquisition token, the latter a database-time expiry. Every transition checks both current token and unexpired lease. Recovery replaces expired ownership before another transition. Stable worker identity confers no ownership. | -| **Dead letter** | Explicit completed terminal state after invalid data or exhausted attempts, distinct from a terminal request or delayed availability. On the producer row, `terminal_reason` requests terminalization and excludes normal publication; only `dead_lettered_at` records completed terminal state. Producer terminal state retains its envelope and commits with MUST audit; subscriber terminal state belongs to its independent delivery ledger and never completes its inbox. P02b-3 Step 4 implements targeted internal subscriber replay; operator routes/permissions and producer reset/replay are separately owned by Phase 03. See [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#producer-dispatch-and-recovery). | +| **Dead letter** | Explicit completed terminal state after invalid data or exhausted attempts, distinct from a terminal request or delayed availability. On the producer row, `terminal_reason` requests terminalization and excludes normal publication; only `dead_lettered_at` records completed terminal state. Producer terminal state retains its envelope and commits with MUST audit; subscriber terminal state belongs to its independent delivery ledger and never completes its inbox. An operator can inspect a dead letter's metadata, replay one dead-lettered subscriber delivery and reset one retry-exhausted producer row, each under a [fence](#operator-recovery) ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md)). See [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#producer-dispatch-and-recovery). | | **`EventTerminalTransition`** | Restricted immutable witness minted only from the successful fenced terminal UPDATE result in its live transaction. It binds actual row identity, acquisition and terminal values to `WriteEventTerminalAsync`; substituting draft tenant/org/event or transaction requires rollback of state and audit. Producer fifth seam implemented in P02b-2 Step 2, with both independent review rounds complete; P02b-3 Step 4 adds the subscriber tuple witness and terminal writer using a validated attempt trace without causal-envelope/payload access. | | **`DeploymentMode`** | Enum (`Development \| SaaS \| Dedicated \| SelfHostedOnline \| SelfHostedAirGapped`) read at the composition root to select provider implementations. Modules never read this enum. | diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index 3171cfdc..4910e829 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -8,7 +8,10 @@ adds the confined terminal-audit seam in P02b-2, not an Audit-module operation. `platform.outbox.dead_letter` and P02b-3's `platform.delivery.dead_letter` belong to [Tenancy's off-path matrix](../tenancy/audit.md). P02b-2 Step 2 implements the producer writer, with both review rounds complete; P02b-3 Step 4 implements -the subscriber writer with both review rounds complete. Phase 03 owns privileged +the subscriber writer with both review rounds complete. P03-9 Step 4 adds the +operator's fenced recovery writer, `platform.delivery.replay` and +`platform.delivery.reset`, on the same off-path matrix +([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Phase 03 owns privileged erasure execution and its bounded caller contract; Phase 11 owns retention purge. diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 026baee0..fb6ccc67 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -146,6 +146,9 @@ unmarked row is one a shipped command already raises. |---|---|---|---| | `outbox_messages` | `platform.outbox.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-2 Step 2's consequential BYPASSRLS terminal transition; state and row commit together through the row-bound fifth audit seam, with stored tenant/org/event identity and SystemActor ([ADR-0046](../../decisions/0046-durable-event-delivery-and-recovery.md)) | | delivery ledger | `platform.delivery.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-3 Step 4's subscriber terminal writer binds stored tenant/org/event/subscription, acquisition token, reason and attempts to the actual fenced transition; ledger and MUST audit commit together through the same restricted fifth seam. It receives no causal-envelope or payload SELECT grant | +| delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation names this slug, with the closed reason `delivery_inspect` and the operator attribution and ticket in `metadata.operator`; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | +| delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | +| `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | | `Tenant` | `tenancy.tenant.create` | **MUST** | The root of a customer's data; its existence is a contractual fact | | `Tenant` | `tenancy.tenant.change_status` `(planned)` | **MUST** | Suspension withdraws access; an operator must be able to say who and when | diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index 91e0e941..f1d4962f 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -111,7 +111,7 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi the widening it needs is an ADR's to make, not a migration's. The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) -is separate and never assignable to a Role. Tenancy owns two keys in it today. +is separate and never assignable to a Role. Tenancy owns four keys in it today. `platform.killswitch.write` authorizes the operator surface to toggle `platform_killswitches`. `platform.tenant.write` authorizes the operator's production tenant provisioning and host mapping @@ -120,8 +120,14 @@ tenant provisioning and host mapping operations whose one source is `PlatformOperator`, run on the application role under the target tenant's ordinary announcement, and share their audit slugs (`tenancy.tenant.create`, `tenancy.organization.create`, `tenancy.hostmapping.write`) -with the seed commands they parallel. Operators hold the keys by configuration -([Standard 19](../../standards/19-permissions.md)). +with the seed commands they parallel. `platform.delivery.read` and +`platform.delivery.write` authorize the operator's inspection of dead-lettered +asynchronous work and its two fenced recovery transitions +([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)): they run in +the platform scope and on the dispatcher's outbox role, not through the pipeline, and +write the off-path slugs `platform.delivery.inspect`, `platform.delivery.replay` and +`platform.delivery.reset` in [Tenancy's audit matrix](audit.md). Operators hold the keys +by configuration ([Standard 19](../../standards/19-permissions.md)). ## Bounded human administration contract diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index 6b574aee..2c8c8ff3 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -12,3 +12,4 @@ begins this directory with the platform operator runbooks; | [Killswitch](killswitch.md) | A capability must be switched off for every tenant during an incident | | [Tenant onboarding](tenant-onboarding.md) | A production tenant must be provisioned, mapped to a host and given its first administrator, or an administrator must be recovered | | [Identity issuer rebind](identity-issuer-rebind.md) | The tenant identity provider keeps its realm and users but changes address, and the stored issuer must follow without re-keying anyone | +| [Operator recovery](operator-recovery.md) | An event or delivery is dead-lettered, a job is quarantined, and an operator must inspect it or reset one delivery or outbox row under a fence | diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index e6b94b8a..bbbd3851 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -42,7 +42,9 @@ The registered permissions are `platform.killswitch.write` `platform.identity_authority.admin`, which the offline [issuer rebind](identity-issuer-rebind.md) tool checks against the same grants. That tool reads the same `PlatformOperator__*` settings from its own environment and is not -an API route. +an API route. `platform.delivery.read` and `platform.delivery.write` are the two +permissions of [operator recovery](operator-recovery.md): the first for the inspection +routes and the second for a replay or a producer reset. A Self-Hosted issuer other than the shipped realm must issue access tokens that meet the profile below. If it cannot, no operator can act, by design. @@ -177,7 +179,8 @@ the response. |---|---| | `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate; `operation` is the audit slug, for example `tenancy.killswitch.toggle` | | `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `request_aborted`, `metadata_stale`, `metadata_unavailable`, `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_algorithm`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `invalid_ticket`, `missing_permission`, `unknown_operation`, `invalid_witness` | -| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by the platform scope, so the killswitch act only | +| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by an operator act: the killswitch toggle in the platform scope, and a replay or a reset on the dispatcher's outbox role | +| `learnstack_platform_operator_recoveries_total{operation,outcome}` | Recovery transitions by how they ended; see the [recovery runbook](operator-recovery.md#signals) | | `learnstack_platform_operator_acts_total{operation,outcome}` | Onboarding acts by how they ended (`applied`, `replayed`, `refused`, `failed`); see the [onboarding runbook](tenant-onboarding.md#signals) | | `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | | `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs, new keys are not learned; a fetch that failed is not retried for 30 seconds, and once the keys held are more than 15 minutes old with a later fetch failed, every operator is refused (`metadata_stale`) | diff --git a/docs/runbooks/operator-recovery.md b/docs/runbooks/operator-recovery.md new file mode 100644 index 00000000..2847b325 --- /dev/null +++ b/docs/runbooks/operator-recovery.md @@ -0,0 +1,158 @@ +# Operator recovery of asynchronous work + +How an operator inspects dead-lettered events and quarantined jobs, and resets one +dead-lettered delivery or outbox row under a fence. Decided in +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md). There is **no +dashboard** and **no job recovery**: this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/asynchronous-work/outbox-messages` | Lists dead-lettered or terminal-requested outbox rows | `platform.delivery.read` | +| `GET /api/platform/v1/asynchronous-work/event-deliveries` | Lists dead-lettered or terminal-requested subscriber deliveries | `platform.delivery.read` | +| `GET /api/platform/v1/asynchronous-work/quarantined-jobs` | Lists quarantined jobs with their reservation occupancy | `platform.delivery.read` | +| `POST .../event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay` | Resets one dead-lettered delivery (a **replay**) | `platform.delivery.write` | +| `POST .../outbox-messages/{tenantId}/{eventId}/reset` | Resets one retry-exhausted outbox row (a **producer reset**) | `platform.delivery.write` | + +Authentication, the token profile and how a grant is given are in [Platform operator +access](operator-access.md). The served operator document, `platform-v1`, is the +contract for these routes, and it is the only client there is. + +A reset changes a row. An inspection changes nothing: it reads metadata only, and it +cannot read an event body, a job's parameters or plan, a causal id or a lease token, +because the database refuses those columns to the platform role. + +## What is not here + +- **Job recovery.** A quarantined job stays frozen, keeps its reservation and keeps the + `jobs` health check unhealthy. Nothing here requeues, retries, releases or re-arms + it, because the only proof that would make that safe is a provider's fence or the + termination of the process that started the effect, and no adapter can supply one + today. The inspection shows the job and how many reservations hold capacity; it is an + operator's evidence for an escalation, not a remedy. +- **A recurrence skip, pause or resume.** None exists. +- **The Hangfire dashboard.** `/admin/hangfire` answers 404 in every deployment mode. +- **A privileged subscription.** A delivery that belongs to one is refused. + +## When to look + +- `learnstack_outbox_deadletter_total` or `learnstack_inbox_deadletter_total` rises, or + the `jobs`, `outbox` or `delivery` health check goes unhealthy. +- A tenant reports an effect that never happened and the audit trail shows a + `platform.outbox.dead_letter` or `platform.delivery.dead_letter` row for it. + +## Inspect + +Each page is one entered platform scope, so each page writes one +`platform.admin_scope.enter` audit row naming `platform.delivery.inspect`, with your +attribution and ticket. Pass the ticket as `?ticket=`: 1 to 64 letters, digits or +`.` `_` `:` `/` `#` `-`. + +```sh +curl -s -H "Authorization: Bearer $TOKEN" \ + "$API/api/platform/v1/asynchronous-work/outbox-messages?state=dead_lettered&limit=20&ticket=CHG-123" +``` + +- `state` is `dead_lettered` (default) or `terminal_requested`. A **terminal requested** + row has a terminal reason recorded and the commit of its dead-letter not yet made: its + state is shown and it is **not actionable**. It becomes dead-lettered by itself, or it + does not. +- `limit` is 1 to 100 (default 20, larger values are clamped). The answer holds `items` and a `pageInfo` + with `nextCursor` and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs + to the route and state that issued it. +- Each row carries `eventType` as the registry's label (never stored text) and + `actionable`. Treat `actionable` as advice: the transition checks again. +- **The fence travels with the row.** A delivery shows `replayCount`, `deadLetteredAt`, + `terminalReason`; an outbox row shows `attempts` and `deadLetteredAt`. + `deadLetteredAt` has microsecond precision: send it back **exactly as returned**. + +## Choose: replay or reset + +- **Replay** resets one *delivery*: one subscription of one event. Use it when a + subscriber's handler failed for a reason that is now fixed, or its subscription became + Active. The completed siblings, the inbox row, the producer row and every other event + are untouched. +- **Producer reset** resets one *outbox row* whose terminal reason is `retry_exhausted`: + a burst of dispatch failures used up its six attempts. Use it when the event was never + published. It **renews the six-attempt budget**, so a row that fails for a lasting + reason fails six more times and is dead-lettered again with a new audit row. The reset + reaches the subscriptions that have no delivery row yet, and a publication that + already reached a subscriber is absorbed by the event's stable identity; a delivery + that already ended terminal needs its own replay. +- **Neither** if the reason is `invalid_envelope`: the stored envelope is immutable and + cannot become valid. A reason of `unknown_type` or `retired_type` follows the registry + now: an event the registry still does not know, or has retired, is refused. + +## Act + +Send the fence read at inspection, and a ticket if you have one: + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/asynchronous-work/event-deliveries/$TENANT/$SUBSCRIPTION/$EVENT/replay" \ + -d '{"replayCount":0,"deadLetteredAt":"2026-10-01T12:00:00.123456Z","terminalReason":"retry_exhausted","ticket":"CHG-123"}' +``` + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/asynchronous-work/outbox-messages/$TENANT/$EVENT/reset" \ + -d '{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.123456Z","ticket":"CHG-123"}' +``` + +| Answer | Meaning | +|---|---| +| `200`, `outcome: applied` | The row was reset and its MUST audit row committed with it. `countAfter` is the new replay count, or zero attempts | +| `409`, `errors.fence` = `lockey_stale_fence` | The row no longer shows the fence you sent: the dispatcher, another operator or a retry moved it. Nothing changed and nothing was written. **Inspect again** and decide again | +| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one a reset may act on: processed, leased, `invalid_envelope`, a reason a reset refuses, a subscription that is no longer Active, an event type the registry no longer knows, or a tenant that is not serving (not Trial or Active, or deleted). Nothing changed | +| `404` | No such row for that tenant | +| `403` | You hold no `platform.delivery.write` grant. Nothing was opened | +| `400` | The route, the body or the ticket is malformed. A refusal at the gate carries no per-field errors | +| `503`, `audit_unavailable` | The MUST row could not be written, so nothing changed. Retry after the delay | +| `503`, `dependency_unavailable` | The outbox role's connection or its one operator lane was unavailable. Nothing changed. Only one operator call runs per store at a time; retry after the delay | +| `503`, `outcome_unknown` | The commit's answer was lost. It **may have landed**. **Inspect the row before repeating**: a landed reset shows an advanced `replayCount` (or `attempts` of zero), and a repeat of the same request would answer `409` `lockey_stale_fence` | + +An applied replay makes the delivery due at once; the dispatcher claims it like any +other. + +## Check it worked + +1. Inspect the row: it is no longer in the dead-lettered list (an applied reset moves it + back to the ordinary queue). +2. Watch the dispatcher claim it: `learnstack_delivery_pending_count` or + `learnstack_outbox_pending_count` moves, and the executor runs the handler. A reset + row that fails for a lasting reason is dead-lettered again after its attempts, with a + second `platform.*.dead_letter` row. Fix the cause before you reset again. +3. Read the audit trail. The row is in the **tenant's** trail (it names the real event + tenant) with no actor, the operation `platform.delivery.replay` or + `platform.delivery.reset`, the reason `delivery_replay` or `delivery_reset`, your + attribution in `metadata.operator` and the fence before and after in + `metadata.fence`. The ticket is not on it, because the tenant can read it. + +## Signals + +`learnstack_platform_operator_recoveries_total{operation,outcome}` counts every +transition by `applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable` +and `commit_unknown`. A rising `stale_fence` is two operators, or a script, replaying +the same rows. `learnstack_platform_operator_audit_failures_total` counts the refusals +for an audit failure, and the admission and refusal counters are in [Platform operator +access](operator-access.md#signals). + +## Limits + +- **Erasure.** The rule that the tenant is serving is the guard until the erasure work + defines what a replay may reach after a tenant's data is erased; it re-verifies these + transitions. Do not reset anything for a tenant that is being erased. +- **The invitation path.** A stuck or unknown outbound invitation email is a *job*, and + nothing here releases it. Reissuing an invitation helps only while the tenant has a + free slot; it neither reconciles nor releases the old effect, and four unresolved + effects can hold every slot with no operator remedy. +- **Capacity.** The operator lane is one connection per store, so replays are one at a + time. A burst is slow on purpose. + +## Not recoverable here + +- A quarantined job, a held reservation, a recurrence. +- An `invalid_envelope` delivery. +- A reset of a row that was processed, or an event the registry no longer knows. +- A dashboard. diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 4445e548..2efa5a2b 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -1112,12 +1112,12 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | `platform_killswitches` | `SELECT` | `SELECT, INSERT, UPDATE, DELETE` | — | | `idempotency_keys` | `SELECT, INSERT, UPDATE` | `SELECT, DELETE` | — | | `inbox_messages` | `SELECT`, `INSERT (tenant_id, subscription_id, event_id)` | — | — | -| `event_deliveries` | `SELECT`, acceptance-column `INSERT`, `UPDATE (processed_at)`; exact lists [below](#inbox) | — | routing/status-column `SELECT`, scheduling/status-column `UPDATE`; exact lists [below](#inbox) | -| `outbox_messages` | `SELECT, INSERT` | `SELECT, DELETE` | `SELECT`, `UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at)` (P02b-2 Step 1) | -| `background_jobs` | RLS `SELECT`; envelope `INSERT`, admission/checkpoint `UPDATE` | — | Routing/status `SELECT, UPDATE` | +| `event_deliveries` | `SELECT`, acceptance-column `INSERT`, `UPDATE (processed_at)`; exact lists [below](#inbox) | inspection-metadata column `SELECT` ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)) | routing/status-column `SELECT`, scheduling/status-column `UPDATE`; exact lists [below](#inbox) | +| `outbox_messages` | `SELECT, INSERT` | `DELETE`, and `SELECT` of twelve inspection-metadata columns only ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md); the earlier table-wide `SELECT` is revoked) | `SELECT`, `UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at)` (P02b-2 Step 1) | +| `background_jobs` | RLS `SELECT`; envelope `INSERT`, admission/checkpoint `UPDATE` | 27 metadata columns `SELECT`, no parameter, plan, trace, causal or capability column | Routing/status `SELECT, UPDATE` | | `background_job_attempts` | RLS `SELECT`; receipt `INSERT`, evidence `UPDATE` | — | Enumerated metadata `SELECT`, excluding outcome DTO | | `background_job_capacity` | RLS `SELECT, INSERT`; immutable-column `UPDATE` for row locking | — | `SELECT` | -| `background_job_reservations` | RLS `SELECT, INSERT`; positive-evidence release `UPDATE` | — | `SELECT` | +| `background_job_reservations` | RLS `SELECT, INSERT`; positive-evidence release `UPDATE` | `SELECT` of every column, for occupancy | `SELECT` | | `background_job_recurrences` | — | — | Manifest `INSERT`, control `SELECT, UPDATE` | | `background_job_occurrences` | — | — | Slot `INSERT`, control `SELECT, UPDATE` | | `background_job_recipients` | RLS `SELECT`; child receipt `UPDATE` | — | Route `INSERT`, routing `SELECT, UPDATE` | @@ -1645,7 +1645,10 @@ CREATE POLICY outbox_messages_isolation ON outbox_messages -- DELETE; status transitions belong to the dispatcher and purging belongs to the -- audited platform scope. GRANT SELECT, INSERT ON outbox_messages TO learnstack_app; -GRANT SELECT, DELETE ON outbox_messages TO learnstack_platform; +GRANT DELETE ON outbox_messages TO learnstack_platform; +GRANT SELECT (id, tenant_id, organization_id, occurred_at, type, processed_at, attempts, + last_error, available_after, locked_until, terminal_reason, dead_lettered_at) + ON outbox_messages TO learnstack_platform; GRANT SELECT ON outbox_messages TO learnstack_outbox_admin; GRANT UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at) @@ -1836,6 +1839,9 @@ CREATE INDEX ix_event_deliveries_recovery CREATE INDEX ix_event_deliveries_terminal ON event_deliveries (available_after, occurred_at, event_id, tenant_id, subscription_id) WHERE processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL; +CREATE INDEX ix_event_deliveries_dead_lettered + ON event_deliveries (dead_lettered_at, tenant_id, subscription_id, event_id) + WHERE dead_lettered_at IS NOT NULL; ALTER TABLE event_deliveries ENABLE ROW LEVEL SECURITY; ALTER TABLE event_deliveries FORCE ROW LEVEL SECURITY; @@ -1911,6 +1917,10 @@ GRANT SELECT (tenant_id, subscription_id, event_id, organization_id, occurred_at GRANT UPDATE (attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at, replay_count, replayed_at) ON event_deliveries TO learnstack_outbox_admin; +GRANT SELECT (tenant_id, subscription_id, event_id, organization_id, occurred_at, + type, processed_at, attempts, last_error, available_after, locked_until, + terminal_reason, dead_lettered_at, replay_count, replayed_at) + ON event_deliveries TO learnstack_platform; ``` The app acceptance INSERT excludes all scheduling/completion/terminal columns; @@ -4169,6 +4179,15 @@ GRANT INSERT (id, occurrence_id, tenant_id, organization_id, recurrence_key, rev ON background_job_recipients TO learnstack_outbox_admin; GRANT UPDATE (available_after, ownership_token, ownership_until, skipped_at, skipped_reason, last_error, quarantined_at) ON background_job_recipients TO learnstack_outbox_admin; +-- ADR-0103: the platform role reads job metadata for operator inspection through named columns only. +GRANT SELECT (id, tenant_id, organization_id, definition_key, profile, queue, capacity_group, + original_due_at, created_at, phase, normal_attempts, finalize_attempts, available_after, + ownership_kind, ownership_until, attempt_deadline, probe_after, unsuccessful_probes, last_error, + quarantine_reason, terminal_reason, processed_at, dead_lettered_at, finalization_status, + finalization_reason, business_finalization_incomplete, wake_generation) + ON background_jobs TO learnstack_platform; +GRANT SELECT (tenant_id, capacity_group, job_id, attempt_id, reserved_at, released_at, release_reason) + ON background_job_reservations TO learnstack_platform; REVOKE ALL ON FUNCTION public.fn_background_job_no_delete() FROM PUBLIC; @@ -4585,21 +4604,25 @@ driver's later no-op into cleanup evidence. The dispatch and bridge stores retain concrete connections and disposal tasks on connection-cleanup failure and seal later acquisitions. Each messaging store has -two fixed ownership slots for terminal-COMMIT reconciliation; the bridge has one -serialized SQL slot. These witnesses concern physical-source release, not all +two fixed ownership slots for terminal-COMMIT reconciliation and a third, reserved +for the operator recovery owner of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), +so an operator's reset can never take the slot the dispatcher's own reconciliation +needs and a second concurrent operator call is refused as unavailable; the bridge +has one serialized SQL slot. These witnesses concern physical-source release, not all application callbacks or private driver tasks. Failed opens rely on the pinned driver's qualified ordinary unwind; an arbitrary driver-cleanup fault is not a release guarantee. `BackgroundJobPhysicalCapacity` calculates the current Step 8 floor as -`W + 4P + 2C + 18 + U = 2W + 8P + 2C + 18`, where `W` is total workers, `P` is +`W + 4P + 2C + 20 + U = 2W + 8P + 2C + 20`, where `W` is total workers, `P` is pools, `C` is control pools and `U = W + 4P` is retained invocation owners. Each invocation issues at most one privileged routing, recovery acquisition, confirmation or checkpoint-history SQL operation at a time, including actual cleanup. A clean unavailable history retry follows cleanup in that same slot; it does not add another simultaneous checkout. The original eleven covers two shared components, four bridge calls, one bridge -SQL lane and two depth-two messaging lanes. Step 5 adds one batch-renewal slot, +SQL lane and two depth-two messaging lanes; the operator recovery owner adds one +lane in each messaging store, which makes thirteen. Step 5 adds one batch-renewal slot, one recovery slot plus its fresh-probe slot, and one terminal slot plus its fresh-probe slot. Step 8 adds one serialized recurrence SQL lane and one separately owned native recurring-manager call. The latter reuses its dedicated provider @@ -4607,7 +4630,7 @@ connection for its stock lock and write transaction. A held native call cannot consume another recurrence SQL slot. Failed cleanup retains the concrete owner and seals that lane; probes do not recursively acquire another probe. The default topology requires -**52**; the maximum valid topology requires **158**. Pooled startup refuses a +**54**; the maximum valid topology requires **160**. Pooled startup refuses a lower `MaxPoolSize` before bootstrap, using settings captured from the same immutable configuration as the source. Nonpooling remains allowed with the same owner bounds; its positive `MaxPoolSize` is not a physical-checkout cap. @@ -4621,6 +4644,7 @@ peak. Its complete acquisition ledger is: | `4P` | Per-generation metadata heartbeat, watchdog, cancellation watcher and lifecycle allowance; retained cleanup still belongs to that one generation. | | `2C` | Delayed and recurring schedulers, each with parallelism one and sequential reuse of its outer distributed-lock connection. | | Original eleven | Shared expiration and fetched-job heartbeat; four bridge native calls plus serialized SQL; two concrete slots in each messaging store. | +| Two operator lanes | The third slot of each messaging store, reserved for the operator recovery owner ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)); a second concurrent operator call on a store is refused and does not wait. | | Five control slots | One batch renewal, control/recovery plus fresh probe, terminal plus fresh probe; unconfirmed cleanup seals each lane. | | Two recurrence slots | One serialized SQL flight and one native manager, including actual return and cleanup. | | `U` | One privileged routing/recovery/history/status flight per admitted invocation, including retained cleanup; application work uses the separate source. | @@ -4652,7 +4676,7 @@ including live work and unresolved receipt history; it does not add stock worker slots. Adding control pools adds neither terminal nor recipient application owners. External Prepare, read, Arm, Outcome, recovery checkpoints and fresh Finalize use the same sequential main/auxiliary inventory; their phase count is not a -connection multiplier. The facade fixture for privileged maximum 158 +connection multiplier. The facade fixture for privileged maximum 160 has eight pools of four workers, six of them control, and requires 42 application connections. Other worker distributions can share the same privileged maximum with a different application floor; neither maximum substitutes for calculating @@ -6456,3 +6480,65 @@ a killed session, a lost commit acknowledgement and a reconciliation that waits) `IdentityAuthorityRebindToolTests` (the offline tool as a child process). The census counts are in `GlobalIdentitySchemaTests` (thirty functions, sixteen definers, thirty triggers) and the head pin in `MigrationRollbackTests`. + +## Operator recovery storage + +**Derives from:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and its +Amendment 1. Operator inspection reads metadata through the platform role's column grants, and the two +fenced transitions run on the dispatcher's outbox role. The canonical SQL of every grant and index +named here is in the [Outbox](#outbox), [Inbox](#inbox) and Background jobs blocks, which migration +tests compare with the applied schema, and the head of the Platform chain is pinned in +`MigrationRollbackTests`. + +### The platform role's inspection grants + +`learnstack_platform` holds `SELECT` on named columns of four tables and nothing wider: twelve columns +of `outbox_messages`, fifteen of `event_deliveries`, twenty-seven of `background_jobs` and every column +of `background_job_reservations`. It never reads `payload`, `metadata`, `correlation_id`, +`causation_id`, `actor_user_id`, `topic`, `partition_key`, `locked_by`, a job's `parameters`, `plan`, +`plan_fingerprint`, `traceparent`, a causal column, `operation_id` or an ownership or bridge token, so a +statement that names one is refused by PostgreSQL itself. The role kept `DELETE` on `outbox_messages` for +the retention purge of [Phase 11](../roadmap/phase-11-production-hardening.md), and the table-wide +`SELECT` it held beside it was revoked, because a column grant next to a table grant excludes nothing. +Column privileges are read from `information_schema.column_privileges`, as for every column-grant table. +Two partial indexes, `ix_outbox_messages_dead_lettered` and `ix_event_deliveries_dead_lettered`, serve the +dead-lettered scan the inspection pages by keyset. The migration is forward-only. + +### The two transitions + +Both run on the outbox role, which already holds the column `UPDATE` grants they need, the lifecycle +`SELECT` of `tenants` and `INSERT` on `audit_log`: no write grant was added. Each locks one row with +`FOR UPDATE`, compares the fence the operator read, checks the state, and updates under the same predicate +with `RETURNING old.*` and `new.*`, so the witness is built from what the statement did and the row is +written on the same transaction before `COMMIT`. + +- **Replay** fences `(replay_count, dead_lettered_at, terminal_reason)` on one + `(tenant, subscription, event)` row of `event_deliveries`. It refuses a processed or leased row, the reason + `invalid_envelope`, a subscription that is not an Active ordinary one of the stored type and a tenant that is + not serving, clears the terminal fields and the lease, resets attempts, makes the row due, and adds one to + `replay_count`. The inbox row, the siblings and the producer row are untouched. +- **Producer reset** fences `(attempts, dead_lettered_at)` on one `outbox_messages` row and acts only on + `terminal_reason = 'retry_exhausted'` of a row not processed or leased whose stored type the registry still + knows. It clears the terminal fields, `last_error` and the lease, sets `attempts` to zero and makes the row + due. It writes no delivery row. + +The timestamp of a fence is `timestamptz` to the microsecond. It is carried and compared exactly, and a test +presents a fence one microsecond off. + +### The operator lane + +Each messaging store has two slots for the dispatcher's own SQL owner and its uncertain-COMMIT reconciliation +and a third, reserved for the operator owner. The operator never takes the dispatcher's slots, and a second +concurrent operator call on a store is refused. The lanes are two of the thirteen messaging and bridge slots in +the [capacity ledger](#shared-dispatcher-source-lifetime-and-capacity), which is 54 for the default topology +and 160 for the maximum. + +### Proof + +Real PostgreSQL as each role: `DeliveryDispatchStoreTests` and `OutboxDispatchStoreTests` (the current fence +applies, every stale variant including one microsecond refuses and changes nothing, each refused state, a +tenant that is not serving, a forced audit failure rolling the change back, an admission for another operation +or a stale or spent one, a busy operator lane that leaves the dispatcher's slots alone, a lost commit +acknowledgement, and every other row byte-identical), `DeliveryInspectionTests` (pages, cursors, the entry +row, and the columns the platform role cannot select) and `PlatformOperatorHttpTests` (the routes, their +statuses and the contract). diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index 40ab967e..d69d7012 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -478,6 +478,7 @@ backend treat business rejections as system failures. | `learnstack_platform_operator_admissions_total` | counter | outcome (`admitted`, `refused`), operation (a registered slug or `unknown`) | | `learnstack_platform_operator_refusals_total` | counter | cause (a closed set: token, profile and gate causes; [runbook](../runbooks/operator-access.md#signals)) | | `learnstack_platform_operator_results_total` | counter | operation | +| `learnstack_platform_operator_recoveries_total` | counter | operation (`platform.delivery.replay`, `platform.delivery.reset`), outcome (`applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable`, `commit_unknown`; [runbook](../runbooks/operator-recovery.md#signals)) | | `learnstack_platform_operator_audit_failures_total` | counter | operation | | `learnstack_platform_operator_metadata_failures_total` | counter | none | | `learnstack_identity_rebind_runs_total` | counter | outcome (`applied`, `already_applied`, `unknown`, or a `refused_` class; [runbook](../runbooks/identity-issuer-rebind.md#when-it-refuses)) | diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index b0921302..ca9e0ae6 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -233,7 +233,13 @@ will raise them — which this standard requires it to do. ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 8), are `(off-path)` for the same reason one step further: they are written by an offline tool on its own role through two witness-bound methods, under the platform sentinel, with no actor and the - ticket in `metadata.operator`. + ticket in `metadata.operator`. The operator recovery operations of + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) are + `(off-path)` too: `platform.delivery.inspect` is the operation the platform scope's + entry row names, and `platform.delivery.replay` and `platform.delivery.reset` are + written on the dispatcher's outbox-role transaction through one witness-bound method, + under the real event tenant, with no actor, the operator attribution and the fence in + `metadata`, and no ticket, because a tenant can read the row. ## Baseline Coverage (LearnStack Core Modules) diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 6d2e4fab..8fd4d24c 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write` and `platform.identity_authority.admin` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read` and `platform.delivery.write` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | @@ -107,6 +107,8 @@ not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authori | `platform.tenant.write` | `tenancy.tenant.create` (tenant provisioning), `tenancy.hostmapping.write` (host mapping) | P03-9 Step 2 | | `platform.tenant_bootstrap.write` | `identity.role.initialize`, `identity.membership.create_first_admin`, `identity.membership.recover_admin` | P03-9 Step 2 | | `platform.identity_authority.admin` | `identity.authority.rebind` (the controlled issuer rebind, an offline tool and not a route) | P03-9 Step 3 | +| `platform.delivery.read` | `platform.delivery.inspect` (metadata-only inspection of dead-lettered work and quarantined jobs, in the platform scope) | P03-9 Step 4 | +| `platform.delivery.write` | `platform.delivery.replay`, `platform.delivery.reset` (the two fenced transitions, on the dispatcher's outbox role) | P03-9 Step 4 | The five onboarding acts of [ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the @@ -118,7 +120,11 @@ grant is evaluated by the gate on every act, never cached across acts. The rebin and not a route: the scope refuses an operation that needs no platform role, and the executor runs only the closed catalog of five onboarding acts, which refuses the rebind operation by construction (`PlatformOperatorActCatalog`). The offline tool that consumes -the admission validates the same token and evaluates the same grant. +the admission validates the same token and evaluates the same grant. The two recovery +transitions of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) +are likewise not pipeline acts: each operation records where it runs +(`PlatformOperationExecutor`: the pipeline, the platform scope, the offline tool or the +recovery owner), and the catalog admits only the first. Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index a36b757c..cd05de63 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -793,6 +793,15 @@ actual routing/terminal identity and a validated attempt trace; it adds no causal-envelope or payload read to the bypass scheduler. See [Audit Coverage](18-audit-coverage.md#required-behaviours). +The dispatcher's two stores have a second writer, the operator recovery owner of +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md): a fenced +subscriber replay and a narrow producer reset, each behind an operator admission and +each writing its MUST row through a sibling witness (`OperatorRecoveryTransition`) on +the same outbox-role transaction. The owner holds no credential: it is a DI consumer of the two +stores, whose third connection slot is reserved for it, and `IOperatorRecovery` is the +only port the recovery routes hold. The inspection that precedes a reset runs in the +platform scope on column grants and writes no change. + ## Background Jobs and Hangfire Accepted [ADR-0047](../decisions/0047-transactional-background-job-runtime.md) diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 85b5e007..7b7d9158 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**386 test methods run in +**389 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**290 rules in this catalogue are Implemented, and 172 of them are in that assembly.** +**292 rules in this catalogue are Implemented, and 174 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -3781,11 +3781,12 @@ which decides identity, multiplicity, capture and classification; `The_AppendOnly_Sweep_Can_Actually_Fail`, that checks the pattern against the shapes it must catch and the shapes it must not, because with no offending statement anywhere the sweep passes whether it works or matches nothing; and a reflection check, - `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly thirteen + `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly fourteen write methods and no update: the event/job seams ship in Phase 02b, ADR-0072's two global seams in P03-1 Step 3, the two trusted authorization seams in P03-2, the - operator result seam of ADR-0101 in P03-9 Step 1 and the two controlled-rebind seams - of ADR-0104 in P03-9 Step 3. None + operator result seam of ADR-0101 in P03-9 Step 1, the two controlled-rebind seams + of ADR-0104 in P03-9 Step 3 and the operator recovery seam of ADR-0103 in P03-9 + Step 4. None of the three sanctioned redaction sites exists yet — they land in Phase 03 and Phase 11 — so the exemption set ships with the rule **empty**, as exact paths: the first site to land adds its own path, so it is exempted by name rather than the pattern @@ -5988,12 +5989,55 @@ structural test proves — and what it does not. - **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3). - **Phase:** P03-9. +#### `Operator_Recovery_Audit_Identity_Is_Row_Bound` + +- **Asserts:** by IL, over every production assembly, that `OperatorRecoveryTransition` + is sealed with one private live-reader constructor, readonly state and getter-only + properties, in an assembly with no friend; that its nested `MintingSource` is public, + abstract and protected-constructed with exactly the two protected static factories + (`FromReplayUpdate`, `FromResetUpdate`); that the only subtypes are the private sealed + `RecoveryMint` classes nested in `DeliveryDispatchStore` and `OutboxDispatchStore`; that + the factories' only callers are those classes' two wrappers, whose only callers are the + stores' `ReplayCoreAsync` and `ResetCoreAsync`; that the witness constructor's only + callers are the factories; and that `IAuditStore.WriteOperatorRecoveryAsync` is declared + on the port and implemented by `PostgresAuditStore` alone, with the two stores' + `WriteRecoveryRowAsync` as its only callers. Its companion + `Operator_recovery_census_detects_extra_derivers_constructors_and_callers` plants a + second subtype, an extra mint helper, a direct constructor call, an extra writer caller + and a helper on the sanctioned store, and requires the same detector to reject each. +- **Why it matters:** the witness is evidence that a row was reset under a fence in a live + transaction, and it binds the audit row to the admitted operation, the operator and the + fence. A second way to make one, or to write the row, is a second way to forge that + evidence. The terminal witness could not carry an operator, so this is a sibling, not + a third factory on it. +- **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 5 + and its Amendment 1. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`OutboxDispatchConventionTests`, P03-9 Step 4). +- **Phase:** P03-9. + +#### `Only_The_Recovery_Routes_And_Their_Owners_Name_The_Operator_Recovery_And_Inspection_Ports` + +- **Asserts:** the files, by their path under `backend/src`, that name `IOperatorRecovery` + are exactly the port, its one implementation, the outbox composition and the recovery + routes, and the files that name `IDeliveryInspection` are exactly the port, its + implementation, the persistence composition and the recovery routes. Adding a caller + is a deliberate edit here, with its denied proof. +- **Why it matters:** the two transitions are the dispatcher's second writer and the + inspection reads across tenants; a handler that held either port would reach a reset or + a cross-tenant read from a request path the operator gate does not guard. +- **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 4. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 4). +- **Phase:** P03-9. + #### `Only_The_Operator_Services_Hold_The_Platform_Scope` - **Asserts:** the files, by their path under `backend/src`, that name `IPlatformAdminScope` are exactly the interface, the scope, the persistence composition and the operator services that perform an admitted act (today the - killswitch toggle). Adding a service is a deliberate edit here, with its denied proof. + killswitch toggle and the delivery inspection). Adding a service is a deliberate + edit here, with its denied proof. - **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a tenant request path. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 55cdd47d..5585493a 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -83,6 +83,7 @@ "LearnStack.Tests.Integration.Database.DatabaseRoleTests", "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests", "LearnStack.Tests.Integration.Database.DeliveryExecutionTests", + "LearnStack.Tests.Integration.Database.DeliveryInspectionTests", "LearnStack.Tests.Integration.Database.DeliveryProcessorTests", "LearnStack.Tests.Integration.Database.DomainEventProductionTests", "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests", From 708635ab2c30e2a45ad2fd3fd98167ed959d6024 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 07:03:32 +0300 Subject: [PATCH 18/28] fix(platform): close P03-9 step 4 review round 1 findings Three independent reviewers read the operator recovery step. The findings that survived verification are fixed: - the unknown-commit 503 now carries its own status in the body: the reason is a field of dependency_unavailable, not a new top-level code the closed status map answers 500 for - a fault after the COMMIT was sent is reported as an unknown outcome, a missing lifecycle projection is a configuration error, an inspection's database fault is a retryable 503, and the cause of every 503 is logged and never returned - a limit of zero and a state on the jobs list are refused naming the parameter, and last_error is shown only in the dispatcher's descriptor shape - the integration fixtures derive the connection floor from the production manifest instead of repeating the old literal - tests added for the permission pair, the real owner and its counters, the witness refusing each substituted field, the cursor scope, equal-instant paging, job occupancy, the outbox column grants and the outbox operator lane; twenty-six mutations of the step's guards are killed - ADR-0103 carries inline errata and Amendment 1 items 6, 7, 9 and 10; the runbooks, Standards 05, 18, 20, 21, the OpenAPI texts and the delivery log say what the code does Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 75 +++++++- .../PlatformOperatorEndpoints.Recovery.cs | 88 +++++++-- .../DeliveryDispatchStore.Operator.cs | 27 ++- .../Messaging/OutboxDispatchStore.Operator.cs | 27 ++- .../PlatformOperator/DeliveryInspection.cs | 32 +++- .../Audit/IAuditStore.cs | 2 +- .../Platform/IOperatorRecovery.cs | 10 +- .../DeliveryDispatchBoundaryTests.cs | 2 +- .../OperatorRecoveryBoundaryTests.cs | 15 ++ .../OutboxDispatchBoundaryTests.cs | 2 +- .../OutboxDispatchObservationTests.cs | 6 + .../BackgroundJobCapacity.cs | 15 ++ .../BackgroundJobProductionManifestTests.cs | 2 +- ...ackgroundJobPositiveSdkTests.NativeFlow.cs | 6 +- ...groundJobPositiveSdkTests.RecoveryWakes.cs | 6 +- ...undJobPositiveSdkTests.SourceContention.cs | 6 +- ...dJobRuntimeFacadeTests.AuxiliaryCleanup.cs | 4 +- ...ackgroundJobRuntimeFacadeTests.Business.cs | 8 +- ...JobRuntimeFacadeTests.CapacityAdmission.cs | 2 +- ...meFacadeTests.CapacityAdmissionRollback.cs | 2 +- ...obRuntimeFacadeTests.CapacityCheckpoint.cs | 2 +- ...ndJobRuntimeFacadeTests.CapacityCleanup.cs | 4 +- ...ndJobRuntimeFacadeTests.CapacityControl.cs | 2 +- ...ndJobRuntimeFacadeTests.CapacityNoStart.cs | 2 +- ...roundJobRuntimeFacadeTests.CapacityStop.cs | 4 +- ...dJobRuntimeFacadeTests.CapacityTakeover.cs | 4 +- ...imeFacadeTests.CombinedPhysicalCapacity.cs | 8 +- ...roundJobRuntimeFacadeTests.CommitFaults.cs | 4 +- ...dJobRuntimeFacadeTests.ComposedLifetime.cs | 6 +- ...ndJobRuntimeFacadeTests.ControlFailures.cs | 2 +- ...ndJobRuntimeFacadeTests.HeartbeatCutoff.cs | 2 +- ...ackgroundJobRuntimeFacadeTests.Lifetime.cs | 8 +- .../Database/DeliveryDispatchStoreTests.cs | 141 ++++++++++++++ .../Database/DeliveryInspectionTests.cs | 148 +++++++++++++- .../OperatorRecoveryAuditDecorator.cs | 47 +++++ .../Database/OperatorRecoveryMeterProbe.cs | 51 +++++ .../Database/OutboxDispatchStoreTests.cs | 181 ++++++++++++++++++ .../Database/PostgresFixture.cs | 2 +- .../PlatformOperatorHttpTests.cs | 167 ++++++++++++++-- ...undJobRuntimeProductionCompositionTests.cs | 8 +- .../MultiTenancy/PlatformAdminGateTests.cs | 24 +++ ...-operator-recovery-of-asynchronous-work.md | 58 ++++-- docs/modules/audit/audit.md | 6 +- docs/modules/tenancy/audit.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 112 ++++++++++- docs/runbooks/operator-access.md | 3 +- docs/runbooks/operator-recovery.md | 50 +++-- docs/standards/05-database.md | 113 ++++++----- docs/standards/18-audit-coverage.md | 5 +- docs/standards/20-infrastructure-stack.md | 8 +- .../21-architecture-tests-catalogue.md | 7 + 51 files changed, 1324 insertions(+), 194 deletions(-) create mode 100644 backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 957743fe..02cd640b 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Nodes; using LearnStack.Api.PublicReads; using Microsoft.AspNetCore.OpenApi; using Microsoft.OpenApi; @@ -60,7 +61,12 @@ public async Task TransformAsync( [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, document)] = [], }, ]; - DescribeResponses(document, operation); + DescribeResponses(document, operation, method == HttpMethod.Get); + if (method == HttpMethod.Get) + { + DescribeInspectionParameters(operation); + } + // An inspection is a read and carries no body. if (operation.RequestBody is null && method != HttpMethod.Get) { @@ -91,11 +97,67 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum _ => throw new InvalidOperationException("An operator operation declares no request body: " + operationId), }; - private static void DescribeResponses(OpenApiDocument document, OpenApiOperation operation) + /// + /// The page parameters of an inspection by their rule and not only by prose: the closed state set, the page-size + /// range, the ticket's shape and the cursor's length bound. + /// + private static void DescribeInspectionParameters(OpenApiOperation operation) + { + foreach (var parameter in operation.Parameters ?? []) + { + if (parameter is not OpenApiParameter concrete) + { + continue; + } + + switch (concrete.Name) + { + case "state": + concrete.Description = "dead_lettered (default) or terminal_requested; a quarantined-jobs list takes no state."; + concrete.Schema = new OpenApiSchema + { + Type = JsonSchemaType.String, + Enum = [JsonValue.Create("dead_lettered")!, JsonValue.Create("terminal_requested")!], + }; + break; + case "limit": + concrete.Description = "Page size, 1 or more; a value above 100 is clamped to 100. Zero or less is refused."; + concrete.Schema = new OpenApiSchema + { + Type = JsonSchemaType.Integer, + Minimum = "1", + Default = JsonValue.Create(20), + }; + break; + case "cursor": + concrete.Description = "The nextCursor of the previous page; it belongs to the route and state that issued it."; + concrete.Schema = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 512 }; + break; + case "ticket": + concrete.Description = "An optional change reference, recorded on the platform scope's entry row."; + concrete.Schema = new OpenApiSchema + { + Type = JsonSchemaType.String, + MinLength = 1, + MaxLength = 64, + Pattern = Platform.TicketPattern.Value, + }; + break; + } + } + } + + private static void DescribeResponses(OpenApiDocument document, OpenApiOperation operation, bool isRead) { operation.Responses ??= []; foreach (var (status, description) in Statuses) { + // A read has no body to refuse and no row to find: 404, 413 and 415 belong to the acts. + if (isRead && status is "404" or "413" or "415") + { + continue; + } + // 409 belongs to the acts that can meet a state they refuse; a switch toggle never answers it. if (status == "409" && !operation.Responses.ContainsKey("409")) { @@ -135,7 +197,8 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation concrete.Headers["Retry-After"] = new OpenApiHeader { Required = true, - Description = "Suggested retry delay in seconds; the act is safe to repeat.", + Description = "Suggested retry delay in seconds. Repeat after it unless the body names errors.outcome: " + + "then the commit may have landed, and the row is read before the act is repeated.", Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Minimum = "0" }, }; } @@ -144,7 +207,7 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation private static readonly (string Status, string Description)[] Statuses = [ - ("400", "validation_failed: the body is malformed, a required field is missing, an identifier is not a UUIDv7, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate or by a route check carries no per-field errors."), + ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit or errors.cursor."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, or a recovery names no such row."), @@ -152,7 +215,7 @@ private static readonly (string Status, string Description)[] Statuses = ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), - ("500", "internal_error: an unexpected failure. An act whose final commit's outcome is unknown may have landed; repeat the same request (every act is idempotent on its identifiers) or read the state before changing it."), - ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written or an ordered lock could not be taken, so nothing changed. Retry after the delay. A recovery can also answer outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed reset answers a repeat 409 on errors.fence."), + ("500", "internal_error: an unexpected failure. An act's final commit may have landed: read the state before changing it. An exact repeat of an onboarding act answers 200; a repeat of a recovery that had landed answers 409 on errors.fence."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written, a connection or an ordered lock could not be taken, or a read failed, so nothing changed. Retry after the delay. A recovery's dependency_unavailable can carry errors.outcome = lockey_outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed recovery answers a repeat 409 on errors.fence."), ]; } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs index 5d82fbba..805205dd 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs @@ -106,24 +106,27 @@ private static Task InspectOutboxAsync( HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, CancellationToken cancellationToken) => InspectAsync( - http, gate, ticket, state, limit, loggers, cancellationToken, - async (admission, parsedState, size) => await inspection.InspectOutboxAsync(admission, parsedState, cursor, size, cancellationToken)); + http, gate, ticket, state, limit, loggers, true, + async (admission, parsedState, size) => await inspection.InspectOutboxAsync(admission, parsedState, cursor, size, cancellationToken), + cancellationToken); private static Task InspectDeliveriesAsync( [FromQuery] string? state, [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, CancellationToken cancellationToken) => InspectAsync( - http, gate, ticket, state, limit, loggers, cancellationToken, - async (admission, parsedState, size) => await inspection.InspectDeliveriesAsync(admission, parsedState, cursor, size, cancellationToken)); + http, gate, ticket, state, limit, loggers, true, + async (admission, parsedState, size) => await inspection.InspectDeliveriesAsync(admission, parsedState, cursor, size, cancellationToken), + cancellationToken); private static Task InspectJobsAsync( - [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, + [FromQuery] string? state, [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, HttpContext http, IPlatformOperatorGate gate, IDeliveryInspection inspection, ILoggerFactory loggers, CancellationToken cancellationToken) => InspectAsync( - http, gate, ticket, "dead_lettered", limit, loggers, cancellationToken, - async (admission, _, size) => await inspection.InspectJobsAsync(admission, cursor, size, cancellationToken)); + http, gate, ticket, state, limit, loggers, false, + async (admission, _, size) => await inspection.InspectJobsAsync(admission, cursor, size, cancellationToken), + cancellationToken); /// /// The shared flow of an inspection: the gate first, so the query is answered only to an operator who may inspect, @@ -136,8 +139,9 @@ private static async Task InspectAsync( string? state, string? limit, ILoggerFactory loggers, - CancellationToken cancellationToken, - Func?>> page) + bool acceptsState, + Func?>> page, + CancellationToken cancellationToken) { var (refusal, admission) = await AdmitAsync(http, gate, PlatformOperations.DeliveryInspect, ticket, cancellationToken); if (refusal is not null) @@ -145,16 +149,22 @@ private static async Task InspectAsync( return refusal; } - if (!TryState(state, out var parsedState) || !TryLimit(limit, out var size)) + var parsedState = DeliveryInspectionState.DeadLettered; + if (acceptsState ? !TryState(state, out parsedState) : state is not null) { - return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + return InvalidParameter(http, "state"); + } + + if (!TryLimit(limit, out var size)) + { + return InvalidParameter(http, "limit"); } try { var result = await page(admission!, parsedState, size); return result is null - ? Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed") + ? InvalidParameter(http, "cursor") : Results.Ok(new InspectionResponse( result.Items, new InspectionPageInfo(result.NextCursor, null, result.NextCursor is not null, false))); } @@ -162,6 +172,10 @@ private static async Task InspectAsync( { return AuditUnavailableProblem(http, loggers, PlatformOperations.DeliveryInspect, failure); } + catch (OperatorRecoveryUnavailableException failure) + { + return UnavailableProblem(http, loggers, PlatformOperations.DeliveryInspect, failure); + } } private static async Task ReplayDeliveryAsync( @@ -239,13 +253,49 @@ private static async Task RecoverAsync( } catch (OperatorRecoveryUnavailableException failure) { - RetryAfter.Apply(http.Response, StatusCodes.Status503ServiceUnavailable); - return Problem( - http, StatusCodes.Status503ServiceUnavailable, - failure.CommitOutcomeUnknown ? "lockey_outcome_unknown" : "lockey_dependency_unavailable"); + return UnavailableProblem(http, loggers, operation, failure); } } + private static readonly Action LogRecoveryUnavailable = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(7109, nameof(LogRecoveryUnavailable)), + "An operator recovery owner was unavailable for {Operation}; the commit's outcome unknown: {CommitOutcomeUnknown}."); + + /// + /// A 503 whose cause the operator can find: the fault is logged, and the response names only whether the commit's + /// outcome is unknown. The status map is closed, so the reason travels on the field outcome of + /// dependency_unavailable and the body's status agrees with the response's. + /// + private static IResult UnavailableProblem( + HttpContext http, ILoggerFactory loggers, PlatformOperation operation, OperatorRecoveryUnavailableException failure) + { + LogRecoveryUnavailable( + loggers.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), operation.AuditSlug, failure.CommitOutcomeUnknown, + failure.InnerException); + return ResultProblem( + http, + failure.CommitOutcomeUnknown + ? new Error( + new LocalizedMessage("lockey_dependency_unavailable"), + new Dictionary>(StringComparer.Ordinal) + { + ["outcome"] = [new LocalizedMessage("lockey_outcome_unknown")], + }) + : new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + } + + /// A 400 that names the query parameter at fault, as Standard 04 asks of a page parameter. + private static IResult InvalidParameter(HttpContext http, string parameter) => ResultProblem( + http, + new Error( + new LocalizedMessage("lockey_validation_failed"), + new Dictionary>(StringComparer.Ordinal) + { + [parameter] = [new LocalizedMessage(ModelBindingProblemDetails.FieldMessageKey)], + })); + /// A 409 with the reason on the field it concerns; the status map is closed, so the code stays the business rule's. private static Error Rule(string field, string reason) => new( new LocalizedMessage("lockey_business_rule_violation"), @@ -314,12 +364,14 @@ private static bool TryLimit(string? text, out int size) return true; } - if (!int.TryParse(text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed)) + // Standard 04: a limit of zero or less is rejected, a larger one is clamped, never rejected. + if (!int.TryParse(text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) + || parsed < 1) { return false; } - size = Math.Clamp(parsed, 1, MaximumPageSize); + size = Math.Min(parsed, MaximumPageSize); return true; } diff --git a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs index bd64d9d8..b0777c25 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs @@ -47,19 +47,29 @@ public async Task ReplayAsync( return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); } + var progress = new RecoveryProgress(); try { - return await ReplayCoreAsync(request, admission, cancellationToken).ConfigureAwait(false); + return await ReplayCoreAsync(request, admission, progress, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (progress.CommitAttempted + && (failure is NpgsqlException or TimeoutException or InvalidOperationException or AggregateException + || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested))) + { + // The COMMIT was sent, so whatever failed afterwards (the connection's cleanup included) leaves its + // outcome unknown, and the operator inspects the row before repeating. + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) { - throw new OperatorRecoveryUnavailableException(); + throw new OperatorRecoveryUnavailableException(cause: failure); } } private async Task ReplayCoreAsync( - DeliveryReplayRequest request, PlatformAdmission admission, CancellationToken cancellationToken) + DeliveryReplayRequest request, PlatformAdmission admission, + RecoveryProgress progress, CancellationToken cancellationToken) { using var deadline = Deadline(cancellationToken); await using var ownedConnection = await OpenConnectionAsync(deadline.Token, operatorLane: true).ConfigureAwait(false); @@ -135,6 +145,7 @@ FROM event_deliveries WHERE {Identity} FOR UPDATE } await WriteRecoveryRowAsync(witness, admission, connection, transaction, deadline.Token).ConfigureAwait(false); + progress.CommitAttempted = true; try { await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); @@ -144,7 +155,7 @@ FROM event_deliveries WHERE {Identity} FOR UPDATE // COMMIT may have reached PostgreSQL. The change and its row commit together or not at all, so there is // nothing to repair; the operator inspects the row, whose fence moved if the reset landed. ownedConnection.RecordCommitFailure(failure); - throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } return new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, witness.AfterCount); @@ -187,7 +198,7 @@ private async Task WriteRecoveryRowAsync( private async Task TenantServesAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, CancellationToken cancellationToken) { - var lifecycle = _lifecycle ?? throw new InvalidOperationException("The tenant lifecycle projection is not configured."); + var lifecycle = _lifecycle ?? throw new NotSupportedException("The tenant lifecycle projection is not configured."); await using var command = new NpgsqlCommand( "SELECT status, deleted_at IS NOT NULL, default_organization_id FROM tenants WHERE id = @tenant", connection, transaction); Configure(command); @@ -199,6 +210,12 @@ private async Task TenantServesAsync( BackgroundJobRecipientPolicy.ServingTenants); } + /// Whether the COMMIT was sent, so a later fault is reported as an unknown outcome and not as nothing changed. + private sealed class RecoveryProgress + { + internal bool CommitAttempted { get; set; } + } + /// The store's own minting subtype for the recovery witness; no other type may derive from the seam. private sealed class RecoveryMint : OperatorRecoveryTransition.MintingSource { diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs index a67412c8..44e98a9b 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs @@ -40,19 +40,29 @@ public async Task ResetAsync( return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); } + var progress = new RecoveryProgress(); try { - return await ResetCoreAsync(request, admission, cancellationToken).ConfigureAwait(false); + return await ResetCoreAsync(request, admission, progress, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (progress.CommitAttempted + && (failure is NpgsqlException or TimeoutException or InvalidOperationException or AggregateException + || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested))) + { + // The COMMIT was sent, so whatever failed afterwards (the connection's cleanup included) leaves its + // outcome unknown, and the operator inspects the row before repeating. + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) { - throw new OperatorRecoveryUnavailableException(); + throw new OperatorRecoveryUnavailableException(cause: failure); } } private async Task ResetCoreAsync( - OutboxResetRequest request, PlatformAdmission admission, CancellationToken cancellationToken) + OutboxResetRequest request, PlatformAdmission admission, + RecoveryProgress progress, CancellationToken cancellationToken) { using var deadline = Deadline(cancellationToken); await using var ownedConnection = await OpenConnectionAsync(deadline.Token, operatorLane: true).ConfigureAwait(false); @@ -127,6 +137,7 @@ AND locked_by IS NULL AND locked_until IS NULL } await WriteRecoveryRowAsync(witness, admission, connection, transaction, deadline.Token).ConfigureAwait(false); + progress.CommitAttempted = true; try { await transaction.CommitAsync(deadline.Token).ConfigureAwait(false); @@ -136,7 +147,7 @@ AND locked_by IS NULL AND locked_until IS NULL // COMMIT may have reached PostgreSQL; the row and its audit commit together or not at all, so the // operator inspects the row, whose fence moved if the reset landed. ownedConnection.RecordCommitFailure(failure); - throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } return new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, witness.AfterCount); @@ -179,7 +190,7 @@ private async Task WriteRecoveryRowAsync( private async Task TenantServesAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, CancellationToken cancellationToken) { - var lifecycle = _lifecycle ?? throw new InvalidOperationException("The tenant lifecycle projection is not configured."); + var lifecycle = _lifecycle ?? throw new NotSupportedException("The tenant lifecycle projection is not configured."); await using var command = new NpgsqlCommand( "SELECT status, deleted_at IS NOT NULL, default_organization_id FROM tenants WHERE id = @tenant", connection, transaction); Configure(command); @@ -191,6 +202,12 @@ private async Task TenantServesAsync( BackgroundJobRecipientPolicy.ServingTenants); } + /// Whether the COMMIT was sent, so a later fault is reported as an unknown outcome and not as nothing changed. + private sealed class RecoveryProgress + { + internal bool CommitAttempted { get; set; } + } + /// The store's own minting subtype for the recovery witness; no other type may derive from the seam. private sealed class RecoveryMint : OperatorRecoveryTransition.MintingSource { diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs index 5234a8d7..a3921a78 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs @@ -1,9 +1,11 @@ using System.Data.Common; using System.Globalization; using System.Text; +using System.Text.RegularExpressions; using LearnStack.Infrastructure.Messaging; using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; +using Npgsql; namespace LearnStack.Infrastructure.PlatformOperator; @@ -28,6 +30,12 @@ public sealed class DeliveryInspection(IPlatformAdminScope scope, OutboxEventReg { private const int MaximumLimit = 100; + // The dispatcher writes a closed vocabulary of lowercase descriptors (for example publish:failed:provider). The + // database bounds only the byte length of last_error, so the projection shows a value of that shape and nothing + // else: free text could carry markup, and a page is rendered by a client the operator trusts. + private static readonly Regex DescriptorShape = new( + @"\A[a-z][a-z0-9_.:-]{0,63}\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); + private const string OutboxColumns = "id, tenant_id, organization_id, occurred_at, type, attempts, last_error, " + "available_after, locked_until, terminal_reason, dead_lettered_at, processed_at"; @@ -143,9 +151,20 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, after = new DateTimeOffset(ticks, TimeSpan.Zero); } - await using var handle = await scope.EnterAsync(admission, cancellationToken).ConfigureAwait(false); - var built = statement(after, key, size + 1); - var rows = await handle.QueryAsync(built.Sql, built.Parameters, map, cancellationToken).ConfigureAwait(false); + IReadOnlyList rows; + try + { + await using var handle = await scope.EnterAsync(admission, cancellationToken).ConfigureAwait(false); + var built = statement(after, key, size + 1); + rows = await handle.QueryAsync(built.Sql, built.Parameters, map, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException + || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + // A read is safe to repeat; the cause is for the route's log, never for the response. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + var items = rows.Take(size).ToList(); var next = rows.Count > size && items.Count > 0 ? Encode(scopeKey, ticksOf(items[^1]), keyOf(items[^1])) @@ -177,7 +196,7 @@ private OutboxMessageInspection MapOutbox(DbDataReader reader) var disposition = registry.Resolve(type); return new OutboxMessageInspection( reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), disposition.EventTypeLabel, - reader.GetFieldValue(3), reader.GetInt32(5), reader.IsDBNull(6) ? null : reader.GetString(6), + reader.GetFieldValue(3), reader.GetInt32(5), Shown(reader.IsDBNull(6) ? null : reader.GetString(6)), reader.GetFieldValue(7), lockedUntil, reason, deadLettered, Actionable: deadLettered is not null && reason == "retry_exhausted" && reader.IsDBNull(11) && lockedUntil is null && disposition.Disposition is not (OutboxEventDisposition.Retired or OutboxEventDisposition.Unknown)); @@ -193,12 +212,15 @@ private EventDeliveryInspection MapDelivery(DbDataReader reader) return new EventDeliveryInspection( reader.GetGuid(0), subscription, reader.GetGuid(2), reader.IsDBNull(3) ? null : reader.GetGuid(3), registry.Resolve(type).EventTypeLabel, reader.GetFieldValue(4), reader.GetInt32(6), - reader.IsDBNull(7) ? null : reader.GetString(7), reader.GetFieldValue(8), lockedUntil, reason, + Shown(reader.IsDBNull(7) ? null : reader.GetString(7)), reader.GetFieldValue(8), lockedUntil, reason, deadLettered, reader.GetInt32(12), reader.IsDBNull(13) ? null : reader.GetFieldValue(13), Actionable: deadLettered is not null && reader.IsDBNull(14) && lockedUntil is null && reason != "invalid_envelope" && registry.IsActiveOrdinarySubscription(type, subscription)); } + private static string? Shown(string? error) => + error is null ? null : DescriptorShape.IsMatch(error) ? error : "unrecognized"; + private static QuarantinedJobInspection MapJob(DbDataReader reader) => new( reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), reader.GetString(3), reader.GetString(4), reader.GetString(5), reader.IsDBNull(6) ? null : reader.GetString(6), diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index 9a84c011..d22b6e8f 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -221,7 +221,7 @@ Task WriteOperatorRecoveryAsync( DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) => - throw new InvalidOperationException("This audit store cannot write an operator recovery row."); + throw new NotSupportedException("This audit store cannot write an operator recovery row."); /// Inserts a MUST terminal audit on the successful transition's live transaction. /// diff --git a/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs index 0d4c80bd..b39487b8 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs @@ -45,13 +45,17 @@ public sealed record OperatorRecoveryResult(OperatorRecoveryOutcome Outcome, int /// The recovery owner could not finish and nothing is known to be wrong with the request: the credential or the pool /// is unavailable, the owner's one lane is busy, or the commit's outcome is unknown (ADR-0103 § 5). /// -/// The message is fixed and carries no address, credential or row value. +/// +/// The message is fixed and carries no address, credential or row value. The cause, when there is one, is for the +/// operator's logs only: no response carries it. +/// public sealed class OperatorRecoveryUnavailableException : Exception { /// Builds the refusal. /// Whether the transition's COMMIT may have reached the database. - public OperatorRecoveryUnavailableException(bool commitOutcomeUnknown = false) - : base("The operator recovery owner is unavailable.") => CommitOutcomeUnknown = commitOutcomeUnknown; + /// The fault that made the owner unavailable, kept so the route can log it. + public OperatorRecoveryUnavailableException(bool commitOutcomeUnknown = false, Exception? cause = null) + : base("The operator recovery owner is unavailable.", cause) => CommitOutcomeUnknown = commitOutcomeUnknown; /// Whether the commit may have landed, so the operator inspects the row before repeating the request. public bool CommitOutcomeUnknown { get; } diff --git a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs index 8c8b4650..84b8d11f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs @@ -481,7 +481,7 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc RequireBoundaryMethod(offenders, store, "ReplayCoreAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Private, "LearnStack.SharedKernel.Platform.DeliveryReplayRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", - BoundaryCancellation), + DeliveryStore + "/RecoveryProgress", BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", "System.Threading.Tasks.ValueTask`1<" + DeliveryStore + "/OwnedConnection>", MethodAttributes.Private, diff --git a/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs index 2d19848f..481ab0fc 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs @@ -77,6 +77,21 @@ public void Operator_recovery_census_detects_extra_derivers_constructors_and_cal var method = AddCall(type, "UnrelatedRecoveryHelper", factory, OpCodes.Call); return () => type.Methods.Remove(method); }, RecoveryOffenders); + + // The reset factory is as closed as the replay one: it is probed the same ways. + var resetFactory = source.Methods.Single(method => method.Name == RecoveryResetMint); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) + { + AssertMutation(census, "a cross-assembly reset mint helper using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryResetMintCaller", resetFactory, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a reset mint helper on the delivery store type", () => + { + var type = census.Types[(InfrastructureAssembly, DeliveryStore)]; + var method = AddCall(type, "UnrelatedRecoveryResetHelper", resetFactory, OpCodes.Call); + return () => type.Methods.Remove(method); + }, RecoveryOffenders); } private static SortedSet RecoveryOffenders(ProductionCensus census) diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs index 9bd65ca5..40714907 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs @@ -679,7 +679,7 @@ private static SortedSet CredentialOffenders(ProductionCensus census) RequireBoundaryMethod(offenders, store, "ResetCoreAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Private, "LearnStack.SharedKernel.Platform.OutboxResetRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", - BoundaryCancellation), + Store + "/RecoveryProgress", BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", "System.Threading.Tasks.ValueTask`1<" + Store + "/OwnedConnection>", MethodAttributes.Private, diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs index 79400494..d9ff2086 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs @@ -321,6 +321,12 @@ public void Outbox_SQL_census_detects_quoted_schema_CTE_extra_and_missing_writer var method = AddSqlMethod(store, "AcquireAsync", "UPDATE outbox_messages SET attempts=0"); return () => store.Methods.Remove(method); }, OutboxSqlOffenders); + AssertMutation(census, "an extra overload of the operator's producer reset", () => + { + var store = census.Types[(InfrastructureAssembly, Store)]; + var method = AddSqlMethod(store, "ResetCoreAsync", "UPDATE outbox_messages SET attempts=0"); + return () => store.Methods.Remove(method); + }, OutboxSqlOffenders); AssertMutation(census, "a missing production mutation path", () => { var literal = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == Store) diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs new file mode 100644 index 00000000..b138962c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs @@ -0,0 +1,15 @@ +using LearnStack.Infrastructure.Jobs; + +namespace LearnStack.Tests.Integration; + +/// +/// The smallest Maximum Pool Size the default background-job topology accepts. The +/// fixtures derive it from the production manifest instead of repeating a literal, so a +/// new connection slot in a messaging store or the job runtime cannot leave a test below +/// the floor. The literal is pinned once, in BackgroundJobPhysicalCapacityTests. +/// +internal static class BackgroundJobCapacity +{ + public static readonly int Floor = BackgroundJobPhysicalCapacity + .Calculate(BackgroundJobInfrastructureRegistry.CreateDefault()).RequiredConnections; +} diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs index dd4f319e..6019ffcd 100644 --- a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs @@ -325,7 +325,7 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(new Dictionary { ["ConnectionStrings:Default"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_app;Maximum Pool Size=32", - ["ConnectionStrings:OutboxDispatcher"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_outbox_admin;Maximum Pool Size=52", + ["ConnectionStrings:OutboxDispatcher"] = $"Host=localhost;Port=1;Database=learnstack;Username=learnstack_outbox_admin;Maximum Pool Size={BackgroundJobCapacity.Floor}", })); builder.ConfigureTestServices(collection => { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs index 0354e216..6a06c8a6 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs @@ -39,7 +39,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ }, applicationPoolSize: 32); var bounds = host.Services.GetRequiredService(); var dispatcherConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(dispatcherConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(Fixture.Registry.Infrastructure); @@ -47,7 +47,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ var runtime = new BackgroundJobRuntime(source, Fixture.Registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, Fixture.Registry, bounds, ids, gate), gate, bounds, ids, TimeProvider.System, - new(true, 52), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); + new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); // Construction-only host removed both messaging workers; neither issued work. runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); var submitted = await Fixture.SubmitAsync(host.Services, Fixture.Parameters(resource, prepared, finalized)); @@ -64,7 +64,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ { var settings = new NpgsqlConnectionStringBuilder(physical.ConnectionString); settings.Pooling.Should().BeTrue(); - settings.MaxPoolSize.Should().Be(52); + settings.MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); } var waiting = Stopwatch.StartNew(); // A successor hint may finish before the original Outcome cleanup diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs index d0882f05..b6f9fe4d 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs @@ -165,14 +165,14 @@ public async Task Actual_facade_parks_expired_external_work_reconciles_or_uses_r }, applicationPoolSize: 32); var bounds = host.Services.GetRequiredService(); var dispatcherConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(dispatcherConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(Fixture.Registry.Infrastructure); var ids = new SystemGuidFactory(); var runtime = new BackgroundJobRuntime(source, Fixture.Registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, Fixture.Registry, bounds, ids, gate), - gate, bounds, ids, TimeProvider.System, new(true, 52), new HangfireBoundedLogProvider(), + gate, bounds, ids, TimeProvider.System, new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); try @@ -186,7 +186,7 @@ public async Task Actual_facade_parks_expired_external_work_reconciles_or_uses_r { var settings = new NpgsqlConnectionStringBuilder(physical.ConnectionString); settings.Pooling.Should().BeTrue(); - settings.MaxPoolSize.Should().Be(52); + settings.MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); } var waiting = Stopwatch.StartNew(); var completionBudget = bounds.HandoffRepairGrace + bounds.TransactionTimeout + bounds.SqlTimeout * 2 + bounds.ControlPoll * 2; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs index c565cb47..e4f60321 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs @@ -99,14 +99,14 @@ public async Task Native_transactional_pool_completes_at_the_app_source_floor_wh }, applicationPoolSize: 32, reconcileProbe: reconcile, componentRequests: [transactional.RequestType("Submit")]); var lifetime = host.Services.GetRequiredService(); var privilegedConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(privilegedConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(registry.Infrastructure); var ids = new SystemGuidFactory(); var runtime = new BackgroundJobRuntime(source, registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, registry, bounds, ids, gate), - gate, bounds, ids, TimeProvider.System, new(true, 52), new HangfireBoundedLogProvider(), lifetime); + gate, bounds, ids, TimeProvider.System, new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), lifetime); // Neither messaging worker starts in the existing construction-only host. runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); var submitted = await Fixture.SubmitAsync(host.Services, Fixture.Parameters(resource, prepared, finalized)); @@ -132,7 +132,7 @@ void PreserveFailure(Exception error) lifetime.PoolSettings.Should().Be(new BackgroundJobApplicationPoolSettings(true, 32)); runtime.Snapshot.ApplicationCapacity!.RequiredConnections.Should().Be(32); await using (var physical = await source.OpenConnectionAsync(startup.Token)) - new NpgsqlConnectionStringBuilder(physical.ConnectionString).MaxPoolSize.Should().Be(52); + new NpgsqlConnectionStringBuilder(physical.ConnectionString).MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); // Execute and the provider journal commit are real. The native recovery // then enters the SDK's post-call barrier, retaining its actual task. boundary = "reconcile_wait"; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs index 56ef3dbc..b187768a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs @@ -121,7 +121,7 @@ public async Task Native_cache_waiter_timeout_joins_late_actual_auxiliary_cleanu services.AddSingleton>(auditLogger); services.AddSingleton>(reconcileLogger); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); var auditHealth = host.Services.GetRequiredService(); auditHealth.IsHealthy.Should().BeTrue(); @@ -137,7 +137,7 @@ public async Task Native_cache_waiter_timeout_joins_late_actual_auxiliary_cleanu auditListener.SetMeasurementEventCallback((_, count, tags, _) => auditFailures.Enqueue((count, tags.ToArray()))); auditListener.Start(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); HangfireGeneration? generation = null; var verified = false; Exception? testFailure = null; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs index 3bacc832..b0b13011 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs @@ -72,7 +72,7 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(100)); @@ -168,7 +168,7 @@ public async Task Admitted_native_business_renews_across_local_drain_and_commits services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(100)); @@ -261,10 +261,10 @@ public async Task Native_business_overrun_and_private_callback_keep_both_sources services.RemoveAll(); services.AddSingleton(bounds); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); using var deadline = new CancellationTokenSource(TestWait); try { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs index c6afac9f..5cda08b1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs @@ -41,7 +41,7 @@ public async Task Native_capacity_completion_releases_with_business_child_outbox services.AddSingleton(bounds); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_commit_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs index 5083088f..df161896 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs @@ -56,7 +56,7 @@ public async Task Native_rolled_back_capacity_admission_joins_after_peer_clears_ services.AddScoped(); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); await using var peerSource = Source(database, physical); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs index 77b0175c..31ac4ec3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs @@ -36,7 +36,7 @@ public async Task Native_capacity_checkpoint_lost_ACK_uses_exact_committed_clean services.AddSingleton(bounds); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_checkpoint_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs index 0cdd7c80..d412684f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs @@ -104,10 +104,10 @@ public async Task Native_grouped_rollback_checkpoints_only_after_original_auxili services.AddTransient>, CapacityCleanupCheckpointObserver>(); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); var observation = host.Services.GetRequiredService(); using var metrics = new BackgroundJobStageProbe(observation); using var traces = new BackgroundJobTraceProbe(observation); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs index d0301752..e85437d3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs @@ -32,7 +32,7 @@ public async Task Native_grouped_permanent_refusal_survives_lost_checkpoint_ACK_ services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: proxy.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_capacity_control_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs index 48005d97..f887ce27 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs @@ -94,7 +94,7 @@ public async Task Native_grouped_admission_never_started_releases_only_after_act CommandTimeout = 0, CancellationTimeout = 1000, }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_no_start_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs index 3184ee06..9111f387 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs @@ -35,7 +35,7 @@ public async Task Native_host_stop_after_recovery_ACK_does_not_issue_capacity_ch }, }; await using var host = CapacityStopHost(database, probe, state, bounds); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_stop_before_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); @@ -140,7 +140,7 @@ public async Task Native_host_stop_joins_issued_capacity_checkpoint_private_call }, }; await using var host = CapacityStopHost(database, probe, state, bounds); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs index 48ff157b..b12ec2e6 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs @@ -53,8 +53,8 @@ public async Task Native_capacity_recovery_reprobes_settled_history_after_peer_t }); await using var proxy = new CommitResponseDroppingProxy(database.OutboxConnectionString, commitsToPass: int.MaxValue, lifetime: TimeSpan.FromMinutes(2)); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); - var settings = new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 52 }; + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); + var settings = new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(settings.ConnectionString)); await using var peerSource = Source(database, physical); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs index ecd65034..53c9718d 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs @@ -30,7 +30,7 @@ public async Task Supported_pool_serves_native_business_during_combined_actual_m await using var database = await DatabaseAsync(); var applicationName = "combined_capacity_" + Guid.NewGuid().ToString("N"); var connectionString = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52, ApplicationName = applicationName }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor, ApplicationName = applicationName }.ConnectionString; var outboxHold = new CombinedTerminalHold(); var deliveryHold = new CombinedTerminalHold(); // Uncommitted unique-key contention identifies the exact stock expiration @@ -90,7 +90,7 @@ await SchemaQueries.ExecuteAsync(blocker, blockedTransaction, await delivery.StartAsync(CancellationToken.None); await jobs.StartAsync(CancellationToken.None); await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy)); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); expiration = ActualExpiration(runtime); await EventuallyAsync(async () => { @@ -121,7 +121,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) absentOwner.Should().Throw(); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, tenant: SchemaFixture.TenantB); await EnsureQualificationStartAsync(runtime, source, job, bodyObserved.Task); - (await bodyObserved.Task.WaitAsync(TestWait)).Should().BeInRange(3, 52); + (await bodyObserved.Task.WaitAsync(TestWait)).Should().BeInRange(3, BackgroundJobCapacity.Floor); await EventuallyAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, job, tenant: SchemaFixture.TenantB))?.Phase == "completed"); await AssertCombinedBusinessAsync(database, organization); @@ -171,7 +171,7 @@ private static void AssertCombinedHolds(CombinedTerminalHold outbox, CombinedTer expiration.Should().NotBeNull(); expiration!.Snapshot.Should().BeEquivalentTo(new { State = HangfireSharedComponentState.Retained, Invocations = 1L, OwnsResources = true, ActualJoined = false }); source.Should().NotBeNull(); - PoolStatistics(source!).Busy.Should().BeInRange(3, 52); + PoolStatistics(source!).Busy.Should().BeInRange(3, BackgroundJobCapacity.Floor); } private static async Task CombinedBlockedExpirationPidAsync(DisposableSchemaDatabase database, string applicationName, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs index 44b852b1..d794e673 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs @@ -49,7 +49,7 @@ public async Task Native_lost_business_ACK_retains_the_actual_identity_until_a_l services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: appSettings.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_commit_probe_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); @@ -164,7 +164,7 @@ public async Task Native_final_completion_rechecks_database_expiry_after_its_rea services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: appSettings.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TestWait); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs index a720182e..960b781b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs @@ -40,7 +40,7 @@ public async Task Actual_API_composition_keeps_both_sources_after_host_disposal_ var connectionString = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) { Pooling = true, - MaxPoolSize = 52, + MaxPoolSize = BackgroundJobCapacity.Floor, ApplicationName = applicationName, }.ConnectionString; var cleanup = new FacadeCleanupSignals(); @@ -83,7 +83,7 @@ public async Task Actual_API_composition_keeps_both_sources_after_host_disposal_ await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy && services.GetRequiredService().IsHealthy && services.GetRequiredService().IsHealthy)); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); (await ServerCountAsync(source)).Should().Be(3); outbox.ExecuteTask.Should().NotBeNull(); delivery.ExecuteTask.Should().NotBeNull(); @@ -142,7 +142,7 @@ await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy await SchemaQueries.AssertApplicationRoleAsync(remaining); source.HasUnconfirmedCleanup.Should().BeFalse("pending scope ownership is not a disposal fault"); PoolStatistics(source).Busy.Should().Be(1); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); PoolStatistics(source).Busy.Should().Be(1); cleanup.Release.TrySetResult(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs index e1df98d4..0dc161f7 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs @@ -43,7 +43,7 @@ public async Task Native_clean_control_lock_timeout_retains_the_permanent_refusa services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_control_failure_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs index 3ee6f5af..6e4c0bdd 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs @@ -147,7 +147,7 @@ public async Task Actual_common_database_outage_drains_all_pools_and_recovery_ke observation.Configure(services); services.AddScoped(_ => new FacadeHeldReadCleanup(cleanupSignals)); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(HeartbeatQualificationWait); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs index 8581cf41..7c41ac09 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs @@ -24,7 +24,7 @@ public sealed partial class BackgroundJobRuntimeFacadeTests public async Task Native_framework_wait_retains_actual_cleanup_and_releases_its_slot_before_host_stop(bool synchronousPrefix) { await using var database = await DatabaseAsync(); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var applicationName = "facade_cleanup_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, applicationName); var cleanup = new FacadeCleanupSignals(); @@ -183,7 +183,7 @@ await FluentActions.Awaiting(() => runtime.StopAsync(callerWait.Token)) public async Task Pooled_boundary_52_keeps_actual_expiration_checkout_after_caller_timeout_while_transactional_admission_progresses() { await using var database = await DatabaseAsync(); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var applicationName = "facade_capacity_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, applicationName); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -211,7 +211,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) .Should().ThrowAsync(); await EventuallyAsync(() => Task.FromResult(expiration.Snapshot.State == HangfireSharedComponentState.Retained)); expiration.Completion.IsCompleted.Should().BeFalse(); - PoolStatistics(source).Busy.Should().BeInRange(1, 52); + PoolStatistics(source).Busy.Should().BeInRange(1, BackgroundJobCapacity.Floor); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); await EnsureQualificationStartAsync(runtime, source, job, entered.Task); @@ -226,7 +226,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) ActualJoined = false, }); expiration.Completion.IsCompleted.Should().BeFalse(); - PoolStatistics(source).Busy.Should().BeInRange(1, 52); + PoolStatistics(source).Busy.Should().BeInRange(1, BackgroundJobCapacity.Floor); runtime.Snapshot.RunningPools.Should().Be(3); var health = await new BackgroundJobHealthCheck(runtime).CheckHealthAsync(new HealthCheckContext()); health.Status.Should().Be(HealthStatus.Unhealthy); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs index 23efe2fb..73df4a78 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs @@ -538,6 +538,27 @@ public async Task Replay_refuses_a_matching_fence_on_a_state_a_reset_may_not_act (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty("a refusal writes no row"); } + [Theory] + [InlineData("count")] + [InlineData("reason")] + public async Task Replay_reports_a_stale_fence_before_it_reports_a_refused_state(string variation) + { + // The fence is compared before the state, so an operator who read an older row is told to read it again and + // is not told the row is refused: only a row whose fence they hold can be refused to them. + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, "terminal_reason = 'invalid_envelope', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); + var before = await test.ReadAsync(id); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, + change: request => variation == "count" ? request with { ReplayCount = request.ReplayCount + 1 } + : request with { TerminalReason = "retry_exhausted" }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + [Theory] [InlineData("live")] [InlineData("requested")] @@ -776,6 +797,120 @@ public async Task Real_scheduler_role_cannot_read_payload_causality_or_inbox(str (await test.Store().TryClaimAsync(NoBlocked)).Should().NotBeNull(); } + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + [InlineData("operation")] + [InlineData("reason")] + [InlineData("metadata")] + [InlineData("correlation")] + [InlineData("actor")] + [InlineData("class")] + [InlineData("type")] + [InlineData("transaction")] + public async Task Substituting_a_field_of_the_replay_row_or_its_transaction_is_refused_by_the_real_seam_and_rolls_the_replay_back( + string substitution) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.UpdateAsync(id, First, DeadLetter); + var calls = 0; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + calls++; + // The witness came from the real successful UPDATE, before the row it must describe is written. + witness.Kind.Should().Be("replay"); + witness.EventId.Should().Be(id); + witness.TenantId.Should().Be(SchemaFixture.TenantA); + witness.OrganizationId.Should().Be(SchemaFixture.OrgA1); + if (substitution == "transaction") + { + await using var otherConnection = await test.Dispatch.OpenConnectionAsync(cancellationToken); + await using var otherTransaction = await otherConnection.BeginTransactionAsync(cancellationToken); + await inner.WriteOperatorRecoveryAsync(draft, witness, otherConnection, otherTransaction, cancellationToken); + return; + } + + var changed = substitution switch + { + "tenant" => draft with { TenantId = TenantId.From(SchemaFixture.TenantB) }, + "organization" => draft with { OrganizationId = OrganizationId.From(SchemaFixture.OrgA2) }, + "operation" => draft with { Operation = PlatformOperations.DeliveryReset.AuditSlug }, + "reason" => draft with { Reason = PlatformOperations.DeliveryReset.ReasonSlug }, + "metadata" => draft with { Metadata = draft.Metadata + " " }, + "correlation" => draft with { CorrelationId = "00-forged" }, + "actor" => draft with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + "class" => draft with { OperationClass = OperationClass.Should }, + "type" => draft with { OperationType = OperationType.Update }, + _ => throw new ArgumentOutOfRangeException(nameof(substitution)), + }; + await inner.WriteOperatorRecoveryAsync(changed, witness, connection, transaction, cancellationToken); + })); + var before = await test.ReadAsync(id); + + var attempt = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, id); + await attempt.Should().ThrowAsync(); + + calls.Should().Be(1, "the refusal must come from the real audit seam, after a successful UPDATE"); + (await test.ReadAsync(id)).Should().Be(before, "the replay and its row commit together or not at all"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the same fence succeeds through the unmodified seam"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle(); + } + + [Fact] + public async Task A_witness_from_an_earlier_replay_cannot_be_reused_on_a_later_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + OperatorRecoveryTransition? previous = null; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + await inner.WriteOperatorRecoveryAsync(draft, previous ?? witness, connection, transaction, cancellationToken); + previous = witness; + })); + var first = await test.InsertAsync(); + await test.UpdateAsync(first, First, DeadLetter); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, first)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + var second = await test.InsertAsync(); + await test.UpdateAsync(second, First, DeadLetter); + var before = await test.ReadAsync(second); + + var attempt = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, second); + await attempt.Should().ThrowAsync(); + + (await test.ReadAsync(second)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle("only the first replay committed"); + } + + [Fact] + public async Task The_recovery_owner_replays_through_the_delivery_store_and_counts_each_outcome_under_the_replay_operation() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var fence = await test.ReadAsync(id); + var request = new DeliveryReplayRequest(SchemaFixture.TenantA, First, id, fence.ReplayCount, fence.DeadLettered!.Value, "retry_exhausted"); + var owner = new OperatorRecovery(test.Store(), test.OutboxStore()); + using var meters = new OperatorRecoveryMeterProbe(); + + var applied = await owner.ReplayDeliveryAsync(ReplayAdmission(), request); + var stale = await owner.ReplayDeliveryAsync(ReplayAdmission(), request); + var unknown = await owner.ReplayDeliveryAsync(ReplayAdmission(), request with { EventId = Guid.CreateVersion7() }); + + (applied.Outcome, stale.Outcome, unknown.Outcome).Should().Be( + (OperatorRecoveryOutcome.Applied, OperatorRecoveryOutcome.StaleFence, OperatorRecoveryOutcome.NotFound)); + (await test.ReadAsync(id)).ReplayCount.Should().Be(1, "the owner reached the delivery store and no other"); + var replay = PlatformOperations.DeliveryReplay.AuditSlug; + var reset = PlatformOperations.DeliveryReset.AuditSlug; + (meters.Recoveries(replay, "applied"), meters.Recoveries(replay, "stale_fence"), meters.Recoveries(replay, "not_found")) + .Should().Be((1, 1, 1)); + meters.Results(replay).Should().Be(1, "only an applied replay committed a result row"); + meters.Recoveries(reset, "applied").Should().Be(0, "a delivery replay is never counted as a producer reset"); + } + private static OutboxEventRegistry Registry() { var handlers = IntegrationEventHandlerRegistry.FromServiceDescriptors([ @@ -856,6 +991,12 @@ INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at catch { await test.DisposeAsync(); throw; } } + /// The producer store beside the delivery store, for a test that builds the recovery owner over both. + public OutboxDispatchStore OutboxStore() => + new(new PrivilegedDataSource(() => Dispatch), Registry(), new OutboxDispatchOptions(), new SystemGuidFactory(), + new FixedClock(Occurred), _provider.GetRequiredService(), + BackgroundJobLifecycleProjectionDeclaration.Create()); + public DeliveryDispatchStore Store(NpgsqlDataSource? source = null, Func? decorate = null) => new(new PrivilegedDataSource(() => source ?? Dispatch), Registry(), new DeliveryDispatchOptions(), new SystemGuidFactory(), new FixedClock(Occurred), decorate is null diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs index 78236604..427eff7e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs @@ -167,6 +167,152 @@ await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sq await SchemaQueries.ExecuteAsync(platform, null, "SELECT job_id, released_at FROM background_job_reservations"); } + [Fact] + public async Task Job_occupancy_counts_the_unreleased_reservations_of_the_job_and_of_its_capacity_group() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var held = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA, + capacityGroup: "fixture.resource"); + var neighbour = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA, + capacityGroup: "fixture.resource"); + await using (var dispatcher = await PostgresFixture.OpenAsync(proof.Database.OutboxConnectionString)) + await SchemaQueries.ExecuteAsync(dispatcher, null, + "UPDATE background_jobs SET phase = 'quarantined', quarantine_reason = 'unknown_outcome' WHERE id = @id", ("id", held.Value)); + // The fixture rows are written with the foreign keys and guard triggers off: the proof is the two counts, and + // a reservation's own lifecycle has its own proofs. One unreleased and one released reservation belong to the + // quarantined job; a second job of the same group holds one more. + await proof.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO background_job_capacity (tenant_id, capacity_group) + SELECT DISTINCT tenant_id, capacity_group FROM background_jobs WHERE id IN ('{held.Value}', '{neighbour.Value}') + ON CONFLICT DO NOTHING; + INSERT INTO background_job_attempts (id, tenant_id, job_id, stage, ordinal, admission_token, deadline) + SELECT uuidv7(), tenant_id, id, 'normal', ordinal, uuidv7(), clock_timestamp() + interval '4 minutes' + FROM background_jobs, (VALUES (1), (2)) AS attempts(ordinal) WHERE id = '{held.Value}' + UNION ALL + SELECT uuidv7(), tenant_id, id, 'normal', 1, uuidv7(), clock_timestamp() + interval '4 minutes' + FROM background_jobs WHERE id = '{neighbour.Value}'; + INSERT INTO background_job_reservations (tenant_id, capacity_group, job_id, attempt_id, reserved_at, released_at, release_reason) + SELECT j.tenant_id, j.capacity_group, j.id, a.id, clock_timestamp() - interval '1 minute', + CASE WHEN a.ordinal = 2 AND j.id = '{held.Value}' THEN clock_timestamp() END, + CASE WHEN a.ordinal = 2 AND j.id = '{held.Value}' THEN 'completed' END + FROM background_jobs j JOIN background_job_attempts a ON a.job_id = j.id AND a.tenant_id = j.tenant_id + WHERE j.id IN ('{held.Value}', '{neighbour.Value}'); + """); + + var page = await proof.Inspection.InspectJobsAsync(proof.Admission(), null, 10); + + var row = page!.Items.Should().ContainSingle("only the quarantined job is listed").Which; + row.JobId.Should().Be(held.Value); + row.HeldReservations.Should().Be(1, "the released reservation of the job is not held"); + row.GroupOccupancy.Should().Be(2, "the job's unreleased reservation and its neighbour's, both of one capacity group"); + } + + [Fact] + public async Task A_cursor_belongs_to_the_resource_and_state_that_issued_it_even_when_its_key_is_valid_for_another() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + for (var index = 1; index <= 2; index++) + { + await proof.OutboxAsync(Guid.CreateVersion7(), $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index} 12:00:00+00'"); + await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index} 12:00:00+00'"); + } + + var outbox = (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + var delivery = (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + outbox.Should().NotBeNull(); + delivery.Should().NotBeNull(); + + // Each was issued for the route and state it came from: the same position under another one is refused. + (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().NotBeNull(); + } + + [Fact] + public async Task Deliveries_page_through_equal_instants_without_a_repeat_or_a_gap() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var ids = Enumerable.Range(0, 5).Select(_ => Guid.CreateVersion7()).ToArray(); + foreach (var id in ids) + await proof.DeliveryAsync(id, Subscription, "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.000001+00'"); + + var seen = new List(); + string? cursor = null; + var pages = 0; + do + { + var page = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, cursor, 2); + seen.AddRange(page!.Items.Select(row => row.EventId)); + cursor = page.NextCursor; + pages++; + } + while (cursor is not null && pages < 10); + + pages.Should().Be(3); + seen.Should().BeEquivalentTo(ids, "every row once").And.OnlyHaveUniqueItems(); + seen.Should().Equal(ids.OrderBy(id => id), "equal instants are ordered by the row's own key"); + } + + [Fact] + public async Task Terminal_requested_rows_page_in_the_order_their_dead_letter_is_due() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var late = Guid.CreateVersion7(); + var early = Guid.CreateVersion7(); + await proof.OutboxAsync(late, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-03 12:00:00+00'"); + await proof.OutboxAsync(early, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-02 12:00:00+00'"); + + var first = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 1); + var second = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, first!.NextCursor, 1); + + first.Items.Single().EventId.Should().Be(early); + second!.Items.Single().EventId.Should().Be(late); + second.NextCursor.Should().BeNull(); + } + + [Fact] + public async Task The_platform_role_can_select_exactly_the_twelve_outbox_columns_the_inspection_projects() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT attname FROM pg_attribute + WHERE attrelid = 'outbox_messages'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'outbox_messages', attnum, 'SELECT') + ORDER BY attname + """, (NpgsqlConnection)platform); + var granted = new List(); + await using (var reader = await command.ExecuteReaderAsync()) + while (await reader.ReadAsync()) granted.Add(reader.GetString(0)); + + granted.Should().Equal( + "attempts", "available_after", "dead_lettered_at", "id", "last_error", "locked_until", "occurred_at", + "organization_id", "processed_at", "tenant_id", "terminal_reason", "type"); + } + + [Theory] + [InlineData("publish:failed:provider", "publish:failed:provider")] + [InlineData("migration:legacy:redacted", "migration:legacy:redacted")] + [InlineData("stored text", "unrecognized")] + [InlineData("Free Text With Spaces", "unrecognized")] + public async Task The_last_error_a_page_shows_is_a_descriptor_or_the_word_unrecognized(string stored, string shown) + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.OutboxAsync(Guid.CreateVersion7(), $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); + await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); + + var outbox = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + var delivery = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + + outbox!.Items.Single().LastError.Should().Be(shown); + delivery!.Items.Single().LastError.Should().Be(shown); + } + [IntegrationEventPartition(nameof(TenantId), tenantWide: true)] public sealed record InspectionEvent : IntegrationEventBase { @@ -244,7 +390,7 @@ INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization return rows; } - private Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); + internal Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); public async ValueTask DisposeAsync() { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs new file mode 100644 index 00000000..4c495ece --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs @@ -0,0 +1,47 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Wraps the real audit store and hands the operator-recovery row to a test before it is written, so a test can +/// substitute a field of the draft or the transaction and watch the real store refuse it. +/// +internal sealed class OperatorRecoveryAuditDecorator( + IAuditStore inner, + Func recovery) : IAuditStore +{ + public Task WriteGlobalIdentityPendingAsync(IUnitOfWork unitOfWork, GlobalIdentityCreationReference creation, + CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unitOfWork, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + + public Task WritePendingAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + inner.WritePendingAsync(unitOfWork, cancellationToken); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => + inner.WriteStandaloneAsync(entry, cancellationToken); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => + inner.WriteBestEffortAsync(entry, cancellationToken); + + public Task WritePlatformScopeAsync(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken = default) => + inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => + inner.WriteEventTerminalAsync(entry, transition, connection, transaction, cancellationToken); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => + inner.WriteJobTerminalAsync(entry, transition, connection, transaction, cancellationToken); + + public Task WriteOperatorRecoveryAsync(AuditEntryDraft entry, OperatorRecoveryTransition transition, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) => + recovery(entry, transition, connection, transaction, cancellationToken); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs new file mode 100644 index 00000000..ccb0b6ba --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs @@ -0,0 +1,51 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using LearnStack.Infrastructure.PlatformOperator; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Captures the operator recovery counters while it lives. The counters are process-wide, so a test reads the +/// difference its own calls made and filters by operation, and no other test calls the recovery owner. +/// +internal sealed class OperatorRecoveryMeterProbe : IDisposable +{ + private readonly MeterListener _listener = new(); + private readonly ConcurrentBag<(string Counter, string Operation, string? Outcome, long Value)> _measurements = []; + + public OperatorRecoveryMeterProbe() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name is PlatformOperatorMetrics.RecoveryCounterName or PlatformOperatorMetrics.ResultCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value?.ToString(); + if (tag.Key == "outcome") outcome = tag.Value?.ToString(); + } + + _measurements.Add((instrument.Name, operation ?? string.Empty, outcome, value)); + }); + _listener.Start(); + } + + /// The recoveries counted for the operation under the outcome label. + public long Recoveries(string operation, string outcome) => _measurements + .Where(m => m.Counter == PlatformOperatorMetrics.RecoveryCounterName && m.Operation == operation && m.Outcome == outcome) + .Sum(m => m.Value); + + /// The MUST result rows counted for the operation. + public long Results(string operation) => _measurements + .Where(m => m.Counter == PlatformOperatorMetrics.ResultCounterName && m.Operation == operation) + .Sum(m => m.Value); + + public void Dispose() => _listener.Dispose(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs index 1149b998..1bf61eff 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs @@ -1035,6 +1035,24 @@ public async Task Reset_refuses_every_reason_but_retry_exhaustion(string reason) (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); } + [Fact] + public async Task Reset_reports_a_stale_fence_before_it_reports_a_refused_state() + { + // The fence is compared before the state: an operator who read an older row is told to read it again, and is not + // told the row is refused, even when the tenant has since stopped serving. + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + var result = await ResetAsync(test.Store(), test, id, change: request => request with { Attempts = request.Attempts + 1 }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + [Theory] [InlineData("pending")] [InlineData("processed")] @@ -1185,6 +1203,150 @@ private sealed record AuditRow( Guid Tenant, Guid? Organization, Guid Actor, string Module, string Operation, string Type, string Class, string Outcome, string? Reason, string Correlation, string Metadata); + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + [InlineData("operation")] + [InlineData("reason")] + [InlineData("metadata")] + [InlineData("correlation")] + [InlineData("actor")] + [InlineData("class")] + [InlineData("type")] + [InlineData("transaction")] + public async Task Substituting_a_field_of_the_reset_row_or_its_transaction_is_refused_by_the_real_seam_and_rolls_the_reset_back( + string substitution) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var calls = 0; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + calls++; + witness.Kind.Should().Be("reset"); + witness.EventId.Should().Be(id); + witness.TenantId.Should().Be(SchemaFixture.TenantA); + witness.OrganizationId.Should().Be(SchemaFixture.OrgA1); + if (substitution == "transaction") + { + await using var otherConnection = await test.DispatchSource.OpenConnectionAsync(cancellationToken); + await using var otherTransaction = await otherConnection.BeginTransactionAsync(cancellationToken); + await inner.WriteOperatorRecoveryAsync(draft, witness, otherConnection, otherTransaction, cancellationToken); + return; + } + + var changed = substitution switch + { + "tenant" => draft with { TenantId = TenantId.From(SchemaFixture.TenantB) }, + "organization" => draft with { OrganizationId = OrganizationId.From(SchemaFixture.OrgA2) }, + "operation" => draft with { Operation = PlatformOperations.DeliveryReplay.AuditSlug }, + "reason" => draft with { Reason = PlatformOperations.DeliveryReplay.ReasonSlug }, + "metadata" => draft with { Metadata = draft.Metadata + " " }, + "correlation" => draft with { CorrelationId = "00-forged" }, + "actor" => draft with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + "class" => draft with { OperationClass = OperationClass.Should }, + "type" => draft with { OperationType = OperationType.Update }, + _ => throw new ArgumentOutOfRangeException(nameof(substitution)), + }; + await inner.WriteOperatorRecoveryAsync(changed, witness, connection, transaction, cancellationToken); + })); + var before = await test.ReadAsync(id); + + var attempt = () => ResetAsync(store, test, id); + await attempt.Should().ThrowAsync(); + + calls.Should().Be(1, "the refusal must come from the real audit seam, after a successful UPDATE"); + (await test.ReadAsync(id)).Should().Be(before, "the reset and its row commit together or not at all"); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the same fence succeeds through the unmodified seam"); + } + + [Fact] + public async Task A_witness_from_an_earlier_reset_cannot_be_reused_on_a_later_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + OperatorRecoveryTransition? previous = null; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + await inner.WriteOperatorRecoveryAsync(draft, previous ?? witness, connection, transaction, cancellationToken); + previous = witness; + })); + var first = await test.InsertAsync(); + await test.SetStateAsync(first, DeadLetterRetryExhausted); + (await ResetAsync(store, test, first)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + var second = await test.InsertAsync(); + await test.SetStateAsync(second, DeadLetterRetryExhausted); + var before = await test.ReadAsync(second); + + var attempt = () => ResetAsync(store, test, second); + await attempt.Should().ThrowAsync(); + + (await test.ReadAsync(second)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle("only the first reset committed"); + } + + [Fact] + public async Task The_recovery_owner_resets_through_the_outbox_store_and_counts_each_outcome_under_the_reset_operation() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var fence = await test.ReadAsync(id); + var request = new OutboxResetRequest(SchemaFixture.TenantA, id, fence.Attempts, fence.DeadLetteredAt!.Value); + var owner = new OperatorRecovery(test.DeliveryStore(), test.Store()); + using var meters = new OperatorRecoveryMeterProbe(); + + var applied = await owner.ResetOutboxAsync(ResetAdmission(), request); + var stale = await owner.ResetOutboxAsync(ResetAdmission(), request); + var unknown = await owner.ResetOutboxAsync(ResetAdmission(), request with { EventId = Guid.CreateVersion7() }); + + (applied.Outcome, stale.Outcome, unknown.Outcome).Should().Be( + (OperatorRecoveryOutcome.Applied, OperatorRecoveryOutcome.StaleFence, OperatorRecoveryOutcome.NotFound)); + (await test.ReadAsync(id)).Attempts.Should().Be(0, "the owner reached the outbox store and no other"); + var reset = PlatformOperations.DeliveryReset.AuditSlug; + var replay = PlatformOperations.DeliveryReplay.AuditSlug; + (meters.Recoveries(reset, "applied"), meters.Recoveries(reset, "stale_fence"), meters.Recoveries(reset, "not_found")) + .Should().Be((1, 1, 1)); + meters.Results(reset).Should().Be(1, "only an applied reset committed a result row"); + meters.Recoveries(replay, "applied").Should().Be(0, "a producer reset is never counted as a delivery replay"); + } + + [Fact] + public async Task The_operator_lane_is_its_own_slot_so_a_busy_operator_never_costs_the_dispatcher_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var first = await test.InsertAsync(); + var second = await test.InsertAsync(); + await test.SetStateAsync(first, DeadLetterRetryExhausted); + await test.SetStateAsync(second, DeadLetterRetryExhausted); + var store = test.Store(); + + // Hold the first row's lock, so the first reset waits inside the operator lane. + await using var holder = await test.DispatchSource.OpenConnectionAsync(); + await using var holding = await holder.BeginTransactionAsync(); + await using (var hold = new NpgsqlCommand("SELECT 1 FROM outbox_messages WHERE id = @id FOR UPDATE", holder, holding)) + { + hold.Parameters.AddWithValue("id", first); + await hold.ExecuteScalarAsync(); + } + + var waiting = ResetAsync(store, test, first); + await test.WaitForLockWaitAsync(); + + var busy = () => ResetAsync(store, test, second); + await busy.Should().ThrowAsync("one operator call at a time per store"); + (await store.ReadSnapshotAsync(NoBlockedPartitions)).Should().NotBeNull("the dispatcher's own slots are untouched"); + + await holding.CommitAsync(); + (await waiting).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await ResetAsync(store, test, second)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the lane is free again once the first call ends"); + } + private sealed class TestDatabase : IAsyncDisposable { private readonly DisposableSchemaDatabase _database; @@ -1199,6 +1361,19 @@ private TestDatabase(DisposableSchemaDatabase database) } public NpgsqlDataSource DispatchSource { get; } + + public async Task WaitForLockWaitAsync() + { + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await using var connection = await DispatchSource.OpenConnectionAsync(); + while (true) + { + await using var command = new NpgsqlCommand( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock')", connection); + if (await command.ExecuteScalarAsync(deadline.Token) is true) return; + await Task.Delay(10, deadline.Token); + } + } public ServiceProvider Provider { get; } public string OutboxConnectionString => _database.OutboxConnectionString; @@ -1217,6 +1392,12 @@ public static async Task CreateAsync(PostgresFixture postgres, boo } } + /// The subscriber store beside the producer store, for a test that builds the recovery owner over both. + public DeliveryDispatchStore DeliveryStore() => new( + new PrivilegedDataSource(() => DispatchSource), EligibleRegistry(), new DeliveryDispatchOptions(), + new SystemGuidFactory(), new FixedClock(Occurred), Provider.GetRequiredService(), + BackgroundJobLifecycleProjectionDeclaration.Create()); + public OutboxDispatchStore Store( OutboxEventRegistry? registry = null, IClock? clock = null, Func? decorate = null, NpgsqlDataSource? dispatchSource = null) => new( diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs index 15c5e160..29d7e0e0 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs @@ -98,7 +98,7 @@ public sealed class PostgresFixture : IAsyncLifetime private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:18.4-alpine") .WithDatabase(Database) // Qualification can hold the supported job application (128) and - // privileged (158) source boundaries together, plus fixture observers. + // privileged (160) source boundaries together, plus fixture observers. .WithCommand("-c", "max_connections=300", "-c", "log_error_verbosity=terse", "-c", "log_min_error_statement=panic", "-c", "log_statement=none", "-c", "log_min_duration_statement=-1", "-c", "log_min_duration_sample=-1", diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index 4cd7a817..9244f50f 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -518,9 +518,29 @@ string[] RequiredOf(string route) .Should().Contain(["attempts", "deadLetteredAt"]); foreach (var route in OperatorRoutes) { - root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("responses").EnumerateObject() - .Select(response => response.Name).Should().Contain(["413", "429"], route); + var statuses = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("responses") + .EnumerateObject().Select(response => response.Name).ToArray(); + if (VerbOf(route) == "get") + { + statuses.Should().Contain("429", route).And.NotContain(["404", "409", "413", "415"], "a read has no body, no row to find and no state to refuse: " + route); + } + else + { + statuses.Should().Contain(["413", "429"], route); + } } + + // The page parameters are declared by their rule, not only described: the closed state set, the size range, + // the ticket's shape and the cursor's bound. + JsonElement ParameterOf(string route, string name) => root.GetProperty("paths").GetProperty(route).GetProperty("get") + .GetProperty("parameters").EnumerateArray().Single(parameter => parameter.GetProperty("name").GetString() == name) + .GetProperty("schema"); + var outbox = "/api/platform/v1/asynchronous-work/outbox-messages"; + ParameterOf(outbox, "state").GetProperty("enum").EnumerateArray().Select(value => value.GetString()) + .Should().BeEquivalentTo(["dead_lettered", "terminal_requested"]); + ParameterOf(outbox, "limit").GetProperty("minimum").GetRawText().Trim('"').Should().Be("1"); + ParameterOf(outbox, "cursor").GetProperty("maxLength").GetInt32().Should().Be(512); + ParameterOf(outbox, "ticket").GetProperty("pattern").GetString().Should().Be(@"^[A-Za-z0-9._:/#-]{1,64}$"); } private const string Work = "/api/platform/v1/asynchronous-work"; @@ -554,6 +574,8 @@ public async Task An_Inspection_Passes_Its_Parameters_On_Clamps_The_Limit_And_An [InlineData("limit=abc")] [InlineData("limit=-1")] [InlineData("limit=1.5")] + [InlineData("limit=0")] + [InlineData("limit=99999999999")] [InlineData("ticket=has%20space")] public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failure_Before_Any_Scope(string query) { @@ -563,6 +585,106 @@ public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failu _inspection.Calls.Should().BeEmpty(); } + [Theory] + [InlineData("limit=0", "limit")] + [InlineData("limit=-3", "limit")] + [InlineData("state=bogus", "state")] + public async Task A_Refused_Page_Parameter_Names_Itself_As_Standard_04_Asks(string query, string field) + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("errors").TryGetProperty(field, out _).Should().BeTrue(field); + _inspection.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task The_Quarantined_Jobs_List_Takes_No_State_And_Refuses_One_After_The_Gate() + { + var refused = await Call(HttpMethod.Get, Work + "/quarantined-jobs?state=terminal_requested", Valid()); + + refused.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using (var body = JsonDocument.Parse(await refused.Content.ReadAsStringAsync())) + { + body.RootElement.GetProperty("errors").TryGetProperty("state", out _).Should().BeTrue(); + } + + _inspection.Calls.Should().BeEmpty(); + (await Call(HttpMethod.Get, Work + "/quarantined-jobs?state=terminal_requested", Sign(("sub", "someone-else")))) + .StatusCode.Should().Be(HttpStatusCode.Forbidden, "the gate answers before a parameter is read"); + } + + [Fact] + public async Task An_Inspection_Whose_Database_Fault_Surfaces_Is_A_Retryable_503_Whose_Body_Agrees_With_Its_Status() + { + _inspection.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + + var response = await Call(HttpMethod.Get, Work + "/outbox-messages", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + body.RootElement.ToString().Should().NotContain("forced", "the cause is for the log and never for the response"); + } + + [Theory] + [InlineData(HeldKey.None)] + [InlineData(HeldKey.Read)] + [InlineData(HeldKey.Write)] + public async Task The_Read_And_Write_Delivery_Permissions_Admit_Only_Their_Own_Routes_And_The_Killswitch_Grant_Neither( + HeldKey held) + { + // ADR-0103 Decision table. Every other test here runs as an operator who holds all three keys, so none of them can tell + // which key a route asks for. This one holds exactly one key, and the other routes must refuse it. + var key = held switch + { + HeldKey.Read => PlatformPermissions.DeliveryRead.Key, + HeldKey.Write => PlatformPermissions.DeliveryWrite.Key, + _ => PlatformPermissions.KillswitchWrite.Key, + }; + var recovery = new RecordingRecovery(); + var inspection = new RecordingInspection(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => + { + registrations.AddSingleton(recovery); + registrations.AddScoped(_ => inspection); + }, + permissions: [key]); + using var client = single.CreateClient(); + + async Task Send(HttpMethod method, string path, string? json) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + Valid() } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return (await client.SendAsync(request)).StatusCode; + } + + var reads = new[] { Work + "/outbox-messages", Work + "/event-deliveries", Work + "/quarantined-jobs" }; + foreach (var path in reads) + { + (await Send(HttpMethod.Get, path, null)).Should().Be( + held == HeldKey.Read ? HttpStatusCode.OK : HttpStatusCode.Forbidden, path); + } + + (await Send(HttpMethod.Post, ReplayPath, ReplayBody)).Should().Be( + held == HeldKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden, ReplayPath); + (await Send(HttpMethod.Post, ResetPath, ResetBody)).Should().Be( + held == HeldKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden, ResetPath); + inspection.Calls.Count.Should().Be(held == HeldKey.Read ? reads.Length : 0); + recovery.Calls.Count.Should().Be(held == HeldKey.Write ? 2 : 0); + } + + public enum HeldKey + { + None, + Read, + Write, + } + [Fact] public async Task A_Cursor_The_Service_Refuses_Is_A_Validation_Failure_And_A_Failed_Audit_Write_Is_A_Retryable_503() { @@ -639,15 +761,17 @@ public async Task A_Replay_Body_That_Cannot_Be_A_Fence_Is_A_Validation_Failure_A } [Theory] - [InlineData("/event-deliveries/not-a-guid/orders.notify.v1/" + RowEvent + "/replay")] - [InlineData("/event-deliveries/" + RowTenant + "/Not.A.Subscription/" + RowEvent + "/replay")] - [InlineData("/event-deliveries/00000000-0000-0000-0000-000000000000/orders.notify.v1/" + RowEvent + "/replay")] - [InlineData("/event-deliveries/" + RowTenant + "/orders.notify.v1/00000000-0000-0000-0000-000000000000/replay")] - public async Task A_Replay_Route_Naming_No_Real_Row_Is_Refused_Without_Calling_The_Owner(string suffix) + [InlineData("/event-deliveries/not-a-guid/orders.notify.v1/" + RowEvent + "/replay", HttpStatusCode.NotFound)] + [InlineData("/event-deliveries/" + RowTenant + "/Not.A.Subscription/" + RowEvent + "/replay", HttpStatusCode.BadRequest)] + [InlineData("/event-deliveries/00000000-0000-0000-0000-000000000000/orders.notify.v1/" + RowEvent + "/replay", HttpStatusCode.BadRequest)] + [InlineData("/event-deliveries/" + RowTenant + "/orders.notify.v1/00000000-0000-0000-0000-000000000000/replay", HttpStatusCode.BadRequest)] + public async Task A_Replay_Route_Naming_No_Real_Row_Is_Refused_Without_Calling_The_Owner(string suffix, HttpStatusCode expected) { + // A tenant that is not a UUID matches no route; the nil identifiers and a malformed subscription match it and + // are refused by the route's own checks, after the gate. var response = await Call(HttpMethod.Post, Work + suffix, Valid(), ReplayBody); - response.StatusCode.Should().BeOneOf(HttpStatusCode.BadRequest, HttpStatusCode.NotFound); + response.StatusCode.Should().Be(expected); _recovery.Calls.Should().BeEmpty(); } @@ -694,7 +818,16 @@ public async Task An_Owner_That_Cannot_Finish_Or_Whose_Commit_Is_Unknown_Or_Whos response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); response.Headers.RetryAfter.Should().NotBeNull(reason); - (await response.Content.ReadAsStringAsync()).Should().Contain(reason); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain(reason); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503, "the body's status never disagrees with the response's: " + reason); + body.RootElement.GetProperty("code").GetString().Should().Be( + reason == "outcome_unknown" ? "dependency_unavailable" : reason); + if (reason == "outcome_unknown") + { + body.RootElement.GetProperty("errors").GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } } } @@ -727,7 +860,6 @@ public async Task The_Production_Composition_Resolves_The_Recovery_Owner_And_The .Should().BeOfType(); scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); - await Task.CompletedTask; } private static readonly string[] OperatorRoutes = @@ -1032,7 +1164,8 @@ private sealed class PlatformOperatorApiFactory( IKillswitchToggle toggle, string grantSubject = Subject, bool configured = true, - Action? services = null) : ConstructionOnlyApiFactory + Action? services = null, + string[]? permissions = null) : ConstructionOnlyApiFactory { protected override void ConfigureTestHost(IWebHostBuilder builder) { @@ -1044,9 +1177,15 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) builder.UseSetting("PlatformOperator:AcceptedAcr:0", "mfa"); builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); builder.UseSetting("PlatformOperator:Grants:0:Subject", grantSubject); - builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", PlatformPermissions.KillswitchWrite.Key); - builder.UseSetting("PlatformOperator:Grants:0:Permissions:1", PlatformPermissions.DeliveryRead.Key); - builder.UseSetting("PlatformOperator:Grants:0:Permissions:2", PlatformPermissions.DeliveryWrite.Key); + var held = permissions ?? + [ + PlatformPermissions.KillswitchWrite.Key, PlatformPermissions.DeliveryRead.Key, + PlatformPermissions.DeliveryWrite.Key, + ]; + for (var index = 0; index < held.Length; index++) + { + builder.UseSetting("PlatformOperator:Grants:0:Permissions:" + index, held[index]); + } } builder.ConfigureTestServices(registrations => diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs index ce64eba8..68cacea7 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs @@ -21,7 +21,7 @@ public sealed class BackgroundJobRuntimeProductionCompositionTests [Fact] public async Task Mandatory_hosted_aliases_bind_the_actual_messaging_instances_and_keep_the_source_lazy() { - var builder = Builder(52); + var builder = Builder(54); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Services.AddLearnStackOutboxDispatcher(builder.Configuration); await using var services = builder.Services.BuildServiceProvider(); @@ -54,7 +54,7 @@ public async Task Mandatory_hosted_aliases_bind_the_actual_messaging_instances_a [Fact] public async Task Captured_capacity_refuses_one_below_the_supported_floor_before_source_construction() { - var builder = Builder(51); + var builder = Builder(53); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Configuration["ConnectionStrings:OutboxDispatcher"] = Connection(100); await using var services = builder.Services.BuildServiceProvider(); @@ -62,7 +62,7 @@ public async Task Captured_capacity_refuses_one_below_the_supported_floor_before var resolve = () => services.GetRequiredService(); resolve.Should().Throw().WithMessage("*supported physical capacity*"); source.IsValueCreated.Should().BeFalse(); - services.GetRequiredService().MaxPoolSize.Should().Be(51, + services.GetRequiredService().MaxPoolSize.Should().Be(53, "the source and its sanitized settings must use the same immutable registration input"); } @@ -72,7 +72,7 @@ public async Task Captured_capacity_refuses_one_below_the_supported_floor_before public async Task Captured_application_capacity_includes_external_work_before_either_source_is_constructed( int maximum, bool accepted) { - var builder = Builder(52); + var builder = Builder(54); builder.Configuration["ConnectionStrings:Default"] = ApplicationConnection(maximum); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Services.AddLearnStackOutboxDispatcher(builder.Configuration); diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 2f074e81..3492ffcb 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -88,6 +88,30 @@ public async Task The_Rebind_Operation_Is_Admitted_Only_For_The_Identity_Authori rebind.NeedsPlatformRole.Should().BeFalse(); } + [Theory] + [InlineData("platform.delivery.inspect", "platform.delivery.read")] + [InlineData("platform.delivery.replay", "platform.delivery.write")] + [InlineData("platform.delivery.reset", "platform.delivery.write")] + public async Task A_Recovery_Operation_Is_Admitted_Only_For_Its_Own_Delivery_Permission(string slug, string permission) + { + // ADR-0103 Decision table: inspecting needs platform.delivery.read, and the two acts need platform.delivery.write. The pair + // is pinned both ways: the table says which key each operation binds, and no other Platform key, the other + // delivery key and the killswitch key included, admits it. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == slug); + operation.Permission.Key.Should().Be(permission); + + var admitted = await Gate(Grants("operator-1", permission)) + .AdmitAsync(TestPlatformAdmissions.Witness(), operation, "CHG-103"); + admitted.IsAdmitted.Should().BeTrue(); + admitted.Admission!.Operation.Should().BeSameAs(operation); + + foreach (var other in PlatformPermissions.All.Where(candidate => candidate.Key != permission)) + { + (await Gate(Grants("operator-1", other.Key)).AdmitAsync(TestPlatformAdmissions.Witness(), operation, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, other.Key); + } + } + [Fact] public async Task A_Grant_For_Another_Permission_Does_Not_Admit() { diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md index 03dddd4a..bc9eb749 100644 --- a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -86,6 +86,12 @@ dashboard. causal column, so the database refuses what the projection must not return. Grant tests read column privileges. Each row returns the fence its transition needs. A row whose terminal request is pending shows its state and is not actionable. + + > **Erratum (2026-11-20, Amendment 1 items 2 and 6).** The platform role already + > held table-wide `SELECT` on `outbox_messages`, so named column grants beside it + > would have excluded nothing: the migration revokes it first. The scope's entry row + > carries the operation `platform.admin_scope.enter` and the reason + > `delivery_inspect`, not the slug `platform.delivery.inspect` as an operation. 2. **Targeted subscriber replay.** `platform.delivery.replay` resets one `(tenant, subscription, event)` delivery. The request carries the fence read at inspection: `replay_count`, `dead_lettered_at` and `terminal_reason`. It is refused @@ -123,6 +129,13 @@ dashboard. rolls the transition back and answers 503 with no state change. A stale fence answers 409 `stale_fence`, a refused state 409 `not_recoverable`, and neither writes a row or changes state. + + > **Erratum (2026-11-20, Amendment 1 items 3 and 4).** The witness is a sibling + > class with two kinds, not a new kind of the terminal witness, and `stale_fence` + > and `not_recoverable` are reasons on the fields `fence` and `state` of the code + > `business_rule_violation`, because the status map is closed. A commit whose + > answer was lost is `503` `dependency_unavailable` with the reason + > `outcome_unknown` on the field `outcome`. 6. **Not admitted: job recovery.** No job requeue, retry, probe re-arm, reservation or capacity release exists. A quarantined job stays frozen, retains its reservation and keeps `jobs` unhealthy, exactly as @@ -291,9 +304,15 @@ recovery. stale fence is `409` `business_rule_violation` with the reason `lockey_stale_fence` on the field `fence`, and a refused state is `409` with `lockey_not_recoverable` on the field `state`, as the onboarding acts already answer. A missing row is `404`. A - MUST row that cannot be written, an unavailable lane or database, and a commit whose - answer was lost are `503` with `Retry-After`, the last with its own reason - `outcome_unknown`. + MUST row that cannot be written, an unavailable lane or database, a failed + inspection read and a commit whose answer was lost are `503` with `Retry-After`. The + last is `dependency_unavailable` with the reason `lockey_outcome_unknown` on the + field `outcome`, so the body's status agrees with the response's: a new top-level + code would have answered `500` in the body under a `503` response. The cause of an + unavailable owner is logged and never returned. A page parameter that is refused + (`state`, `limit`, `cursor`) is `400` naming itself in `errors`; a `limit` of zero or + less is refused and a larger one is clamped, as Standard 04 says, and the + quarantined-jobs list takes no `state`. 5. **"The event's tenant is Active."** The test is the lifecycle projection the dispatcher role already reads, read in the same transaction as the reset: the tenant is not deleted, has its default organization and is Trial or Active, which is the @@ -302,20 +321,37 @@ recovery. retired or no longer knows, because a reset would only dead-letter it again with a second MUST row. 6. **Inspection.** Each page is one entered platform scope on the platform role's column - grants, so the scope's entry row, which names `platform.delivery.inspect` and carries - the ticket and the operator's attribution, is the audit. The scope reads and changes - nothing, so it writes no result row and ends by disposal; the slug is still declared - off-path, because the scope refuses an operation that is not. Pages are keyset - cursors bound to their resource and state, 1 to 100 rows, and a cursor carries no - authority. The fence timestamp is the stored microsecond, returned and compared - exactly. + grants, so the scope's entry row is the audit. Its operation is + `platform.admin_scope.enter` and its reason is `delivery_inspect`, the reason of the + admitted operation `platform.delivery.inspect`; it carries the ticket and the + operator's attribution, and it does not say which of the three lists was read. The + scope reads and changes nothing, so it writes no result row and ends by disposal; the + slug is still declared off-path, because the scope refuses an operation that is not. + A row's `lastError` is shown only when it has the shape of the dispatcher's + descriptors (`publish:failed:provider`) and is `unrecognized` otherwise, because the + database bounds the length of that column and not its content. `actionable` is the + row's and the registry's advice: the tenant's service state is read by the + transition, so a row of a suspended tenant can be listed actionable and refused. + Pages are keyset cursors bound to their resource and state, 1 to 100 rows, and a + cursor carries no authority. The fence timestamp is the stored microsecond, + returned and compared exactly. 7. **An unknown COMMIT is not reconciled automatically.** A reset and its row commit together, so a lost answer leaves nothing to repair: the operator inspects, and the fence of a landed reset has moved, so a repeat answers `409` on the fence. The - runbook says so. + runbook says so. Any fault after the COMMIT was sent, the connection's cleanup + included, is reported the same way, because the answer is then unknown. A cleanup + fault on the operator lane seals its store as one on the dispatcher's lanes does: + the stores share the unconfirmed-cleanup seal, which only a restart clears. 8. **Signals.** `learnstack_platform_operator_recoveries_total{operation,outcome}` counts each transition as applied, stale fence, not recoverable, not found, unavailable or commit unknown, so a replay storm is visible. +9. **A producer reset of a type that is not yet Active.** The reset refuses a retired + or unknown type and acts on a pending one, whose row the dispatcher claims once the + type is Active, as it claims any row of that type; a replay refuses it, because it + needs an Active ordinary subscription. +10. **The tenant test is not locked.** The lifecycle read and the transition share a + transaction but not a lock, so a suspension that commits between them does not stop + the transition. P03-10 (G16) re-verifies this with the replay floor after erasure. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index 4910e829..4792f4eb 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -11,9 +11,9 @@ the producer writer, with both review rounds complete; P02b-3 Step 4 implements the subscriber writer with both review rounds complete. P03-9 Step 4 adds the operator's fenced recovery writer, `platform.delivery.replay` and `platform.delivery.reset`, on the same off-path matrix -([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Phase 03 owns privileged -erasure execution and its bounded -caller contract; Phase 11 owns retention purge. +([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Phase 03 owns +privileged erasure execution and its bounded caller contract; Phase 11 owns retention +purge. **The module that owns the log is audited like any other.** Reading someone's audit trail is itself a sensitive read; exporting it produces a copy that outlives the diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index fb6ccc67..06c64c88 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -146,7 +146,7 @@ unmarked row is one a shipped command already raises. |---|---|---|---| | `outbox_messages` | `platform.outbox.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-2 Step 2's consequential BYPASSRLS terminal transition; state and row commit together through the row-bound fifth audit seam, with stored tenant/org/event identity and SystemActor ([ADR-0046](../../decisions/0046-durable-event-delivery-and-recovery.md)) | | delivery ledger | `platform.delivery.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-3 Step 4's subscriber terminal writer binds stored tenant/org/event/subscription, acquisition token, reason and attempts to the actual fenced transition; ledger and MUST audit commit together through the same restricted fifth seam. It receives no causal-envelope or payload SELECT grant | -| delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation names this slug, with the closed reason `delivery_inspect` and the operator attribution and ticket in `metadata.operator`; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | +| delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | | delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index be540316..df31b04a 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 790 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 898 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -519,6 +519,8 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 3 — controlled issuer rebind (2026-11-20)](#p03-9-step-3--controlled-issuer-rebind-2026-11-20) — 107 lines - [P03-9 Step 3 — review round 1 and its fixes (2026-11-20)](#p03-9-step-3--review-round-1-and-its-fixes-2026-11-20) — 23 lines - [P03-9 Step 3 — review round 2 and its fixes (2026-11-20)](#p03-9-step-3--review-round-2-and-its-fixes-2026-11-20) — 70 lines + - [P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20)](#p03-9-step-4--operator-recovery-of-asynchronous-work-2026-11-20) — 59 lines + - [P03-9 Step 4 — review round 1 and its fixes (2026-11-20)](#p03-9-step-4--review-round-1-and-its-fixes-2026-11-20) — 49 lines @@ -24966,3 +24968,111 @@ Two branches have no case that reaches them and are recorded: the refusal for se settings the server did not apply (it needs a pooler in the path), and the stdin wait ending on a signal. Both are small, and the first is checked in the positive on every run. + +### P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20) + +Step 4 delivers [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md): +a metadata-only inspection of dead-lettered work and two fenced transitions, and no +dashboard and no job recovery. The decision was Accepted in `a396f50e`; this record is +the implementation and its proof, and ADR-0103 Amendment 1 records where the code +corrected the Decision. + +Delivered: + +- **The seam.** `platform.delivery.read` and `platform.delivery.write`, the three + operations `platform.delivery.inspect`, `platform.delivery.replay` and + `platform.delivery.reset` with their off-path declarations, and an executor kind on + every `PlatformOperation` (scope, pipeline, recovery owner, rebind tool) that replaces + the earlier pair of booleans. +- **The inspection.** `IDeliveryInspection` and `DeliveryInspection`: cursor-paged + metadata of dead-lettered and terminal-requested outbox rows and deliveries and of + quarantined jobs with their reservation occupancy, one entered platform scope per + page, on column grants. One forward-only Platform migration revokes the platform + role's table-wide `SELECT` on `outbox_messages` and grants twelve, fifteen, + twenty-seven and seven named columns of the four tables, and adds two partial indexes. +- **The two transitions.** `DeliveryDispatchStore.ReplayAsync` and the new + `OutboxDispatchStore.ResetAsync`, each a partial-class file: lock, fence, state and + tenant checks, one fenced `UPDATE ... RETURNING old.*, new.*` and a MUST row on the + same outbox-role transaction through the sibling witness `OperatorRecoveryTransition` + and the fourteenth `IAuditStore` write. Each store has a third connection slot for + the operator lane (capacity 52 to 54, 158 to 160), and `OperatorRecovery` is the DI + owner behind `IOperatorRecovery`. +- **The routes.** Three `GET` inspections and two `POST` acts under + `/api/platform/v1/asynchronous-work`, gate first, served in `platform-v1`. +- **Signals and documents.** `learnstack_platform_operator_recoveries_total`, the + runbook `operator-recovery.md`, ADR-0103 Amendment 1, Standards 05, 10, 18, 19, 20 and + 21, Architecture 15, 23 and 31, the module documents and the glossary. + +Where the code corrected the Decision (ADR-0103 Amendment 1, with inline errata beside +the statements in the Decision): + +- The platform role already held table-wide `SELECT` on `outbox_messages`, so the + migration revokes it before it grants twelve columns. +- The witness is a sibling class with two kinds, not a new kind of the terminal witness + whose census pins two factories. +- The status map is closed, so a stale fence and a refused state are reasons on the + fields `fence` and `state` of `business_rule_violation`, and an unknown commit + outcome is a reason on the field `outcome` of `dependency_unavailable`. +- The inspection's entry row carries the operation `platform.admin_scope.enter` and the + reason `delivery_inspect`; it does not say which list was read. + +Proof, against real PostgreSQL as each role: the current fence applies and every stale +variant refuses, one microsecond included; a stale fence is reported before a refused +state; each refused state, a tenant that is not serving and a type the registry has +retired or no longer knows; a forced audit failure rolls the change back; a wrong, +stale or spent admission; the operator lane in each store; a lost commit +acknowledgement and its repeat; the siblings and the inbox byte-identical after a +replay; the witness refusing each substituted field of its row and a foreign +transaction, and a reused witness; the real owner counting each outcome under its own +operation; the inspection's pages, cursors, occupancy counts and exact column +grants; the eleven routes, their statuses and the served contract; and each delivery +permission held alone. + +### P03-9 Step 4 — review round 1 and its fixes (2026-11-20) + +Three independent reviewers, each read-only, read the range from the implementation's +base to its commit: authority, security and the attack surface; correctness, +concurrency and failure windows; and tests, censuses and documentation. Each finding +was checked against the code before it was acted on; the three reports agreed on the +two that mattered most. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Tests | About forty integration test sites and three unit sites still pinned the old 52-connection floor, so every runtime fixture threw on construction | The sites derive the floor from the production manifest through one constant; the unit sites pin 54 and 53; the fixture comment says 160 | +| Contract | The unknown-commit `503` carried `status: 500` in its body, because the status map is closed and the reason was a new top-level code | It is `dependency_unavailable` with the reason on the field `outcome`; a test asserts the body's status for every `503` | +| Authority | Nothing pinned which permission each operation binds, and every HTTP case ran as an operator holding all three keys | A unit theory pins the pair both ways, and an HTTP theory holds each key alone against all five routes | +| Tests | The real owner ran in no test, its counters were unobserved, and no test showed the witness refusing a substituted field | Owner tests over the real stores read the counters by operation; a ten-field substitution matrix and a reused witness run for each store | +| Tests | The occupancy assertion was vacuous, the cursor test could not tell a bound scope from an invalid key, deliveries and terminal-requested rows were not paged, the outbox column inventory was open and the outbox operator lane was unproven | Each has its own test, seeded so that the guard decides the outcome | +| Contract | A `limit` of zero was clamped, a state on the jobs list was ignored, a refused page parameter named nothing, an inspection's database fault was a `500`, and a `503` logged no cause | Zero is refused naming `limit`, the jobs list refuses a state, each refusal names its parameter, the fault is a `503` and the cause is logged and never returned | +| Failure windows | A fault after the `COMMIT` was sent, the connection's cleanup included, was reported as nothing changed | Any such fault is reported as an unknown outcome; a missing lifecycle projection is a configuration error and no longer a transient `503` | +| Disclosure | `last_error` is bounded by length only, so stored text could reach the page | The page shows a descriptor-shaped value and `unrecognized` otherwise | +| Documents | Four documents said the entry row names `platform.delivery.inspect`; the access runbook omitted two credentials; the recovery runbook was wrong about reasons, queuing, refusals and the erasure owner; Standard 05 restated the ADR and claimed proofs that did not exist | Corrected; ADR-0103 carries inline errata beside the false text and Amendment 1 items 6, 7, 9 and 10; Standard 21 records the new consumer | +| OpenAPI | A read listed `404`, `413` and `415`, the page parameters were free strings and two texts called every act idempotent | Reads list none of the three, the parameters carry their enum, bounds and shape, and the texts say what a repeat answers | +| Censuses | The reset factory and the outbox reset overload had no mutation twin; two HTTP assertions were loose | Twins added; the assertions name their status | + +Mutation checks of the guards this step added: twenty-six single-line mutations of the +fence comparison, the state and tenant checks, the result row, the operator lane, the +witness binding, the permission pair, the page rules, the descriptor shape, the +occupancy counts, the cursor scope and the owner's counters. Three survived at first +because the fenced `UPDATE` repeats each predicate, so the early comparison only +decides whether a stale fence is reported before a refused state; one test per store +now pins that order, and all twenty-six are killed. + +#### Not changed + +- **`Cache-Control: no-store` on the operator `GET`s.** Steps 1 to 3 answer the same + way, and a shared cache does not store a response to a request that carries + `Authorization`. A response policy for the whole operator surface is the maintainer's + decision, not this step's. +- **Verb sub-paths `/replay` and `/reset`.** Standard 04 does not forbid them and the + decision names no path. +- **The fence as one opaque token.** The microsecond instant is kept exact, because the + comparison is the safety property; a client that truncates it is refused, never + wrongly admitted. The runbook says to send it back as returned. +- **A disposal fault after a successful `COMMIT`.** The code reports it as an unknown + outcome; no test can inject it, because Npgsql's disposal does not throw on a dead + socket. +- **A ticket on a replay or a reset.** It is checked and not stored, because the audit + row is readable by the tenant; the runbook says to record the correlation id. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index bbbd3851..976bab8e 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -22,7 +22,8 @@ The surface does not exist until an issuer is configured; with none, every | `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | | `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, as a time span such as `00:15:00`; at most one hour, default 15 minutes | | `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | -| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act runs under. Required for that act: without it the first act fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | +| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act and the [recovery](operator-recovery.md) inspections run under. Required for them: without it the first one fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | +| `ConnectionStrings:OutboxDispatcher` | The dispatcher's outbox-role credential, which the two recovery acts (replay and reset) use through the dispatcher's own stores. Without it they cannot run, as the dispatcher cannot | List settings are indexed in environment variables, and the double underscore is the separator: diff --git a/docs/runbooks/operator-recovery.md b/docs/runbooks/operator-recovery.md index 2847b325..3f935215 100644 --- a/docs/runbooks/operator-recovery.md +++ b/docs/runbooks/operator-recovery.md @@ -45,9 +45,11 @@ because the database refuses those columns to the platform role. ## Inspect Each page is one entered platform scope, so each page writes one -`platform.admin_scope.enter` audit row naming `platform.delivery.inspect`, with your -attribution and ticket. Pass the ticket as `?ticket=`: 1 to 64 letters, digits or -`.` `_` `:` `/` `#` `-`. +`platform.admin_scope.enter` audit row with the reason `delivery_inspect`, your +attribution and your ticket. It does not say which of the three lists you read or how +far you paged. Pass the ticket as `?ticket=`: 1 to 64 letters, digits or `.` `_` `:` +`/` `#` `-`. Inspections run on `ConnectionStrings:PlatformAdmin`; the two acts run on +`ConnectionStrings:OutboxDispatcher` ([setup](operator-access.md#what-must-be-configured)). ```sh curl -s -H "Authorization: Bearer $TOKEN" \ @@ -58,11 +60,15 @@ curl -s -H "Authorization: Bearer $TOKEN" \ row has a terminal reason recorded and the commit of its dead-letter not yet made: its state is shown and it is **not actionable**. It becomes dead-lettered by itself, or it does not. -- `limit` is 1 to 100 (default 20, larger values are clamped). The answer holds `items` and a `pageInfo` - with `nextCursor` and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs - to the route and state that issued it. -- Each row carries `eventType` as the registry's label (never stored text) and - `actionable`. Treat `actionable` as advice: the transition checks again. +- `limit` is 1 to 100 (default 20; a larger value is clamped, zero or less is refused + with `errors.limit`). The answer holds `items` and a `pageInfo` with `nextCursor` + and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs to the route and + state that issued it. The quarantined-jobs list takes no `state`. +- Each row carries `eventType` as the registry's label (never stored text), `lastError` + (a descriptor such as `publish:failed:provider`, or `unrecognized`) and `actionable`. + Treat `actionable` as advice about the row and the registry: the act also checks the + tenant's service state and the fence, so a suspended tenant's row can be listed + actionable and refused. - **The fence travels with the row.** A delivery shows `replayCount`, `deadLetteredAt`, `terminalReason`; an outbox row shows `attempts` and `deadLetteredAt`. `deadLetteredAt` has microsecond precision: send it back **exactly as returned**. @@ -81,8 +87,11 @@ curl -s -H "Authorization: Bearer $TOKEN" \ already reached a subscriber is absorbed by the event's stable identity; a delivery that already ended terminal needs its own replay. - **Neither** if the reason is `invalid_envelope`: the stored envelope is immutable and - cannot become valid. A reason of `unknown_type` or `retired_type` follows the registry - now: an event the registry still does not know, or has retired, is refused. + cannot become valid. For a *replay*, a reason of `unknown_type` or `retired_type` + follows the registry now: an event the registry still does not know, or has retired, + is refused, and one it knows again is replayed. A *producer reset* acts only on + `retry_exhausted`; any other reason is refused. A reset of a type that is not yet + Active is applied, and the dispatcher claims the row once the type is Active. ## Act @@ -104,13 +113,13 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ |---|---| | `200`, `outcome: applied` | The row was reset and its MUST audit row committed with it. `countAfter` is the new replay count, or zero attempts | | `409`, `errors.fence` = `lockey_stale_fence` | The row no longer shows the fence you sent: the dispatcher, another operator or a retry moved it. Nothing changed and nothing was written. **Inspect again** and decide again | -| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one a reset may act on: processed, leased, `invalid_envelope`, a reason a reset refuses, a subscription that is no longer Active, an event type the registry no longer knows, or a tenant that is not serving (not Trial or Active, or deleted). Nothing changed | +| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one an act may take: `invalid_envelope`, a reason a producer reset refuses, a subscription that is no longer Active, an event type the registry no longer knows, or a tenant that is not serving (not Trial or Active, or deleted). Nothing changed | | `404` | No such row for that tenant | | `403` | You hold no `platform.delivery.write` grant. Nothing was opened | -| `400` | The route, the body or the ticket is malformed. A refusal at the gate carries no per-field errors | +| `400` | The route, the body or the ticket is malformed. A refusal at the gate carries no per-field errors; a refused page parameter names itself (`errors.state`, `errors.limit`, `errors.cursor`) | | `503`, `audit_unavailable` | The MUST row could not be written, so nothing changed. Retry after the delay | -| `503`, `dependency_unavailable` | The outbox role's connection or its one operator lane was unavailable. Nothing changed. Only one operator call runs per store at a time; retry after the delay | -| `503`, `outcome_unknown` | The commit's answer was lost. It **may have landed**. **Inspect the row before repeating**: a landed reset shows an advanced `replayCount` (or `attempts` of zero), and a repeat of the same request would answer `409` `lockey_stale_fence` | +| `503`, `dependency_unavailable` | A connection, the one operator lane or an inspection's read was unavailable. Nothing changed. Only one operator call runs per store at a time, and a second is refused at once and not queued; retry after the delay. The cause is in the API's log, never in the response | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost, or a fault followed it. It **may have landed**. **Inspect the row before repeating**: a landed reset shows an advanced `replayCount` (or `attempts` of zero), and a repeat of the same request would answer `409` `lockey_stale_fence` | An applied replay makes the delivery due at once; the dispatcher claims it like any other. @@ -127,7 +136,9 @@ other. tenant) with no actor, the operation `platform.delivery.replay` or `platform.delivery.reset`, the reason `delivery_replay` or `delivery_reset`, your attribution in `metadata.operator` and the fence before and after in - `metadata.fence`. The ticket is not on it, because the tenant can read it. + `metadata.fence`. The ticket is not on it, because the tenant can read it: a + ticket sent with an act is checked and not stored, so record the response's + `correlationId` against your own change reference. ## Signals @@ -140,15 +151,18 @@ access](operator-access.md#signals). ## Limits -- **Erasure.** The rule that the tenant is serving is the guard until the erasure work +- **Erasure.** The rule that the tenant is serving is the guard until P03-10 (G16) defines what a replay may reach after a tenant's data is erased; it re-verifies these - transitions. Do not reset anything for a tenant that is being erased. + transitions. The check is not locked against a suspension that commits at the same + moment. Do not reset anything for a tenant that is being erased. - **The invitation path.** A stuck or unknown outbound invitation email is a *job*, and nothing here releases it. Reissuing an invitation helps only while the tenant has a free slot; it neither reconciles nor releases the old effect, and four unresolved effects can hold every slot with no operator remedy. - **Capacity.** The operator lane is one connection per store, so replays are one at a - time. A burst is slow on purpose. + time, and a second concurrent call is refused with `503` at once. Send them one after + another. A connection-cleanup fault on that lane seals its store as one on the + dispatcher's lanes does, and only a restart clears it. ## Not recoverable here diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 2efa5a2b..2c8a3bb1 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6483,62 +6483,83 @@ triggers) and the head pin in `MigrationRollbackTests`. ## Operator recovery storage -**Derives from:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and its -Amendment 1. Operator inspection reads metadata through the platform role's column grants, and the two -fenced transitions run on the dispatcher's outbox role. The canonical SQL of every grant and index -named here is in the [Outbox](#outbox), [Inbox](#inbox) and Background jobs blocks, which migration -tests compare with the applied schema, and the head of the Platform chain is pinned in +**Derives from:** +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and its +Amendment 1. Operator inspection reads metadata through the platform role's column +grants, and the two fenced transitions run on the dispatcher's outbox role. The +canonical SQL of every grant and index named here is in the [Outbox](#outbox), +[Inbox](#inbox) and Background jobs blocks, which migration tests compare with the +applied schema, and the head of the Platform chain is pinned in `MigrationRollbackTests`. ### The platform role's inspection grants -`learnstack_platform` holds `SELECT` on named columns of four tables and nothing wider: twelve columns -of `outbox_messages`, fifteen of `event_deliveries`, twenty-seven of `background_jobs` and every column -of `background_job_reservations`. It never reads `payload`, `metadata`, `correlation_id`, -`causation_id`, `actor_user_id`, `topic`, `partition_key`, `locked_by`, a job's `parameters`, `plan`, -`plan_fingerprint`, `traceparent`, a causal column, `operation_id` or an ownership or bridge token, so a -statement that names one is refused by PostgreSQL itself. The role kept `DELETE` on `outbox_messages` for -the retention purge of [Phase 11](../roadmap/phase-11-production-hardening.md), and the table-wide -`SELECT` it held beside it was revoked, because a column grant next to a table grant excludes nothing. -Column privileges are read from `information_schema.column_privileges`, as for every column-grant table. -Two partial indexes, `ix_outbox_messages_dead_lettered` and `ix_event_deliveries_dead_lettered`, serve the -dead-lettered scan the inspection pages by keyset. The migration is forward-only. +`learnstack_platform` holds `SELECT` on named columns of four tables and nothing +wider: twelve columns of `outbox_messages`, fifteen of `event_deliveries`, +twenty-seven of `background_jobs` and every column of `background_job_reservations`. +It never reads `payload`, `metadata`, `correlation_id`, `causation_id`, +`actor_user_id`, `topic`, `partition_key`, `locked_by`, a job's `parameters`, `plan`, +`plan_fingerprint`, `traceparent`, a causal column, `operation_id` or an ownership +or bridge token, so a statement that names one is refused by PostgreSQL itself. The +role kept `DELETE` on `outbox_messages` for the retention purge of +[Phase 11](../roadmap/phase-11-production-hardening.md), and the table-wide `SELECT` +it held beside it was revoked, because a column grant next to a table grant excludes +nothing. Column privileges are read from `information_schema.column_privileges`, as +for every column-grant table. The database bounds which columns a page can read and +the length of `last_error`, not its content, so the inspection shows a `last_error` +only when it has the shape of the dispatcher's descriptors. Two partial indexes, +`ix_outbox_messages_dead_lettered` and `ix_event_deliveries_dead_lettered`, serve +the dead-lettered scan the inspection pages by keyset. The migration is +forward-only. ### The two transitions -Both run on the outbox role, which already holds the column `UPDATE` grants they need, the lifecycle -`SELECT` of `tenants` and `INSERT` on `audit_log`: no write grant was added. Each locks one row with -`FOR UPDATE`, compares the fence the operator read, checks the state, and updates under the same predicate -with `RETURNING old.*` and `new.*`, so the witness is built from what the statement did and the row is -written on the same transaction before `COMMIT`. - -- **Replay** fences `(replay_count, dead_lettered_at, terminal_reason)` on one - `(tenant, subscription, event)` row of `event_deliveries`. It refuses a processed or leased row, the reason - `invalid_envelope`, a subscription that is not an Active ordinary one of the stored type and a tenant that is - not serving, clears the terminal fields and the lease, resets attempts, makes the row due, and adds one to - `replay_count`. The inbox row, the siblings and the producer row are untouched. -- **Producer reset** fences `(attempts, dead_lettered_at)` on one `outbox_messages` row and acts only on - `terminal_reason = 'retry_exhausted'` of a row not processed or leased whose stored type the registry still - knows. It clears the terminal fields, `last_error` and the lease, sets `attempts` to zero and makes the row - due. It writes no delivery row. - -The timestamp of a fence is `timestamptz` to the microsecond. It is carried and compared exactly, and a test -presents a fence one microsecond off. +Both run on the outbox role, which already holds the column `UPDATE` grants they +need, the lifecycle `SELECT` of `tenants` and `INSERT` on `audit_log`: no write +grant was added. Each locks one row with `FOR UPDATE`, compares the fence the +operator read, checks the state, and updates under the same predicate with +`RETURNING old.*` and `new.*`, so the witness is built from what the statement did +and the row is written on the same transaction before `COMMIT`. Which fences and +which states are refused is decided by ADR-0103 (§ 2, § 3 and Amendment 1) and is +not restated here. + +- **Replay** fences one `(tenant, subscription, event)` row of `event_deliveries` + and writes that table only. The inbox row, the siblings and the producer row are + untouched. +- **Producer reset** fences one `outbox_messages` row and writes that table only. + It writes no delivery row. + +The timestamp of a fence is `timestamptz` to the microsecond. It is carried and +compared exactly, and a test presents a fence one microsecond off. ### The operator lane -Each messaging store has two slots for the dispatcher's own SQL owner and its uncertain-COMMIT reconciliation -and a third, reserved for the operator owner. The operator never takes the dispatcher's slots, and a second -concurrent operator call on a store is refused. The lanes are two of the thirteen messaging and bridge slots in -the [capacity ledger](#shared-dispatcher-source-lifetime-and-capacity), which is 54 for the default topology -and 160 for the maximum. +Each messaging store has two slots for the dispatcher's own SQL owner and its +uncertain-COMMIT reconciliation and a third, reserved for the operator owner. The +operator never takes the dispatcher's slots, and a second concurrent operator call +on a store is refused. The lanes are two of the thirteen messaging and bridge slots +in the [capacity ledger](#shared-dispatcher-source-lifetime-and-capacity), which is +54 for the default topology and 160 for the maximum. The stores share one +unconfirmed-cleanup seal, so a cleanup fault on the operator lane seals the store +as one on the dispatcher's lanes does. ### Proof -Real PostgreSQL as each role: `DeliveryDispatchStoreTests` and `OutboxDispatchStoreTests` (the current fence -applies, every stale variant including one microsecond refuses and changes nothing, each refused state, a -tenant that is not serving, a forced audit failure rolling the change back, an admission for another operation -or a stale or spent one, a busy operator lane that leaves the dispatcher's slots alone, a lost commit -acknowledgement, and every other row byte-identical), `DeliveryInspectionTests` (pages, cursors, the entry -row, and the columns the platform role cannot select) and `PlatformOperatorHttpTests` (the routes, their -statuses and the contract). +Real PostgreSQL as each role: + +- `DeliveryDispatchStoreTests` and `OutboxDispatchStoreTests`: the current fence + applies; every stale variant, one microsecond included, refuses and changes + nothing; each refused state; a tenant that is not serving; a forced audit failure + rolling the change back; an admission for another operation, a stale one or a spent + one; the witness refusing each substituted field of the row and a transaction that + is not its own, and a witness reused on a later transition; a busy operator lane + that leaves the dispatcher's slots alone, in each store; a lost commit + acknowledgement; the real `OperatorRecovery` owner reaching the right store and + counting each outcome under its own operation; and the siblings and the inbox + byte-identical after a replay. +- `DeliveryInspectionTests`: pages and keyset cursors (equal instants included), a + cursor refused under another resource or state, the entry row, the job occupancy + counts, the descriptor shape of `last_error`, and the exact columns the platform + role can and cannot select. +- `PlatformOperatorHttpTests` and `PlatformAdminGateTests`: the routes, their + statuses and contract, and the pair of permissions, each held alone. diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index ca9e0ae6..170ebd58 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -235,8 +235,9 @@ will raise them — which this standard requires it to do. through two witness-bound methods, under the platform sentinel, with no actor and the ticket in `metadata.operator`. The operator recovery operations of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) are - `(off-path)` too: `platform.delivery.inspect` is the operation the platform scope's - entry row names, and `platform.delivery.replay` and `platform.delivery.reset` are + `(off-path)` too: `platform.delivery.inspect` is the admitted operation whose + reason `delivery_inspect` the platform scope's entry row carries, and + `platform.delivery.replay` and `platform.delivery.reset` are written on the dispatcher's outbox-role transaction through one witness-bound method, under the real event tenant, with no actor, the operator attribution and the fence in `metadata`, and no ticket, because a tenant can read the row. diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index cd05de63..c447a77f 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -797,10 +797,10 @@ The dispatcher's two stores have a second writer, the operator recovery owner of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md): a fenced subscriber replay and a narrow producer reset, each behind an operator admission and each writing its MUST row through a sibling witness (`OperatorRecoveryTransition`) on -the same outbox-role transaction. The owner holds no credential: it is a DI consumer of the two -stores, whose third connection slot is reserved for it, and `IOperatorRecovery` is the -only port the recovery routes hold. The inspection that precedes a reset runs in the -platform scope on column grants and writes no change. +the same outbox-role transaction. The owner holds no credential: it is a DI consumer of +the two stores, whose third connection slot is reserved for it, and `IOperatorRecovery` +is the only port the two acts hold. The inspection that precedes a reset runs in the +platform scope on column grants through `IDeliveryInspection` and writes no change. ## Background Jobs and Hangfire diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 7b7d9158..9b3762f9 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -2071,6 +2071,13 @@ diagnostic above row security, not the boundary, as its own note says. connection after grant removal, for both direct and transitive membership. - **Phase:** 02b, P02b-2. +- **Accepted extension:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) + adds exactly one more consumer of the two stores' connections, the operator recovery + owner `OperatorRecovery`, which holds no credential and reaches the outbox role only + through each store's reserved operator lane. The dispatcher census pins the stores' + recovery methods and their parameters, and + [OperatorRecoveryBoundaryTests](../../backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs) + closes who may mint the recovery witness and who may write its row. - **Accepted extension:** ADR-0047 preserves this canonical name while adding enumerated H1 credential consumers and the minimal lifecycle reader. P02b-4 Step 2 implements role/table grants; Step 4 adds the closed facade, source pin From da418cbc3a1de31219bc1683a07e3b8fcba10822 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 08:42:47 +0300 Subject: [PATCH 19/28] fix(platform): close P03-9 step 4 review round 2 findings Three fresh reviewers read the operator recovery step with other lenses (composition and regression; SQL, RLS, migration and performance; operability and documentation). The findings that survived verification are fixed: - the unavailable-owner log line moves off event id 7109, which the onboarding runbooks and three ADRs pin as a defect alert, to 7110 - only a transient fault, a timeout or the server's statement timeout is a retryable 503; a refused credential or a missing grant surfaces as the defect it is - a refused state names its rule as the cause parameter of its reason, a misspelt query parameter is refused, any limit above the maximum is clamped, the jobs list no longer advertises a state, and the kernel's page-size constants are used - the recovery runbook gains an unknown-outcome recipe a landed act can be followed with, a section for a 503 that does not clear, the audit read recipe and the response statuses it omitted; Phase 11, Architecture 23 and Standards 05 and 21 no longer state a stale grant inventory or hide an index - tests for the keyset tie-break, the indexes' keys and plans, a recovery admission on the platform scope and result writer, the fault classes against a real database and the previous Platform head's Down; twelve more mutations of the guards are killed Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 3 +- .../PlatformOperatorDocumentTransformer.cs | 16 +- .../PlatformOperatorEndpoints.Recovery.cs | 45 +++-- .../DeliveryDispatchStore.Operator.cs | 22 ++- .../Messaging/OperatorRecoveryFaults.cs | 31 ++++ .../Messaging/OutboxDispatchStore.Operator.cs | 22 ++- .../PlatformOperator/DeliveryInspection.cs | 54 ++++-- .../Audit/IAuditStore.cs | 2 +- .../Platform/IOperatorRecovery.cs | 7 +- ...imeFacadeTests.CombinedPhysicalCapacity.cs | 2 +- .../Database/DeliveryDispatchStoreTests.cs | 4 +- .../Database/DeliveryInspectionTests.cs | 134 +++++++++++++- .../Database/MigrationRollbackTests.cs | 2 + .../Database/OutboxDispatchStoreTests.cs | 10 +- .../Database/PlatformAdminScopeTests.cs | 49 +++++ .../PlatformOperatorHttpTests.cs | 94 +++++++++- .../BackgroundJobQuarantineHealthTests.cs | 2 +- .../Messaging/OperatorRecoveryFaultsTests.cs | 61 +++++++ docs/architecture/23-data-protection.md | 2 +- ...-operator-recovery-of-asynchronous-work.md | 30 ++-- docs/modules/tenancy/audit.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 42 ++++- docs/roadmap/phase-03-identity-admin.md | 2 +- docs/roadmap/phase-11-production-hardening.md | 8 +- docs/runbooks/operator-access.md | 21 ++- docs/runbooks/operator-recovery.md | 170 +++++++++++++----- docs/standards/05-database.md | 20 ++- .../21-architecture-tests-catalogue.md | 38 ++-- 28 files changed, 731 insertions(+), 164 deletions(-) create mode 100644 backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs diff --git a/.env.example b/.env.example index 13e40acc..8944f3c8 100644 --- a/.env.example +++ b/.env.example @@ -63,7 +63,8 @@ LEARNSTACK_IDENTITY_REBIND_PW=learnstack-identity-rebind-dev # FORCE ROW LEVEL SECURITY exists to defeat. # Default — ordinary request/job business owners. NOBYPASSRLS. # PlatformAdmin — resolvable only by PlatformAdminScope. BYPASSRLS. -# OutboxDispatcher — API-owned OutboxProcessor only. Never Seeder or web. +# OutboxDispatcher — the API's dispatcher stores only: the OutboxProcessor, the DeliveryProcessor and +# the operator recovery lane behind them. Never Seeder or web. ConnectionStrings__Migration='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_migration;Password=learnstack-migration-dev' ConnectionStrings__Default='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_app;Password=learnstack-app-dev' ConnectionStrings__PlatformAdmin='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_platform;Password=learnstack-platform-dev' diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 02cd640b..98812665 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -19,7 +19,8 @@ internal sealed class PlatformOperatorDocumentTransformer(string documentName) : internal const string Description = "Operator-only platform operations. Authenticate with a short-lived access token issued by the " + "deployment's operator issuer to the client learnstack-operator after a second factor; the token " - + "profile and the runbooks are in docs/runbooks/operator-access.md. Authentication grants no " + + "profile and the runbooks are in docs/runbooks/operator-access.md, and the recovery of dead-lettered " + + "work is explained in docs/runbooks/operator-recovery.md. Authentication grants no " + "permission: each operation needs a Platform grant held by LearnStack and evaluated on every act."; public async Task TransformAsync( @@ -103,6 +104,15 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum /// private static void DescribeInspectionParameters(OpenApiOperation operation) { + // The quarantined-jobs list takes no state and refuses one, so the document does not offer it. + if (operation.OperationId == "PlatformJobInspect" && operation.Parameters is { } offered) + { + foreach (var state in offered.Where(parameter => parameter.Name == "state").ToList()) + { + offered.Remove(state); + } + } + foreach (var parameter in operation.Parameters ?? []) { if (parameter is not OpenApiParameter concrete) @@ -113,7 +123,7 @@ private static void DescribeInspectionParameters(OpenApiOperation operation) switch (concrete.Name) { case "state": - concrete.Description = "dead_lettered (default) or terminal_requested; a quarantined-jobs list takes no state."; + concrete.Description = "dead_lettered (default) or terminal_requested."; concrete.Schema = new OpenApiSchema { Type = JsonSchemaType.String, @@ -211,7 +221,7 @@ private static readonly (string Status, string Description)[] Statuses = ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, or a recovery names no such row."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one a reset may act on). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs index 805205dd..1465bbd7 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs @@ -5,6 +5,7 @@ using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Pagination; using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Results; using Microsoft.AspNetCore.Mvc; @@ -58,8 +59,9 @@ internal sealed record InspectionResponse(IReadOnlyList Items, InspectionP internal static partial class PlatformOperatorEndpoints { private const string WorkPrefix = "/asynchronous-work"; - private const int DefaultPageSize = 20; - private const int MaximumPageSize = 100; + private static readonly string[] InspectionParameters = ["state", "limit", "cursor", "ticket"]; + private const int DefaultPageSize = CursorPagination.DefaultLimit; + private const int MaximumPageSize = CursorPagination.MaxLimit; private static readonly Regex SubscriptionPattern = new( @"\A[a-z][a-z0-9]*\.[a-z][a-z0-9-]*\.v[1-9][0-9]*\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); @@ -84,12 +86,18 @@ private static void MapRecovery(RouteGroupBuilder group) Describe( group.MapPost(WorkPrefix + "/event-deliveries/{tenantId:guid}/{subscriptionId}/{eventId:guid}/replay", ReplayDeliveryAsync) .WithName("PlatformDeliveryReplay") - .WithSummary("Reset one dead-lettered subscriber delivery under the fence the inspection returned."), + .WithSummary("Reset one dead-lettered subscriber delivery under the fence the inspection returned.") + .WithDescription( + "Send every fence field exactly as the inspection returned it: replayCount, deadLetteredAt (to the microsecond; a " + + "value rounded to milliseconds never matches) and terminalReason. A ticket is checked and not stored."), typeof(RecoveryResponse)); Describe( group.MapPost(WorkPrefix + "/outbox-messages/{tenantId:guid}/{eventId:guid}/reset", ResetOutboxAsync) .WithName("PlatformOutboxReset") - .WithSummary("Reset one retry-exhausted outbox row under the fence the inspection returned; this renews its attempt budget."), + .WithSummary("Reset one retry-exhausted outbox row under the fence the inspection returned; this renews its attempt budget.") + .WithDescription( + "Send every fence field exactly as the inspection returned it: attempts and deadLetteredAt (to the microsecond; a " + + "value rounded to milliseconds never matches). A ticket is checked and not stored."), typeof(RecoveryResponse)); } @@ -160,6 +168,13 @@ private static async Task InspectAsync( return InvalidParameter(http, "limit"); } + // A misspelt parameter would otherwise be ignored and answer a different list than the one asked for. The + // name is not echoed: it is the caller's text. + if (http.Request.Query.Keys.Any(key => !InspectionParameters.Contains(key, StringComparer.Ordinal))) + { + return InvalidParameter(http, "query"); + } + try { var result = await page(admission!, parsedState, size); @@ -243,7 +258,7 @@ private static async Task RecoverAsync( "applied", tenantId, eventId, subscriptionId, result.CountAfter ?? 0, admission.Operator.CorrelationId ?? http.TraceIdentifier)), OperatorRecoveryOutcome.StaleFence => ResultProblem(http, Rule("fence", "lockey_stale_fence")), - OperatorRecoveryOutcome.NotRecoverable => ResultProblem(http, Rule("state", "lockey_not_recoverable")), + OperatorRecoveryOutcome.NotRecoverable => ResultProblem(http, Rule("state", "lockey_not_recoverable", result.Refusal)), _ => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), }; } @@ -260,7 +275,7 @@ private static async Task RecoverAsync( private static readonly Action LogRecoveryUnavailable = LoggerMessage.Define( LogLevel.Warning, - new EventId(7109, nameof(LogRecoveryUnavailable)), + new EventId(7110, nameof(LogRecoveryUnavailable)), "An operator recovery owner was unavailable for {Operation}; the commit's outcome unknown: {CommitOutcomeUnknown}."); /// @@ -296,12 +311,16 @@ private static IResult InvalidParameter(HttpContext http, string parameter) => R [parameter] = [new LocalizedMessage(ModelBindingProblemDetails.FieldMessageKey)], })); - /// A 409 with the reason on the field it concerns; the status map is closed, so the code stays the business rule's. - private static Error Rule(string field, string reason) => new( + /// + /// A 409 with the reason on the field it concerns; the status map is closed, so the code stays the business rule's. + /// A refused state names the rule that refused it as the reason's cause parameter. + /// + private static Error Rule(string field, string reason, string? cause = null) => new( new LocalizedMessage("lockey_business_rule_violation"), new Dictionary>(StringComparer.Ordinal) { - [field] = [new LocalizedMessage(reason)], + [field] = [new LocalizedMessage( + reason, cause is null ? null : new Dictionary(StringComparer.Ordinal) { ["cause"] = cause })], }); private static async Task<(IResult? Refusal, PlatformAdmission? Admission)> AdmitAsync( @@ -364,14 +383,16 @@ private static bool TryLimit(string? text, out int size) return true; } - // Standard 04: a limit of zero or less is rejected, a larger one is clamped, never rejected. - if (!int.TryParse(text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) + // Standard 04: a limit of zero or less is rejected, a larger one is clamped, never rejected. The digits are read + // without a width, so a value past the range of an int is a larger limit and is clamped like any other. + if (!System.Numerics.BigInteger.TryParse( + text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) || parsed < 1) { return false; } - size = Math.Min(parsed, MaximumPageSize); + size = parsed > MaximumPageSize ? MaximumPageSize : (int)parsed; return true; } diff --git a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs index b0777c25..27709fb7 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/DeliveryDispatchStore.Operator.cs @@ -53,15 +53,13 @@ public async Task ReplayAsync( return await ReplayCoreAsync(request, admission, progress, cancellationToken).ConfigureAwait(false); } catch (Exception failure) when (progress.CommitAttempted - && (failure is NpgsqlException or TimeoutException or InvalidOperationException or AggregateException - || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested))) + && (failure is AggregateException || OperatorRecoveryFaults.IsUnavailable(failure, cancellationToken))) { // The COMMIT was sent, so whatever failed afterwards (the connection's cleanup included) leaves its // outcome unknown, and the operator inspects the row before repeating. throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } - catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException - || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + catch (Exception failure) when (OperatorRecoveryFaults.IsUnavailable(failure, cancellationToken)) { throw new OperatorRecoveryUnavailableException(cause: failure); } @@ -110,11 +108,16 @@ FROM event_deliveries WHERE {Identity} FOR UPDATE return new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); } - if (processed || leased || reason == "invalid_envelope" - || !_registry.IsActiveOrdinarySubscription(type, request.SubscriptionId) - || !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false)) + var refusal = processed ? "processed" + : leased ? "leased" + : reason == "invalid_envelope" ? "invalid_envelope" + : !_registry.IsActiveOrdinarySubscription(type, request.SubscriptionId) ? "subscription_not_active" + : !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false) + ? "tenant_not_serving" + : null; + if (refusal is not null) { - return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable, Refusal: refusal); } OperatorRecoveryTransition witness; @@ -153,7 +156,8 @@ FROM event_deliveries WHERE {Identity} FOR UPDATE catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) { // COMMIT may have reached PostgreSQL. The change and its row commit together or not at all, so there is - // nothing to repair; the operator inspects the row, whose fence moved if the reset landed. + // nothing to repair: the operator lists again (a landed replay leaves the dead-lettered list) or reads the + // tenant's audit row by the correlation id. ownedConnection.RecordCommitFailure(failure); throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs new file mode 100644 index 00000000..be1e7443 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs @@ -0,0 +1,31 @@ +using Npgsql; + +namespace LearnStack.Infrastructure.Messaging; + +/// +/// Which faults an operator call may report as unavailable. Only a fault the operator can wait out is one: a +/// refused credential, a missing grant or a missing table is a deployment defect, and answering it with a retryable +/// 503 would invite a retry loop that cannot succeed. +/// +internal static class OperatorRecoveryFaults +{ + /// + /// A database fault that Npgsql calls transient, a timeout, or the server's own statement timeout, which the + /// dispatcher's role sets to the length of its bounded call and which Npgsql does not class as transient. + /// + internal static bool IsTransientDatabaseFault(Exception failure, CancellationToken caller) => failure switch + { + PostgresException { SqlState: PostgresErrorCodes.QueryCanceled } => true, + NpgsqlException { IsTransient: true } => true, + TimeoutException => true, + OperationCanceledException => !caller.IsCancellationRequested, + _ => false, + }; + + /// + /// A transient database fault, or one of the owner's own refusals: the lane is busy, the pool is exhausted or the + /// store is sealed by an unconfirmed cleanup, each of which is an . + /// + internal static bool IsUnavailable(Exception failure, CancellationToken caller) => + failure is InvalidOperationException || IsTransientDatabaseFault(failure, caller); +} diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs index 44e98a9b..0f69b7ea 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/OutboxDispatchStore.Operator.cs @@ -46,15 +46,13 @@ public async Task ResetAsync( return await ResetCoreAsync(request, admission, progress, cancellationToken).ConfigureAwait(false); } catch (Exception failure) when (progress.CommitAttempted - && (failure is NpgsqlException or TimeoutException or InvalidOperationException or AggregateException - || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested))) + && (failure is AggregateException || OperatorRecoveryFaults.IsUnavailable(failure, cancellationToken))) { // The COMMIT was sent, so whatever failed afterwards (the connection's cleanup included) leaves its // outcome unknown, and the operator inspects the row before repeating. throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } - catch (Exception failure) when (failure is NpgsqlException or TimeoutException or InvalidOperationException - || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + catch (Exception failure) when (OperatorRecoveryFaults.IsUnavailable(failure, cancellationToken)) { throw new OperatorRecoveryUnavailableException(cause: failure); } @@ -105,11 +103,16 @@ locked_by IS NOT NULL OR locked_until IS NOT NULL } var disposition = _registry.Resolve(type).Disposition; - if (processed || leased || reason != "retry_exhausted" - || disposition is OutboxEventDisposition.Retired or OutboxEventDisposition.Unknown - || !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false)) + var refusal = processed ? "processed" + : leased ? "leased" + : reason != "retry_exhausted" ? "reason_refused" + : disposition is OutboxEventDisposition.Retired or OutboxEventDisposition.Unknown ? "type_not_dispatchable" + : !await TenantServesAsync(connection, transaction, request.TenantId, deadline.Token).ConfigureAwait(false) + ? "tenant_not_serving" + : null; + if (refusal is not null) { - return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + return new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable, Refusal: refusal); } OperatorRecoveryTransition witness; @@ -145,7 +148,8 @@ AND locked_by IS NULL AND locked_until IS NULL catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) { // COMMIT may have reached PostgreSQL; the row and its audit commit together or not at all, so the - // operator inspects the row, whose fence moved if the reset landed. + // operator lists again (a landed reset leaves the dead-lettered list) or reads the tenant's audit row by + // the correlation id. ownedConnection.RecordCommitFailure(failure); throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, failure); } diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs index a3921a78..dc16f5c8 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs @@ -3,9 +3,9 @@ using System.Text; using System.Text.RegularExpressions; using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Pagination; using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; -using Npgsql; namespace LearnStack.Infrastructure.PlatformOperator; @@ -28,7 +28,7 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// public sealed class DeliveryInspection(IPlatformAdminScope scope, OutboxEventRegistry registry) : IDeliveryInspection { - private const int MaximumLimit = 100; + private const int MaximumLimit = CursorPagination.MaxLimit; // The dispatcher writes a closed vocabulary of lowercase descriptors (for example publish:failed:provider). The // database bounds only the byte length of last_error, so the projection shows a value of that shape and nothing @@ -42,19 +42,41 @@ public sealed class DeliveryInspection(IPlatformAdminScope scope, OutboxEventReg private const string DeliveryColumns = "tenant_id, subscription_id, event_id, organization_id, occurred_at, type, attempts, " + "last_error, available_after, locked_until, terminal_reason, dead_lettered_at, replay_count, replayed_at, processed_at"; + private static (string Where, string Order) Shape(DeliveryInspectionState state) => + state == DeliveryInspectionState.DeadLettered + ? ("dead_lettered_at IS NOT NULL AND processed_at IS NULL", "dead_lettered_at") + : ("processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL", "available_after"); + + /// + /// The statement of an outbox page. It is exposed so that a test can ask PostgreSQL for the plan of the text the + /// inspection really runs: the dead-lettered scan must use ix_outbox_messages_dead_lettered in key order. + /// + internal static string OutboxSql(DeliveryInspectionState state, bool afterCursor) + { + var (where, order) = Shape(state); + return $"SELECT {OutboxColumns} FROM outbox_messages WHERE {where}" + + (afterCursor ? $" AND ({order}, id) > (@after, @key)" : string.Empty) + + $" ORDER BY {order}, id LIMIT @size"; + } + + /// The statement of a delivery page, exposed for the same reason as . + internal static string DeliverySql(DeliveryInspectionState state, bool afterCursor) + { + var (where, order) = Shape(state); + return $"SELECT {DeliveryColumns} FROM event_deliveries WHERE {where}" + + (afterCursor ? $" AND ({order}, tenant_id, subscription_id, event_id) > (@after, @tenant, @subscription, @event)" : string.Empty) + + $" ORDER BY {order}, tenant_id, subscription_id, event_id LIMIT @size"; + } + /// public Task?> InspectOutboxAsync( PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) { - var (where, order, byDeadLetter) = state == DeliveryInspectionState.DeadLettered - ? ("dead_lettered_at IS NOT NULL AND processed_at IS NULL", "dead_lettered_at", true) - : ("processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL", "available_after", false); + var byDeadLetter = state == DeliveryInspectionState.DeadLettered; return PageAsync( admission, "outbox." + state, cursor, limit, cancellationToken, (after, key, size) => new Statement( - $"SELECT {OutboxColumns} FROM outbox_messages WHERE {where}" - + (after is null ? string.Empty : $" AND ({order}, id) > (@after, @key)") - + $" ORDER BY {order}, id LIMIT @size", + OutboxSql(state, after is not null), [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, size)]), reader => MapOutbox(reader), row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, @@ -66,9 +88,7 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, public Task?> InspectDeliveriesAsync( PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) { - var (where, order, byDeadLetter) = state == DeliveryInspectionState.DeadLettered - ? ("dead_lettered_at IS NOT NULL AND processed_at IS NULL", "dead_lettered_at", true) - : ("processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL", "available_after", false); + var byDeadLetter = state == DeliveryInspectionState.DeadLettered; return PageAsync( admission, "delivery." + state, cursor, limit, cancellationToken, (after, key, size) => @@ -82,11 +102,7 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, parameters.Add(new PlatformSqlParameter("event", eventId)); } - return new Statement( - $"SELECT {DeliveryColumns} FROM event_deliveries WHERE {where}" - + (after is null ? string.Empty : $" AND ({order}, tenant_id, subscription_id, event_id) > (@after, @tenant, @subscription, @event)") - + $" ORDER BY {order}, tenant_id, subscription_id, event_id LIMIT @size", - parameters); + return new Statement(DeliverySql(state, after is not null), parameters); }, reader => MapDelivery(reader), row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, @@ -158,10 +174,10 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, var built = statement(after, key, size + 1); rows = await handle.QueryAsync(built.Sql, built.Parameters, map, cancellationToken).ConfigureAwait(false); } - catch (Exception failure) when (failure is NpgsqlException or TimeoutException - || (failure is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + catch (Exception failure) when (OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) { - // A read is safe to repeat; the cause is for the route's log, never for the response. + // A read is safe to repeat; the cause is for the route's log, never for the response. A refused + // credential or a missing grant is not transient and surfaces as the defect it is. throw new OperatorRecoveryUnavailableException(cause: failure); } diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index d22b6e8f..30401e47 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -5,7 +5,7 @@ namespace LearnStack.SharedKernel.Audit; /// -/// The only sanctioned way to put a row in audit_log. Thirteen writes, and +/// The only sanctioned way to put a row in audit_log. Fourteen writes, and /// no update. /// /// diff --git a/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs index b39487b8..0390d090 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/IOperatorRecovery.cs @@ -39,7 +39,12 @@ public enum OperatorRecoveryOutcome /// The end of one recovery and the count the row now carries when it was applied. /// How it ended. /// The fence's count after an applied reset: the new replay count, or zero attempts. -public sealed record OperatorRecoveryResult(OperatorRecoveryOutcome Outcome, int? CountAfter = null); +/// +/// For a refused state, the closed token that says which rule refused it: processed, leased, +/// invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or +/// tenant_not_serving. +/// +public sealed record OperatorRecoveryResult(OperatorRecoveryOutcome Outcome, int? CountAfter = null, string? Refusal = null); /// /// The recovery owner could not finish and nothing is known to be wrong with the request: the credential or the pool diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs index 53c9718d..f5ba26f1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs @@ -133,7 +133,7 @@ await EventuallyAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(data AssertCombinedHolds(outboxHold, deliveryHold, expiration, source); await AssertCombinedBackendsAsync(database, applicationName, outboxHold, deliveryHold, expirationPid); runtime.Snapshot.RunningPools.Should().Be(3); - testOutput.WriteLine("Supported52 pool: real expiration + two distinct terminal-scope physical checkouts held; tenantB native business/MUST audit committed before release. Representative contention, not exact52 saturation."); + testOutput.WriteLine("Supported-floor pool: real expiration + two distinct terminal-scope physical checkouts held; tenantB native business/MUST audit committed before release. Representative contention, not exact-floor saturation."); } finally { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs index 73df4a78..3b4eccd2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs @@ -534,6 +534,7 @@ public async Task Replay_refuses_a_matching_fence_on_a_state_a_reset_may_not_act var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, subscription, id); result.Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable, state); + result.Refusal.Should().Be(state == "active" ? "invalid_envelope" : "subscription_not_active", state); (await test.ReadAsync(id, subscription)).Should().Be(before); (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty("a refusal writes no row"); } @@ -649,8 +650,9 @@ public async Task Replay_of_a_delivery_whose_tenant_is_not_serving_is_not_recove await test.SetTenantStatusAsync("Suspended"); var before = await test.ReadAsync(id); - (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + var refused = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id); + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "tenant_not_serving")); (await test.ReadAsync(id)).Should().Be(before); await test.SetTenantStatusAsync("Active"); (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs index 427eff7e..36fadb58 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs @@ -313,6 +313,125 @@ public async Task The_last_error_a_page_shows_is_a_descriptor_or_the_word_unreco delivery!.Items.Single().LastError.Should().Be(shown); } + [Fact] + public async Task A_refused_credential_is_a_defect_and_an_unreachable_database_is_a_retryable_outage() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var wrongPassword = new NpgsqlConnectionStringBuilder(proof.Database.PlatformConnectionString) + { + Password = "not-the-password", + Pooling = false, + }.ConnectionString; + var unreachable = new NpgsqlConnectionStringBuilder(proof.Database.PlatformConnectionString) + { + Host = "127.0.0.1", + Port = 1, + Pooling = false, + Timeout = 3, + }.ConnectionString; + await using var refusedSource = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(wrongPassword); + await using var unreachableSource = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(unreachable); + + // A retry cannot cure a refused credential, so it surfaces as the defect it is and not as a retryable outage. + var refused = async () => await proof.InspectionOver(refusedSource) + .InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + (await refused.Should().ThrowAsync()).Which.IsTransient.Should().BeFalse(); + + var outage = async () => await proof.InspectionOver(unreachableSource) + .InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + (await outage.Should().ThrowAsync()).Which.InnerException.Should().BeAssignableTo(); + } + + [Fact] + public async Task Deliveries_with_equal_instants_page_by_tenant_then_subscription_then_event() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + // The event ids run against the subscriptions' order, so a keyset that dropped a column would skip a row. + var larger = Guid.Parse("ffffffff-0000-7000-8000-000000000001"); + var smaller = Guid.Parse("00000000-0000-7000-8000-000000000001"); + const string instant = "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.000001+00'"; + await proof.DeliveryAsync(larger, "a.first.v1", instant); + await proof.DeliveryAsync(smaller, "b.second.v1", instant); + + var first = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1); + var second = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 1); + + first.Items.Single().SubscriptionId.Should().Be("a.first.v1"); + second!.Items.Single().SubscriptionId.Should().Be("b.second.v1", "the subscription orders before the event id"); + second.NextCursor.Should().BeNull(); + } + + [Fact] + public async Task The_dead_letter_indexes_exist_with_the_keys_and_predicates_the_inspection_orders_and_filters_by() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + async Task Definition(string index) + { + await using var command = new NpgsqlCommand("SELECT indexdef FROM pg_indexes WHERE indexname = @name", (NpgsqlConnection)platform); + command.Parameters.AddWithValue("name", index); + return await command.ExecuteScalarAsync() as string; + } + + (await Definition("ix_outbox_messages_dead_lettered")).Should() + .Contain("(dead_lettered_at, id)").And.Contain("WHERE (dead_lettered_at IS NOT NULL)"); + (await Definition("ix_event_deliveries_dead_lettered")).Should() + .Contain("(dead_lettered_at, tenant_id, subscription_id, event_id)").And.Contain("WHERE (dead_lettered_at IS NOT NULL)"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task The_dead_lettered_pages_use_their_partial_index_in_key_order_with_no_sort(bool afterCursor) + { + // The statement is the text the inspection runs. Sequential and bitmap scans are disabled so that the only + // plan left is an ordered scan of the index: the index being absent from it, or a Sort above it, means the + // statement's predicate or its order no longer matches the index, and a page would scan and sort every dead + // letter. + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.SqlAsync($""" + INSERT INTO outbox_messages (id, tenant_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, + payload, attempts, terminal_reason, dead_lettered_at, processed_at) + SELECT uuidv7(), '{SchemaFixture.TenantA}', '{SchemaFixture.OrgA1}', now(), 'c', '{KnownType}', + 'learnstack.test.inspection', 'k', '[]'::jsonb, CASE WHEN g % 30 = 0 THEN 6 ELSE 0 END, + CASE WHEN g % 30 = 0 THEN 'retry_exhausted' END, + CASE WHEN g % 30 = 0 THEN now() - make_interval(secs => g) END, + CASE WHEN g % 30 = 0 THEN NULL ELSE now() END + FROM generate_series(1, 6000) g; + INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization_id, occurred_at, correlation_id, type, + topic, partition_key, payload, terminal_reason, dead_lettered_at, processed_at) + SELECT '{SchemaFixture.TenantA}', '{Subscription}', uuidv7(), '{SchemaFixture.OrgA1}', now(), 'c', '{KnownType}', + 'learnstack.test.inspection', 'k', '[]'::jsonb, + CASE WHEN g % 30 = 0 THEN 'retry_exhausted' END, + CASE WHEN g % 30 = 0 THEN now() - make_interval(secs => g) END, + CASE WHEN g % 30 = 0 THEN NULL ELSE now() END + FROM generate_series(1, 6000) g; + ANALYZE outbox_messages; + ANALYZE event_deliveries; + """); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + + async Task Plan(string sql, params (string Name, object Value)[] parameters) + { + await using var command = new NpgsqlCommand("SET enable_seqscan = off; SET enable_bitmapscan = off; EXPLAIN (FORMAT JSON) " + sql, (NpgsqlConnection)platform); + foreach (var (name, value) in parameters) command.Parameters.AddWithValue(name, value); + return (await command.ExecuteScalarAsync())!.ToString()!; + } + + var after = new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + var outbox = await Plan( + DeliveryInspection.OutboxSql(DeliveryInspectionState.DeadLettered, afterCursor), + [("size", 21), .. afterCursor ? new (string, object)[] { ("after", after), ("key", Guid.CreateVersion7()) } : []]); + var delivery = await Plan( + DeliveryInspection.DeliverySql(DeliveryInspectionState.DeadLettered, afterCursor), + [("size", 21), .. afterCursor + ? new (string, object)[] { ("after", after), ("tenant", SchemaFixture.TenantA), ("subscription", Subscription), ("event", Guid.CreateVersion7()) } + : []]); + + outbox.Should().Contain("ix_outbox_messages_dead_lettered").And.NotContain("\"Node Type\": \"Sort\"").And.NotContain("Seq Scan"); + delivery.Should().Contain("ix_event_deliveries_dead_lettered").And.NotContain("\"Node Type\": \"Sort\"").And.NotContain("Seq Scan"); + } + [IntegrationEventPartition(nameof(TenantId), tenantWide: true)] public sealed record InspectionEvent : IntegrationEventBase { @@ -329,6 +448,7 @@ private sealed class Proof : IAsyncDisposable { private readonly PostgresFixture _postgres; private readonly NpgsqlDataSource _platform; + private readonly OutboxEventRegistry _registry; private Proof(PostgresFixture postgres, DisposableSchemaDatabase database) { @@ -337,15 +457,19 @@ private Proof(PostgresFixture postgres, DisposableSchemaDatabase database) _platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); var handlers = IntegrationEventHandlerRegistry.FromServiceDescriptors( [ServiceDescriptor.Scoped, InspectionHandler>()]); - var registry = OutboxEventRegistry.Create( + _registry = OutboxEventRegistry.Create( [OutboxEventRegistration.Required(typeof(InspectionEvent), [OutboxSubscriptionManifest.Active(Subscription, typeof(InspectionHandler))], "declared.previous.inspection")], [], handlers, [typeof(InspectionEvent).Assembly]); - var scope = new PlatformAdminScope( - new PrivilegedDataSource(() => _platform), new AuditCatalog([new TenancyAuditCatalogSource()]), - AuditStoreScopeFactory(), new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); - Inspection = new DeliveryInspection(scope, registry); + Inspection = InspectionOver(_platform); } + /// The inspection as production builds it, over the platform data source a test supplies. + internal DeliveryInspection InspectionOver(NpgsqlDataSource platform) => new( + new PlatformAdminScope( + new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + AuditStoreScopeFactory(), new SystemClock(), new SystemGuidFactory(), NullLogger.Instance), + _registry); + internal DisposableSchemaDatabase Database { get; } internal DeliveryInspection Inspection { get; } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 16eabbb5..76c126d6 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -217,6 +217,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() releaseV4.Should().Throw().WithMessage("Role release adoption requires a reviewed forward migration."); Action operatorResolver = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_operator_subject_resolver().DownOperations; operatorResolver.Should().Throw().WithMessage("Operator subject resolution requires a reviewed forward migration."); + Action protectedReceipts = () => _ = new LearnStack.Infrastructure.Persistence.Migrations.add_custom_field_protected_receipts().DownOperations; + protectedReceipts.Should().Throw().WithMessage("Retained custom field receipts require a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] { (tenancy, "20261029112940_guard_retained_tenancy_defaults", TenancyReversibleHead, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs index 1bf61eff..4b84b058 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs @@ -1029,7 +1029,9 @@ public async Task Reset_refuses_every_reason_but_retry_exhaustion(string reason) await test.SetStateAsync(id, $"terminal_reason = '{reason}', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); var before = await test.ReadAsync(id); - (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + var refused = await ResetAsync(test.Store(), test, id); + + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "reason_refused")); (await test.ReadAsync(id)).Should().Be(before); (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); @@ -1083,7 +1085,8 @@ public async Task Reset_of_a_row_whose_type_the_registry_no_longer_knows_is_not_ foreach (var id in new[] { gone, retired }) { var before = await test.ReadAsync(id); - (await ResetAsync(test.Store(registry), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable, + var refused = await ResetAsync(test.Store(registry), test, id); + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "type_not_dispatchable"), "a reset would only dead-letter the row again with a second MUST row"); (await test.ReadAsync(id)).Should().Be(before); } @@ -1114,8 +1117,9 @@ public async Task Reset_of_a_row_whose_tenant_is_not_serving_is_not_recoverable_ await test.SetTenantStatusAsync("Suspended"); var before = await test.ReadAsync(id); - (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable); + var refused = await ResetAsync(test.Store(), test, id); + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "tenant_not_serving")); (await test.ReadAsync(id)).Should().Be(before); await test.SetTenantStatusAsync("Active"); (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index f32f7a44..bc168c5e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -901,6 +901,55 @@ await audit.WritePlatformOperatorResultAsync( } } + [Theory] + [InlineData("platform.delivery.replay")] + [InlineData("platform.delivery.reset")] + public async Task An_Admission_For_A_Recovery_Act_Opens_No_Platform_Scope_And_Writes_No_Platform_Result_Row(string slug) + { + // ADR-0103: a replay and a reset run on the dispatcher's outbox role and write their own row through the + // recovery witness. An admission minted for one is not spendable on the platform scope or on the platform + // result writer, whose draft below is otherwise exactly what that writer accepts. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == slug); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = TestPlatformAdmissions.Admission(operation, null, correlationId: "corr-" + Guid.NewGuid().ToString("N")); + + var enter = async () => await Build(dataSource).EnterAsync(admission); + (await enter.Should().ThrowAsync(slug)).Which.Message.Should().Contain("platform role"); + + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + var draft = new AuditEntryDraft + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "tenancy", + Operation = operation.AuditSlug, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = "{\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\",\"subjectDigest\":\"" + + admission.Operator.SubjectDigest + "\",\"kind\":\"human\"}}", + }; + var write = async () => await audit.WritePlatformOperatorResultAsync(draft, admission, connection, transaction); + (await write.Should().ThrowAsync(slug)).Which.Message.Should().Contain("admission"); + } + [Fact] public async Task Commit_Without_A_Result_Row_Is_Refused_And_The_Work_Rolls_Back() { diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index 9244f50f..e716c421 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Xunit; namespace LearnStack.Tests.Integration; @@ -47,6 +48,7 @@ public sealed class PlatformOperatorHttpTests : IAsyncLifetime private RecordingToggle _toggle = null!; private RecordingRecovery _recovery = null!; private RecordingInspection _inspection = null!; + private CapturingLogs _logs = null!; private HttpClient _client = null!; public async Task InitializeAsync() @@ -56,9 +58,12 @@ public async Task InitializeAsync() _toggle = new RecordingToggle(); _recovery = new RecordingRecovery(); _inspection = new RecordingInspection(); + _logs = new CapturingLogs(); _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, services: registrations => { + // The host's logging is Serilog, which does not feed registered providers: the routes ask for the factory. + registrations.AddSingleton(_ => LoggerFactory.Create(builder => builder.AddProvider(_logs))); registrations.AddSingleton(_recovery); registrations.AddScoped(_ => _inspection); }); @@ -536,6 +541,9 @@ JsonElement ParameterOf(string route, string name) => root.GetProperty("paths"). .GetProperty("parameters").EnumerateArray().Single(parameter => parameter.GetProperty("name").GetString() == name) .GetProperty("schema"); var outbox = "/api/platform/v1/asynchronous-work/outbox-messages"; + root.GetProperty("paths").GetProperty("/api/platform/v1/asynchronous-work/quarantined-jobs").GetProperty("get") + .GetProperty("parameters").EnumerateArray().Select(parameter => parameter.GetProperty("name").GetString()) + .Should().NotContain("state", "the jobs list takes no state and refuses one"); ParameterOf(outbox, "state").GetProperty("enum").EnumerateArray().Select(value => value.GetString()) .Should().BeEquivalentTo(["dead_lettered", "terminal_requested"]); ParameterOf(outbox, "limit").GetProperty("minimum").GetRawText().Trim('"').Should().Be("1"); @@ -575,7 +583,6 @@ public async Task An_Inspection_Passes_Its_Parameters_On_Clamps_The_Limit_And_An [InlineData("limit=-1")] [InlineData("limit=1.5")] [InlineData("limit=0")] - [InlineData("limit=99999999999")] [InlineData("ticket=has%20space")] public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failure_Before_Any_Scope(string query) { @@ -585,6 +592,67 @@ public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failu _inspection.Calls.Should().BeEmpty(); } + [Theory] + [InlineData("500")] + [InlineData("99999999999")] + [InlineData("99999999999999999999999999")] + public async Task A_Limit_Of_Any_Size_Is_Clamped_To_The_Maximum_And_Never_Refused(string limit) + { + var response = await Call(HttpMethod.Get, Work + "/event-deliveries?limit=" + limit, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + _inspection.Calls.Should().ContainSingle().Which.Limit.Should().Be(100); + } + + [Theory] + [InlineData("statee=terminal_requested")] + [InlineData("limt=5")] + [InlineData("state=dead_lettered&cursr=abc")] + public async Task A_Misspelt_Parameter_Is_Refused_And_Never_Ignored_And_Is_Not_Echoed(string query) + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("errors").TryGetProperty("query", out _).Should().BeTrue(); + text.Should().NotContain("statee").And.NotContain("limt").And.NotContain("cursr"); + _inspection.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("tenant_not_serving")] + [InlineData("invalid_envelope")] + [InlineData("type_not_dispatchable")] + public async Task A_Refused_State_Names_The_Rule_That_Refused_It_As_A_Parameter_Of_Its_Reason(string cause) + { + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable, Refusal: cause); + + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var reason = body.RootElement.GetProperty("errors").GetProperty("state")[0]; + reason.GetProperty("key").GetString().Should().Be("lockey_not_recoverable"); + reason.GetProperty("params").GetProperty("cause").GetString().Should().Be(cause); + } + + [Fact] + public async Task An_Unavailable_Owner_Logs_Its_Cause_Under_Its_Own_Event_Id_Which_No_Other_Line_Uses() + { + _recovery.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + var entry = _logs.Entries.Should().ContainSingle(line => line.Id == 7110).Which; + entry.Level.Should().Be(LogLevel.Warning); + entry.Exception.Should().BeOfType("the cause is in the log and in no response"); + (await response.Content.ReadAsStringAsync()).Should().NotContain("forced"); + // 7109 is the onboarding pipeline's defect alert, which the operator runbooks pin to that meaning. + _logs.Entries.Should().NotContain(line => line.Id == 7109); + } + [Theory] [InlineData("limit=0", "limit")] [InlineData("limit=-3", "limit")] @@ -1132,6 +1200,30 @@ private Task Record(PlatformAdmission admission, object } } + private sealed class CapturingLogs : ILoggerProvider + { + private readonly ConcurrentQueue<(int Id, LogLevel Level, Exception? Exception)> _entries = new(); + + public IReadOnlyCollection<(int Id, LogLevel Level, Exception? Exception)> Entries => [.. _entries]; + + public ILogger CreateLogger(string categoryName) => new Capture(_entries); + + public void Dispose() + { + } + + private sealed class Capture(ConcurrentQueue<(int Id, LogLevel Level, Exception? Exception)> entries) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + entries.Enqueue((eventId.Id, logLevel, exception)); + } + } + private sealed class RecordingInspection : IDeliveryInspection { public List<(PlatformAdmission Admission, string Resource, DeliveryInspectionState? State, string? Cursor, int Limit)> Calls { get; } = []; diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs index 19ce6fa1..d4ec216a 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs @@ -85,7 +85,7 @@ public void Runtime_health_requires_a_fresh_known_negative_quarantine_sample(boo Recurrence = new(0, 0, 0, false, false, true, true, false, false, true), }; var snapshot = new BackgroundJobRuntimeSnapshot(BackgroundJobRuntimeState.Running, - new(3, 4, 1, 16, 52), 3, 0, 0, null, true, true, true, true, false, [], [], control); + new(3, 4, 1, 16, 54), 3, 0, 0, null, true, true, true, true, false, [], [], control); snapshot.IsHealthy.Should().Be(healthy); } diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs new file mode 100644 index 00000000..97db3997 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs @@ -0,0 +1,61 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Messaging; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.Messaging; + +/// +/// What an operator call reports as a retryable outage and what it leaves to surface as the defect it is +/// (ADR-0103 Amendment 1): a retry loop cannot cure a refused credential or a missing grant. +/// +public sealed class OperatorRecoveryFaultsTests +{ + private static PostgresException Server(string sqlState) => new("message", "ERROR", "ERROR", sqlState); + + [Theory] + [InlineData(PostgresErrorCodes.QueryCanceled)] + [InlineData(PostgresErrorCodes.LockNotAvailable)] + [InlineData(PostgresErrorCodes.TooManyConnections)] + [InlineData(PostgresErrorCodes.AdminShutdown)] + public void A_server_fault_that_waiting_can_cure_is_transient(string sqlState) => + OperatorRecoveryFaults.IsTransientDatabaseFault(Server(sqlState), CancellationToken.None).Should().BeTrue(sqlState); + + [Theory] + [InlineData(PostgresErrorCodes.InsufficientPrivilege)] + [InlineData(PostgresErrorCodes.InvalidPassword)] + [InlineData(PostgresErrorCodes.UndefinedTable)] + [InlineData(PostgresErrorCodes.UndefinedColumn)] + [InlineData(PostgresErrorCodes.InvalidAuthorizationSpecification)] + public void A_refused_credential_or_a_missing_grant_or_table_is_a_defect_and_never_transient(string sqlState) + { + OperatorRecoveryFaults.IsTransientDatabaseFault(Server(sqlState), CancellationToken.None).Should().BeFalse(sqlState); + OperatorRecoveryFaults.IsUnavailable(Server(sqlState), CancellationToken.None).Should().BeFalse(sqlState); + } + + [Fact] + public void An_unreachable_database_and_a_timeout_are_transient() + { + OperatorRecoveryFaults.IsTransientDatabaseFault( + new NpgsqlException("unreachable", new IOException("reset")), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsTransientDatabaseFault(new TimeoutException(), CancellationToken.None).Should().BeTrue(); + } + + [Fact] + public void A_cancellation_is_an_outage_only_when_the_caller_did_not_ask_for_it() + { + using var asked = new CancellationTokenSource(); + asked.Cancel(); + + OperatorRecoveryFaults.IsTransientDatabaseFault(new OperationCanceledException(), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsTransientDatabaseFault(new OperationCanceledException(), asked.Token).Should().BeFalse(); + } + + [Fact] + public void The_owners_own_refusals_are_unavailable_and_a_programmer_error_is_not() + { + OperatorRecoveryFaults.IsUnavailable(new InvalidOperationException("lane busy"), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsUnavailable(new NotSupportedException("not configured"), CancellationToken.None).Should().BeFalse(); + OperatorRecoveryFaults.IsUnavailable(new ArgumentException("bad"), CancellationToken.None).Should().BeFalse(); + } +} diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 2c71bd15..201da2e4 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -228,7 +228,7 @@ remain in Database Standards: [Outbox](../standards/05-database.md#outbox), | Store | Copies and subject linkage | Existing constraint | |---|---|---| -| `outbox_messages` | `actor_user_id`, identifier-only `payload`, tenant/org, partition/causation/event IDs and `correlation_id`; new producer `metadata` is SQL NULL | Platform has SELECT/DELETE, no envelope rewrite grant | +| `outbox_messages` | `actor_user_id`, identifier-only `payload`, tenant/org, partition/causation/event IDs and `correlation_id`; new producer `metadata` is SQL NULL | Platform has `DELETE` and `SELECT` of twelve metadata columns only ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)), no envelope rewrite grant | | `event_deliveries` | Independent per-subscription envelope/`payload` copy with `actor_user_id`, tenant/org, causation/trace/partition, lease, closed failure descriptor and dead-letter/replay state | No DELETE grant to runtime roles; producer cleanup does not erase this copy | | `inbox_messages` | `(tenant_id, subscription_id, event_id)` and `recorded_at`; indirect subject linkage without actor, payload or org columns | Immutable completion history; no generic Platform purge | | `background_jobs` | `causal_actor_user_id`, identifier-only `parameters`/`plan`, trace/causation, lease, closed failure/terminal descriptors and parent/recipient/operation/final-attempt links | Envelope/prepared facts stay immutable; uncertain effects retain occupancy | diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md index bc9eb749..496bc6cd 100644 --- a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -135,7 +135,7 @@ dashboard. > and `not_recoverable` are reasons on the fields `fence` and `state` of the code > `business_rule_violation`, because the status map is closed. A commit whose > answer was lost is `503` `dependency_unavailable` with the reason - > `outcome_unknown` on the field `outcome`. + > `lockey_outcome_unknown` on the field `outcome`. 6. **Not admitted: job recovery.** No job requeue, retry, probe re-arm, reservation or capacity release exists. A quarantined job stays frozen, retains its reservation and keeps `jobs` unhealthy, exactly as @@ -281,7 +281,7 @@ recovery. role held table-wide `SELECT` and `DELETE` there since the first platform migration, so a column grant beside it would exclude nothing. The migration revokes the table-wide `SELECT`, grants twelve named columns, keeps `DELETE` for the retention - purge that Phase 11 owns (its predicate reads only granted columns), and grants named + purge that Phase 11 owns (its predicate has to read only granted columns), and grants named columns on the other three tables: fifteen on `event_deliveries`, twenty-seven on `background_jobs` and every column of `background_job_reservations`. No envelope, parameter, plan, outcome, causal, trace, lease-token or operation-key column is among @@ -311,8 +311,14 @@ recovery. code would have answered `500` in the body under a `503` response. The cause of an unavailable owner is logged and never returned. A page parameter that is refused (`state`, `limit`, `cursor`) is `400` naming itself in `errors`; a `limit` of zero or - less is refused and a larger one is clamped, as Standard 04 says, and the - quarantined-jobs list takes no `state`. + less is refused and a larger one, however large, is clamped, as Standard 04 says, + the quarantined-jobs list takes no `state`, and a parameter the route does not know + is refused as `query` without being echoed. A refused state names the rule that + refused it as the `cause` parameter of its reason: `processed`, `leased`, + `invalid_envelope`, `reason_refused`, `subscription_not_active`, + `type_not_dispatchable` or `tenant_not_serving`. Only a transient fault, a timeout + or the server's statement timeout is unavailable: a refused credential or a missing + grant surfaces as a `500`, because a retry cannot cure it. 5. **"The event's tenant is Active."** The test is the lifecycle projection the dispatcher role already reads, read in the same transaction as the reset: the tenant is not deleted, has its default organization and is Trial or Active, which is the @@ -336,12 +342,16 @@ recovery. cursor carries no authority. The fence timestamp is the stored microsecond, returned and compared exactly. 7. **An unknown COMMIT is not reconciled automatically.** A reset and its row commit - together, so a lost answer leaves nothing to repair: the operator inspects, and the - fence of a landed reset has moved, so a repeat answers `409` on the fence. The - runbook says so. Any fault after the COMMIT was sent, the connection's cleanup - included, is reported the same way, because the answer is then unknown. A cleanup - fault on the operator lane seals its store as one on the dispatcher's lanes does: - the stores share the unconfirmed-cleanup seal, which only a restart clears. + together, so a lost answer leaves nothing to repair. A landed act leaves the + dead-lettered list, so the operator lists again, and a repeat of a landed act answers + `409` on the fence; the tenant's audit row, read by the correlation id, tells the act + from another operator's. The runbook says so. Any fault after the COMMIT was sent, + the connection's cleanup included, is reported the same way, because the answer is + then unknown. A cleanup fault on the operator lane seals its store as one on the + dispatcher's lanes does: the three lanes of one store share its unconfirmed-cleanup + seal, which only a restart clears, and the two stores do not share one. A sealed + store also never reports its privileged source released, so the shutdown of the + host waits as it does after a dispatcher fault. 8. **Signals.** `learnstack_platform_operator_recoveries_total{operation,outcome}` counts each transition as applied, stale fence, not recoverable, not found, unavailable or commit unknown, so a replay storm is visible. diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 06c64c88..79a02a84 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -146,7 +146,7 @@ unmarked row is one a shipped command already raises. |---|---|---|---| | `outbox_messages` | `platform.outbox.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-2 Step 2's consequential BYPASSRLS terminal transition; state and row commit together through the row-bound fifth audit seam, with stored tenant/org/event identity and SystemActor ([ADR-0046](../../decisions/0046-durable-event-delivery-and-recovery.md)) | | delivery ledger | `platform.delivery.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-3 Step 4's subscriber terminal writer binds stored tenant/org/event/subscription, acquisition token, reason and attempts to the actual fenced transition; ledger and MUST audit commit together through the same restricted fifth seam. It receives no causal-envelope or payload SELECT grant | -| delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | +| outbox, delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | | delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index df31b04a..5db58fa2 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 898 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 937 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -521,6 +521,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 3 — review round 2 and its fixes (2026-11-20)](#p03-9-step-3--review-round-2-and-its-fixes-2026-11-20) — 70 lines - [P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20)](#p03-9-step-4--operator-recovery-of-asynchronous-work-2026-11-20) — 59 lines - [P03-9 Step 4 — review round 1 and its fixes (2026-11-20)](#p03-9-step-4--review-round-1-and-its-fixes-2026-11-20) — 49 lines + - [P03-9 Step 4 — review round 2 and its fixes (2026-11-20)](#p03-9-step-4--review-round-2-and-its-fixes-2026-11-20) — 39 lines @@ -25076,3 +25077,42 @@ now pins that order, and all twenty-six are killed. socket. - **A ticket on a replay or a reset.** It is checked and not stored, because the audit row is readable by the tenant; the runbook says to record the correlation id. + +### P03-9 Step 4 — review round 2 and its fixes (2026-11-20) + +Three fresh read-only reviewers read the range with different lenses from round 1: +composition and regression; SQL, row-level security, the migration and performance; +and operability, the operator's experience and the truth of the documents. None +reported a Blocker or a Major. Each finding was checked against the code before it +was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Operability | The unavailable-owner log line reused event id 7109, which the onboarding runbooks, three ADRs and a test pin as a defect alert | The line is 7110; a test captures the log of the `503` path and asserts the id, the level and the cause | +| Failure class | Every database fault, a refused credential and a missing grant included, was reported as a retryable `503` | Only a transient fault, a timeout or the server's statement timeout is unavailable; a refused credential or a missing grant surfaces as the `500` it is, with a unit theory over the SQLSTATEs and a real-database test of both | +| Operator experience | A refused state said only that it was refused, and the unknown-outcome recipe asked the operator to observe an advanced count that a landed act never leaves | A refusal names its rule as the `cause` parameter of its reason; the runbook's unknown-outcome recipe is list again, then the tenant's audit row by the correlation id | +| Contract | A misspelt query parameter was ignored and answered a different list, a `limit` past the range of an int was refused, the jobs list advertised a `state` it refuses, and the page size was declared again at the edge | An unknown parameter is refused without being echoed, any size above the maximum is clamped, the jobs list does not offer a `state`, and the kernel's constants are used | +| Documents | Phase 11 and Architecture 23 still said the platform role reads `outbox_messages` whole; the Outbox canonical block lacked its new index; two statements said the two stores share one cleanup seal; the runbooks omitted the log ids, the cause classes of a `503` that does not clear, the response table's other statuses, the audit read recipe, the `#` encoding and the producer-reset wording | Corrected; the runbook now has a section for an unknown outcome and one for a `503` that does not clear; ADR-0103 Amendment 1 items 6, 7, 9 and 10 say what the code does | +| Tests | The keyset's tie-break columns, the indexes' keys and predicates, the plan of each dead-lettered page, a recovery admission on the platform scope and on the platform result writer, and the previous Platform head's `Down` were unpinned; two stale 52-connection literals remained | Each has a test, and the literals are corrected | + +Mutation checks of the guards this round added: the transient classification, the +refusal tokens, the unknown-parameter and limit rules, the event id, the keyset +tie-break and the executor kind of the result writer. + +#### Not changed + +- **A non-concurrent `CREATE INDEX` in the migration.** The two indexes are built in + the migration's transaction, as the earlier ledger indexes were, and the tables are + small until the retention purge of Phase 11 exists. A concurrent build, or a lock + timeout, is a deployment decision for that phase and the maintainer. +- **A single-row read or a tenant and event filter on the lists.** The recipe for an + unknown outcome does not need one, and each page is one audited scope by design; + the runbook names it as not here. +- **The failure descriptor in the audit row.** A reset clears `last_error`, so the + descriptor that caused the dead letter is not in the fence's before state. Whether + the row should carry it is a maintainer decision. +- **The platform role's loss of `SELECT` on the correlation and actor columns of + `outbox_messages`.** It constrains P03-10 and Phase 11, which need a named grant or + another principal for a predicate that reads them; Phase 11's text now says so. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 358653f0..4ffb133e 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -37,7 +37,7 @@ > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | -> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding) and Step 3 (controlled issuer rebind) delivered and twice reviewed, Steps 4 and 5 pending | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding), Step 3 (controlled issuer rebind) and Step 4 (operator recovery of asynchronous work) delivered and twice reviewed, Step 5 pending | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | diff --git a/docs/roadmap/phase-11-production-hardening.md b/docs/roadmap/phase-11-production-hardening.md index 36d12220..29f2177c 100644 --- a/docs/roadmap/phase-11-production-hardening.md +++ b/docs/roadmap/phase-11-production-hardening.md @@ -689,8 +689,12 @@ new erasure permission. - Soft delete and purge jobs. - Processed outbox, delivery, inbox and job-history purge decisions against the inventory. Among its first-party asynchronous tables, only - `outbox_messages` currently grants Platform SELECT/DELETE; - inbox, delivery and LearnStack job tables grant Platform no access. Immutable + `outbox_messages` grants Platform `DELETE`; Platform reads twelve metadata columns of + it, fifteen of `event_deliveries`, twenty-seven of `background_jobs` and every + column of `background_job_reservations` + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)), and the + inbox grants it no access. A purge predicate that needs another column needs a + named grant or another principal. Immutable completion/execution facts and no-delete guards remain effective even with `BYPASSRLS`. Before the first purge writer, a bounded decision names the exact principal, minimum grants and required migration, eligible facts, dependency diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 976bab8e..3a2ce479 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -165,11 +165,11 @@ production realm. | 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached: at start, or for more than 15 minutes after its keys were last fetched | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | | 403 | The token is good and this operator holds no grant for the act | Ask for the grant | | 400 | The ticket or the body is malformed | Fix the request | -| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, or the surface is not configured | Check the key or the tenant and the issuer setting | -| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant) | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) | +| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, a recovery that names no such row, or the surface is not configured | Check the key, the tenant or the row and the issuer setting | +| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant), or a recovery found a stale fence or a row it may not act on | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) or the [recovery runbook](operator-recovery.md#act) | | 415 | The body is not `application/json` | Send the header shown above | -| 503 | The audit row could not be written, so nothing changed. `Retry-After` says when to try again | Retry; the act is safe to repeat | -| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request | +| 503 | The audit row could not be written, or a connection or a lane was unavailable, so nothing changed, except that a recovery's `503` can carry `errors.outcome` for a commit that may have landed. `Retry-After` says when to try again | Retry; the act is safe to repeat. For a recovery that names `errors.outcome`, read the [recovery runbook](operator-recovery.md#an-unknown-outcome) first | +| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request. A recovery is not: list again first | The answer to a refused credential is always the same; the reason is in the signals, not the response. @@ -190,11 +190,14 @@ A log line accompanies each. Search by event id: 7102 (Warning) a refused act, 7 (Warning) a refused credential with its cause, 7106 (Warning) a metadata failure, 7105 (Error) a refused audit write, and 7101 (Error) a grant configuration that failed validation on reload; while 7101 appears every operator act is refused until the -configuration is valid. Every admitted killswitch act logs a Warning with event 7001 and -the text "Platform-admin scope entered" (other hosts reuse the number for unrelated -lines, so match the text too); the onboarding acts do not enter the platform scope and -log no 7001. Event 7109 (Warning) is an onboarding act the request pipeline itself -refused as forbidden. A refused operator leaves no database row; the one exception is an +configuration is valid. Every admitted killswitch act and every recovery inspection page +logs a Warning with event 7001 and the text "Platform-admin scope entered" (other hosts +reuse the number for unrelated lines, so match the text too); the onboarding acts and the +two recovery acts do not enter the platform scope and log no 7001. Event 7109 (Warning) +is an onboarding act the request pipeline itself refused as forbidden, which is a +defect. Event 7110 (Warning) is a recovery or an inspection the owner could not finish, +with whether its commit's outcome is unknown; see the [recovery +runbook](operator-recovery.md#a-503-that-does-not-clear). A refused operator leaves no database row; the one exception is an onboarding act an admitted operator had refused for a business reason, which writes a `failed` row in the tenant. diff --git a/docs/runbooks/operator-recovery.md b/docs/runbooks/operator-recovery.md index 3f935215..604fec76 100644 --- a/docs/runbooks/operator-recovery.md +++ b/docs/runbooks/operator-recovery.md @@ -19,9 +19,17 @@ Authentication, the token profile and how a grant is given are in [Platform oper access](operator-access.md). The served operator document, `platform-v1`, is the contract for these routes, and it is the only client there is. -A reset changes a row. An inspection changes nothing: it reads metadata only, and it +An act changes a row. An inspection changes nothing: it reads metadata only, and it cannot read an event body, a job's parameters or plan, a causal id or a lease token, -because the database refuses those columns to the platform role. +because the database refuses those columns to the platform role. The inspections need +the Platform migration `20261120120000` applied; without it the first one fails with a +permission error in the API's log. + +Three names for one thing trip people. The act on a subscriber delivery is a **replay** +and writes `platform.delivery.replay`. The act on an outbox row is a **producer reset** +and writes `platform.delivery.reset`. The rows the dispatcher itself writes when it +gives up are `platform.delivery.dead_letter` (a delivery) and +`platform.outbox.dead_letter` (an outbox row). ## What is not here @@ -29,11 +37,14 @@ because the database refuses those columns to the platform role. `jobs` health check unhealthy. Nothing here requeues, retries, releases or re-arms it, because the only proof that would make that safe is a provider's fence or the termination of the process that started the effect, and no adapter can supply one - today. The inspection shows the job and how many reservations hold capacity; it is an - operator's evidence for an escalation, not a remedy. + today. The inspection shows the job (`phase`, `quarantineReason`), how many + reservations it holds (`heldReservations`) and how many its capacity group holds + (`groupOccupancy`); it is an operator's evidence for an escalation, not a remedy. - **A recurrence skip, pause or resume.** None exists. - **The Hangfire dashboard.** `/admin/hangfire` answers 404 in every deployment mode. - **A privileged subscription.** A delivery that belongs to one is refused. +- **A read of one row.** The lists are oldest first and cannot be filtered by tenant or + event, so finding one row means paging; each page is one audited scope. ## When to look @@ -48,44 +59,55 @@ Each page is one entered platform scope, so each page writes one `platform.admin_scope.enter` audit row with the reason `delivery_inspect`, your attribution and your ticket. It does not say which of the three lists you read or how far you paged. Pass the ticket as `?ticket=`: 1 to 64 letters, digits or `.` `_` `:` -`/` `#` `-`. Inspections run on `ConnectionStrings:PlatformAdmin`; the two acts run on -`ConnectionStrings:OutboxDispatcher` ([setup](operator-access.md#what-must-be-configured)). +`/` `#` `-`, and percent-encode `#` as `%23`, because a bare `#` ends the query. +Inspections run on `ConnectionStrings:PlatformAdmin`; the two acts run on +`ConnectionStrings:OutboxDispatcher` +([setup](operator-access.md#what-must-be-configured)). ```sh curl -s -H "Authorization: Bearer $TOKEN" \ "$API/api/platform/v1/asynchronous-work/outbox-messages?state=dead_lettered&limit=20&ticket=CHG-123" ``` -- `state` is `dead_lettered` (default) or `terminal_requested`. A **terminal requested** +- `state` is `dead_lettered` (default) or `terminal_requested`. A **terminal-requested** row has a terminal reason recorded and the commit of its dead-letter not yet made: its state is shown and it is **not actionable**. It becomes dead-lettered by itself, or it - does not. -- `limit` is 1 to 100 (default 20; a larger value is clamped, zero or less is refused - with `errors.limit`). The answer holds `items` and a `pageInfo` with `nextCursor` - and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs to the route and - state that issued it. The quarantined-jobs list takes no `state`. -- Each row carries `eventType` as the registry's label (never stored text), `lastError` - (a descriptor such as `publish:failed:provider`, or `unrecognized`) and `actionable`. - Treat `actionable` as advice about the row and the registry: the act also checks the - tenant's service state and the fence, so a suspended tenant's row can be listed - actionable and refused. + does not. One that stays means the dispatcher cannot write its audit row or has + stopped: look at the `outbox`, `delivery` and audit health checks and the error + line 7105 in the dispatcher's host log. +- `limit` is 1 to 100 (default 20; a larger value, however large, is clamped, and zero + or less is refused with `errors.limit`). The answer holds `items` and a `pageInfo` + with `nextCursor` and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs + to the route and state that issued it. The quarantined-jobs list takes no `state`. +- Each row carries `eventType` as the registry's label (`unknown` and `retired` mean + the registry no longer dispatches that stored type), `lastError` and `actionable`. + `lastError` is the dispatcher's closed descriptor of the last failure, whose first + part says where it failed (`publish:`, `execute:`, `recovery:` or `terminal:`), or + `unrecognized`. It carries no handler message: that is in the dispatcher's log, found + by event type and subscription. Treat `actionable` as advice about the row and the + registry: the act also checks the tenant's service state and the fence, so a suspended + tenant's row can be listed actionable and refused. - **The fence travels with the row.** A delivery shows `replayCount`, `deadLetteredAt`, - `terminalReason`; an outbox row shows `attempts` and `deadLetteredAt`. - `deadLetteredAt` has microsecond precision: send it back **exactly as returned**. + `terminalReason`; an outbox row shows `attempts` and `deadLetteredAt`. Send **every** + fence field back exactly as returned. `deadLetteredAt` has microsecond precision: a + client that parses it and writes it back at millisecond precision, or changes the + case of a reason, sends a fence that never matches. ## Choose: replay or reset - **Replay** resets one *delivery*: one subscription of one event. Use it when a subscriber's handler failed for a reason that is now fixed, or its subscription became - Active. The completed siblings, the inbox row, the producer row and every other event - are untouched. + Active. Its reasons are `retry_exhausted`, `unknown_type`, `retired_type` and + `invalid_subscription`. It renews the delivery's attempts to zero too. The completed + siblings, the inbox row, the producer row and every other event are untouched. - **Producer reset** resets one *outbox row* whose terminal reason is `retry_exhausted`: - a burst of dispatch failures used up its six attempts. Use it when the event was never - published. It **renews the six-attempt budget**, so a row that fails for a lasting - reason fails six more times and is dead-lettered again with a new audit row. The reset - reaches the subscriptions that have no delivery row yet, and a publication that - already reached a subscriber is absorbed by the event's stable identity; a delivery - that already ended terminal needs its own replay. + a burst of dispatch failures, and not the event itself, used up its six attempts. It + **renews the six-attempt budget**, so a row that fails for a lasting reason fails six + more times and is dead-lettered again, after about an hour and six minutes of + backoff, with a new audit row. The reset reaches the subscriptions that have no + delivery row yet, and a publication that already reached a subscriber is absorbed by + the event's stable identity; a delivery that already ended terminal needs its own + replay. - **Neither** if the reason is `invalid_envelope`: the stored envelope is immutable and cannot become valid. For a *replay*, a reason of `unknown_type` or `retired_type` follows the registry now: an event the registry still does not know, or has retired, @@ -95,50 +117,102 @@ curl -s -H "Authorization: Bearer $TOKEN" \ ## Act -Send the fence read at inspection, and a ticket if you have one: +Send the fence read at inspection. A ticket is optional and is **checked, not stored**: +the audit row is readable by the tenant, so it never carries one (see [Check it +worked](#check-it-worked)). ```sh curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ "$API/api/platform/v1/asynchronous-work/event-deliveries/$TENANT/$SUBSCRIPTION/$EVENT/replay" \ - -d '{"replayCount":0,"deadLetteredAt":"2026-10-01T12:00:00.123456Z","terminalReason":"retry_exhausted","ticket":"CHG-123"}' + -d '{"replayCount":0,"deadLetteredAt":"2026-10-01T12:00:00.123456+00:00","terminalReason":"retry_exhausted","ticket":"CHG-123"}' ``` ```sh curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ "$API/api/platform/v1/asynchronous-work/outbox-messages/$TENANT/$EVENT/reset" \ - -d '{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.123456Z","ticket":"CHG-123"}' + -d '{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.123456+00:00","ticket":"CHG-123"}' +``` + +A refusal names its reason inside `errors`, as a list under the field, so with `jq` a +stale fence is `.errors.fence[0].key`, a refused state is `.errors.state[0].key` and its +rule is `.errors.state[0].params.cause`, and an unknown commit outcome is +`.errors.outcome[0].key`: + +```json +{ "status": 409, "code": "business_rule_violation", + "errors": { "state": [ { "key": "lockey_not_recoverable", "params": { "cause": "tenant_not_serving" } } ] } } ``` | Answer | Meaning | |---|---| | `200`, `outcome: applied` | The row was reset and its MUST audit row committed with it. `countAfter` is the new replay count, or zero attempts | -| `409`, `errors.fence` = `lockey_stale_fence` | The row no longer shows the fence you sent: the dispatcher, another operator or a retry moved it. Nothing changed and nothing was written. **Inspect again** and decide again | -| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one an act may take: `invalid_envelope`, a reason a producer reset refuses, a subscription that is no longer Active, an event type the registry no longer knows, or a tenant that is not serving (not Trial or Active, or deleted). Nothing changed | +| `409`, `errors.fence` = `lockey_stale_fence` | The row no longer shows the fence you sent: the dispatcher, another operator or a retry moved it, or a fence field was altered on the way back. Nothing changed and nothing was written. **List again** and decide again. If it persists on a fence you just read, a field was not sent exactly as returned | +| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one the act may take. The rule is `params.cause`: `processed`, `leased`, `invalid_envelope`, `reason_refused` (a producer reset acts only on `retry_exhausted`), `subscription_not_active`, `type_not_dispatchable` (the registry has retired the type or no longer knows it) or `tenant_not_serving` (not Trial or Active, or deleted: nothing here changes a tenant's state, so escalate). Nothing changed | | `404` | No such row for that tenant | -| `403` | You hold no `platform.delivery.write` grant. Nothing was opened | +| `401` | The credential is missing or does not meet the token profile; the cause is in [the operator's signals](operator-access.md#signals) | +| `403` | You hold no grant for the route: `platform.delivery.read` for a list, `platform.delivery.write` for an act. Nothing was opened | | `400` | The route, the body or the ticket is malformed. A refusal at the gate carries no per-field errors; a refused page parameter names itself (`errors.state`, `errors.limit`, `errors.cursor`) | -| `503`, `audit_unavailable` | The MUST row could not be written, so nothing changed. Retry after the delay | -| `503`, `dependency_unavailable` | A connection, the one operator lane or an inspection's read was unavailable. Nothing changed. Only one operator call runs per store at a time, and a second is refused at once and not queued; retry after the delay. The cause is in the API's log, never in the response | -| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost, or a fault followed it. It **may have landed**. **Inspect the row before repeating**: a landed reset shows an advanced `replayCount` (or `attempts` of zero), and a repeat of the same request would answer `409` `lockey_stale_fence` | +| `413`, `415`, `429` | The body is over 4096 bytes, is not `application/json`, or the caller exceeded the per-peer request budget | +| `500` | An unexpected failure, a missing connection string or a deployment defect such as a refused credential or a missing grant: the API's log names it. An act's commit may have landed: list again before changing anything | +| `503`, `audit_unavailable` | The MUST row could not be written, so nothing changed. Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | A connection, the one operator lane or an inspection's read was unavailable. Nothing changed. Only one operator call runs per store at a time, and a second is refused at once and not queued; retry after the delay. The cause is in the API's log (warning 7110), found by the response's `correlationId`, and never in the response; see [A `503` that does not clear](#a-503-that-does-not-clear) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost, or a fault followed it. It **may have landed**. **Do not repeat blindly**: see [An unknown outcome](#an-unknown-outcome) | An applied replay makes the delivery due at once; the dispatcher claims it like any -other. +other. A client that never received any answer (a timeout, a gateway error) is in the +same position as an unknown outcome. + +## An unknown outcome + +A landed act leaves the dead-lettered list: it clears the terminal fields. So an +advanced count is not what you will find. Reconcile in this order: + +1. List again. If the row is **gone**, or it is there with a **new** fence (a new + `deadLetteredAt`), the act landed; if it still carries the fence you sent, it did not + land, and repeating it is safe. +2. To tell *your* act from another operator's, read the tenant's audit row by the + `correlationId` of the failed response, as in [Check it worked](#check-it-worked). + A repeat of an act that had landed answers `409` on `errors.fence`, and that answer + alone cannot say whose act it was. ## Check it worked -1. Inspect the row: it is no longer in the dead-lettered list (an applied reset moves it +1. List again: the row is no longer in the dead-lettered list (an applied act moves it back to the ordinary queue). 2. Watch the dispatcher claim it: `learnstack_delivery_pending_count` or - `learnstack_outbox_pending_count` moves, and the executor runs the handler. A reset - row that fails for a lasting reason is dead-lettered again after its attempts, with a - second `platform.*.dead_letter` row. Fix the cause before you reset again. + `learnstack_outbox_pending_count` moves, unless the type is not yet Active, and the + executor runs the handler. A row that fails for a lasting reason is dead-lettered + again after its attempts, with a second `platform.*.dead_letter` row. Fix the cause + before you act again. 3. Read the audit trail. The row is in the **tenant's** trail (it names the real event tenant) with no actor, the operation `platform.delivery.replay` or `platform.delivery.reset`, the reason `delivery_replay` or `delivery_reset`, your attribution in `metadata.operator` and the fence before and after in - `metadata.fence`. The ticket is not on it, because the tenant can read it: a - ticket sent with an act is checked and not stored, so record the response's - `correlationId` against your own change reference. + `metadata.fence`. There is no audit API: read it as the application role + announcing the tenant, by the response's `correlationId`, with the query and the + digest recipe of [Tenant onboarding](tenant-onboarding.md#reading-the-record) and + [Killswitch](killswitch.md#reading-the-record). The ticket is not on it, because the + tenant can read it: record the `correlationId` against your own change reference. + +## A 503 that does not clear + +A `503` `dependency_unavailable` is retryable, and one that never clears is not a +transient fault. Find the cause in the API's host log by the response's `correlationId` +(warning 7110; it carries the operation and whether the outcome is unknown, and the +exception holds the cause): + +- **The lane is busy.** Another operator call is running on that store: wait for it and + send acts one at a time. +- **The database or the credential.** `ConnectionStrings:OutboxDispatcher` (acts) or + `ConnectionStrings:PlatformAdmin` (inspections) cannot connect. A refused credential + or a missing grant is not reported as a `503`: it is a `500` and the log names it. A + connection string that is not set is a `500` on an inspection and a `503` on an act, + and in both the log names the key. +- **The store is sealed.** A connection-cleanup fault on a lane seals that store, for + the dispatcher's own lanes too: its claims fail, so the outbox or the delivery + dispatch halts, and every call to it answers `503` until the API instance restarts. + The remedy is to restart the instance. The three lanes of one store share the seal, and the two + stores do not. ## Signals @@ -147,7 +221,8 @@ transition by `applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavail and `commit_unknown`. A rising `stale_fence` is two operators, or a script, replaying the same rows. `learnstack_platform_operator_audit_failures_total` counts the refusals for an audit failure, and the admission and refusal counters are in [Platform operator -access](operator-access.md#signals). +access](operator-access.md#signals). Each inspection page also logs the scope-entry line +7001, as a killswitch act does. ## Limits @@ -159,10 +234,9 @@ access](operator-access.md#signals). nothing here releases it. Reissuing an invitation helps only while the tenant has a free slot; it neither reconciles nor releases the old effect, and four unresolved effects can hold every slot with no operator remedy. -- **Capacity.** The operator lane is one connection per store, so replays are one at a +- **Capacity.** The operator lane is one connection per store, so acts are one at a time, and a second concurrent call is refused with `503` at once. Send them one after - another. A connection-cleanup fault on that lane seals its store as one on the - dispatcher's lanes does, and only a restart clears it. + another. ## Not recoverable here diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 2c8a3bb1..d65a0c88 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -1628,6 +1628,9 @@ CREATE INDEX ix_outbox_messages_recovery CREATE INDEX ix_outbox_messages_terminal ON outbox_messages (available_after, occurred_at, id) WHERE processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL; +-- ADR-0103: the operator inspection's dead-lettered page, in key order. +CREATE INDEX ix_outbox_messages_dead_lettered + ON outbox_messages (dead_lettered_at, id) WHERE dead_lettered_at IS NOT NULL; ALTER TABLE outbox_messages ENABLE ROW LEVEL SECURITY; ALTER TABLE outbox_messages FORCE ROW LEVEL SECURITY; @@ -6509,8 +6512,10 @@ for every column-grant table. The database bounds which columns a page can read the length of `last_error`, not its content, so the inspection shows a `last_error` only when it has the shape of the dispatcher's descriptors. Two partial indexes, `ix_outbox_messages_dead_lettered` and `ix_event_deliveries_dead_lettered`, serve -the dead-lettered scan the inspection pages by keyset. The migration is -forward-only. +the dead-lettered scan the inspection pages by keyset, and a test asks PostgreSQL for +the plan of the statement the inspection runs. The migration builds them without +`CONCURRENTLY`, inside its transaction, as the earlier ledger indexes were. The +migration is forward-only. ### The two transitions @@ -6557,9 +6562,12 @@ Real PostgreSQL as each role: acknowledgement; the real `OperatorRecovery` owner reaching the right store and counting each outcome under its own operation; and the siblings and the inbox byte-identical after a replay. -- `DeliveryInspectionTests`: pages and keyset cursors (equal instants included), a - cursor refused under another resource or state, the entry row, the job occupancy - counts, the descriptor shape of `last_error`, and the exact columns the platform - role can and cannot select. +- `DeliveryInspectionTests`: pages and keyset cursors (equal instants and the + tenant, subscription and event tie-break included), a cursor refused under another + resource or state, the entry row, the job occupancy counts, the descriptor shape of + `last_error`, the exact columns the platform role can and cannot select, the two + indexes' keys and predicates and the plan of each dead-lettered page, and a + refused credential surfacing as a defect where an unreachable database is a + retryable outage. - `PlatformOperatorHttpTests` and `PlatformAdminGateTests`: the routes, their statuses and contract, and the pair of permissions, each held alone. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 9b3762f9..c347c104 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -6000,23 +6000,25 @@ structural test proves — and what it does not. - **Asserts:** by IL, over every production assembly, that `OperatorRecoveryTransition` is sealed with one private live-reader constructor, readonly state and getter-only - properties, in an assembly with no friend; that its nested `MintingSource` is public, - abstract and protected-constructed with exactly the two protected static factories - (`FromReplayUpdate`, `FromResetUpdate`); that the only subtypes are the private sealed - `RecoveryMint` classes nested in `DeliveryDispatchStore` and `OutboxDispatchStore`; that - the factories' only callers are those classes' two wrappers, whose only callers are the - stores' `ReplayCoreAsync` and `ResetCoreAsync`; that the witness constructor's only - callers are the factories; and that `IAuditStore.WriteOperatorRecoveryAsync` is declared - on the port and implemented by `PostgresAuditStore` alone, with the two stores' - `WriteRecoveryRowAsync` as its only callers. Its companion + properties, in an assembly with no friend; that its nested `MintingSource` is + public, abstract and protected-constructed with exactly the two protected static + factories (`FromReplayUpdate`, `FromResetUpdate`); that the only subtypes are the + private sealed `RecoveryMint` classes nested in `DeliveryDispatchStore` and + `OutboxDispatchStore`; that the factories' only callers are those classes' two + wrappers, whose only callers are the stores' `ReplayCoreAsync` and `ResetCoreAsync`; + that the witness constructor's only callers are the factories; and that + `IAuditStore.WriteOperatorRecoveryAsync` is declared on the port and implemented by + `PostgresAuditStore` alone, with the two stores' `WriteRecoveryRowAsync` as its only + callers. Its companion `Operator_recovery_census_detects_extra_derivers_constructors_and_callers` plants a - second subtype, an extra mint helper, a direct constructor call, an extra writer caller - and a helper on the sanctioned store, and requires the same detector to reject each. -- **Why it matters:** the witness is evidence that a row was reset under a fence in a live - transaction, and it binds the audit row to the admitted operation, the operator and the - fence. A second way to make one, or to write the row, is a second way to forge that - evidence. The terminal witness could not carry an operator, so this is a sibling, not - a third factory on it. + second subtype, an extra mint helper for each factory, a direct constructor call, an + extra writer caller and a helper on the sanctioned stores, and requires the same + detector to reject each. +- **Why it matters:** the witness is evidence that a row was reset under a fence in a + live transaction, and it binds the audit row to the admitted operation, the operator + and the fence. A second way to make one, or to write the row, is a second way to + forge that evidence. The terminal witness could not carry an operator, so this is a + sibling, not a third factory on it. - **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 5 and its Amendment 1. - **Type:** xUnit + IL scan. **Kind:** structural. @@ -6031,8 +6033,8 @@ structural test proves — and what it does not. implementation, the persistence composition and the recovery routes. Adding a caller is a deliberate edit here, with its denied proof. - **Why it matters:** the two transitions are the dispatcher's second writer and the - inspection reads across tenants; a handler that held either port would reach a reset or - a cross-tenant read from a request path the operator gate does not guard. + inspection reads across tenants; a handler that held either port would reach a + reset or a cross-tenant read from a request path the operator gate does not guard. - **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 4. - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 4). From 5392089c2ea8322851d4202069d3ff296438d097 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 14:42:38 +0300 Subject: [PATCH 20/28] feat(platform): federation operator report, remove and disable Implements ADR-0099 Amendments 10 and 11: a platform operator reports, removes and disables the identity-provider brokers a tenant's federation left orphaned, unreadable or nonconforming, through the confined admin client and a separate IFederationOperator port. No realm user is listed or removed; the account review a remove owes is a runbook step. A remove or a disable writes an MUST intent row at a checkpoint on the platform scope handle (ADR-0044 Amendment 18, a fifteenth IAuditStore write), commits it, changes the provider, then writes the completion row, both under the tenant the owner marker names. learnstack_platform reads four columns of federation_connections through an Identity-chain grant migration. The audit-writing service tests run on an isolated database because audit_log is append-only. ADR: 0044, 0099 Module: Identity, Tenancy, Platform Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 1 + .../Composition/FederationComposition.cs | 10 + .../PersistenceCompositionExtensions.cs | 3 + .../PlatformOperatorEndpoints.Federation.cs | 189 ++++++ .../Platform/PlatformOperatorEndpoints.cs | 1 + .../PostgresAuditStore.cs | 53 ++ .../Federation/FederationAdapterFactory.cs | 4 + .../Federation/KeycloakFederationProfile.cs | 27 + .../KeycloakFederationProvider.Operator.cs | 274 ++++++++ .../Federation/KeycloakFederationProvider.cs | 22 +- .../Federation/KeycloakFederationRoutes.cs | 34 +- .../MultiTenancy/PlatformAdminScope.cs | 126 +++- .../PlatformOperatorMetrics.cs | 15 + .../Audit/IAuditStore.cs | 26 +- .../Identity/IFederationOperator.cs | 144 +++++ .../Platform/IFederationBrokerOperations.cs | 100 +++ .../Platform/PlatformOperation.cs | 33 +- .../Platform/PlatformPermissions.cs | 13 +- .../Tenancy/IPlatformAdminScope.cs | 19 +- .../IdentityFoundationRegistration.cs | 2 + .../Federation/FederationBrokerOperations.cs | 360 +++++++++++ .../FederationOperatorProjectionDdl.cs | 27 + ...00_grant_platform_federation_projection.cs | 17 + .../Audit/TenancyAuditCatalogSource.cs | 17 +- .../AuditConventionTests.cs | 5 +- .../FederationAdapterConventionTests.cs | 3 +- .../FederationApplicationConventionTests.cs | 36 +- ...tegrationDeliveryLifecycleBoundaryTests.cs | 2 + .../PlatformAdminScopeConventionTests.cs | 32 + .../FederationBrokerOperationsTests.cs | 587 ++++++++++++++++++ .../Database/MigrationRollbackTests.cs | 6 +- .../Database/PlatformAdminScopeTests.cs | 244 ++++++++ .../KillswitchToggleOrderingTests.cs | 6 + .../PlatformOperatorHttpTests.cs | 216 ++++++- .../FederationProviderTests.Operator.cs | 168 +++++ .../KeycloakFederationProviderTests.cs | 371 ++++++++++- .../MultiTenancy/PlatformAdminGateTests.cs | 25 +- docs/architecture/31-audit-subsystem.md | 7 + docs/decisions/0044-audit-write-path.md | 32 + .../0099-confined-tenant-federation.md | 87 +++ docs/glossary.md | 1 + docs/modules/identity/README.md | 41 ++ docs/modules/identity/audit.md | 10 + docs/modules/identity/providers.md | 33 + docs/modules/tenancy/audit.md | 5 + docs/modules/tenancy/permissions.md | 14 +- docs/roadmap/phase-03-delivery-log.md | 74 ++- docs/runbooks/README.md | 1 + docs/runbooks/federation-operator.md | 256 ++++++++ docs/runbooks/operator-access.md | 19 +- docs/standards/04-api-design.md | 7 +- docs/standards/05-database.md | 22 +- docs/standards/10-observability.md | 1 + docs/standards/11-security.md | 9 +- docs/standards/18-audit-coverage.md | 10 +- docs/standards/19-permissions.md | 4 +- docs/standards/20-infrastructure-stack.md | 6 + .../21-architecture-tests-catalogue.md | 38 +- scripts/ci-test-shards-plan.json | 1 + 59 files changed, 3809 insertions(+), 87 deletions(-) create mode 100644 backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs create mode 100644 backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs create mode 100644 backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs create mode 100644 backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs create mode 100644 docs/runbooks/federation-operator.md diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 98812665..8f3f0a01 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -95,6 +95,7 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum "PlatformFirstAdminCreate" or "PlatformAdminRecover" => typeof(Platform.AdministratorRequest), "PlatformDeliveryReplay" => typeof(Platform.DeliveryReplayBody), "PlatformOutboxReset" => typeof(Platform.OutboxResetBody), + "PlatformFederationRemove" or "PlatformFederationDisable" => typeof(Platform.FederationActBody), _ => throw new InvalidOperationException("An operator operation declares no request body: " + operationId), }; diff --git a/backend/src/LearnStack.Api/Composition/FederationComposition.cs b/backend/src/LearnStack.Api/Composition/FederationComposition.cs index cf768b27..9a37feef 100644 --- a/backend/src/LearnStack.Api/Composition/FederationComposition.cs +++ b/backend/src/LearnStack.Api/Composition/FederationComposition.cs @@ -41,6 +41,8 @@ internal static IServiceCollection AddLearnStackFederationAdapter(this IServiceC || policy.Bulkhead is not { MaxConcurrency: 4, QueueLength: 0 }) throw new InvalidOperationException("Federation requires finite provider resilience without write retries."); services.AddProviderResilience(policyConfiguration, "federation"); + // The operator's calls run under their own pipeline of the same fixed shape, so a sweep cannot starve a tenant's. + services.AddProviderResilience(policyConfiguration, "federation"); var egress = new FederationEgressOptions(configuration.GetSection(AllowedHostsKey).Get() ?? []); services.TryAddSingleton(egress); @@ -52,6 +54,14 @@ internal static IServiceCollection AddLearnStackFederationAdapter(this IServiceC var options = new KeycloakFederationOptions(configuration["Authentication:Tenant:Issuer"] ?? "", development); return FederationAdapterFactory.CreateProvider(options, secrets, provider.GetRequiredService>()); })); + services.Replace(ServiceDescriptor.Singleton(provider => + { + var secrets = provider.GetRequiredService(); + if (!Configured(secrets)) return new UnconfiguredFederationOperator(); + var development = provider.GetRequiredService().IsDevelopment(); + var options = new KeycloakFederationOptions(configuration["Authentication:Tenant:Issuer"] ?? "", development); + return FederationAdapterFactory.CreateOperator(options, secrets, provider.GetRequiredService>()); + })); services.Replace(ServiceDescriptor.Singleton(provider => Configured(provider.GetRequiredService()) ? FederationAdapterFactory.CreateEgressFetcher(provider.GetRequiredService()) diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index 909a7619..d2526831 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -306,6 +306,9 @@ public static IServiceCollection AddLearnStackPersistence( services.TryAddScoped(); // The operator inspection of asynchronous work reads in the platform scope on column grants (ADR-0103 § 1). services.TryAddScoped(); + // ADR-0099 Amendment 10: the operator's federation report, remove and disable, over the platform scope and the + // operator port, which the composition root replaces with the confined adapter when the admin client is configured. + services.TryAddScoped(); // The entitlement socket. A SINGLETON and registered in EVERY deployment mode, // not Development only: ADR-0035 names NullEntitlementProvider the working default diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs new file mode 100644 index 00000000..29a72844 --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs @@ -0,0 +1,189 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Mvc; + +namespace LearnStack.Api.Platform; + +/// The optional ticket of a federation act; the body is otherwise empty. +/// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. +internal sealed record FederationActBody( + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); + +/// One page of the federation report. +internal sealed record FederationReportResponse( + IReadOnlyList Items, InspectionPageInfo PageInfo, int Scanned, int Ignored); + +/// What an applied or repeated federation act answers; the account review is the operator's to start. +internal sealed record FederationActResponse( + string Outcome, string Alias, Guid? TenantId, Guid? ConnectionId, bool AccountReviewOwed, string CorrelationId); + +/// +/// The federation routes of the operator surface (ADR-0099 Amendment 10): a report of the identity-provider brokers a +/// tenant's federation left orphaned, unreadable or nonconforming, a remove and a disable. Each runs the gate first. A +/// remove or a disable writes an intent row before the provider call and a completion row after it; a refusal that +/// precedes the intent writes no tenant row. +/// +internal static partial class PlatformOperatorEndpoints +{ + private const string FederationPrefix = "/federation/brokers"; + + private static readonly Regex DerivedAliasPattern = new( + @"\Alsf-[0-9a-f]{32}\z", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100)); + + private static readonly string[] FederationReportParameters = ["limit", "cursor", "ticket"]; + + private static void MapFederation(RouteGroupBuilder group) + { + DescribeInspection( + group.MapGet(FederationPrefix, ReportFederationAsync) + .WithName("PlatformFederationReport") + .WithSummary("Report identity-provider brokers that are orphaned, unreadable or nonconforming; the realm is read first, then the rows."), + typeof(FederationReportResponse)); + Describe( + group.MapPost(FederationPrefix + "/{alias}/remove", RemoveFederationAsync) + .WithName("PlatformFederationRemove") + .WithSummary("Remove an orphaned or unreadable owned broker at the provider; the provider deletes its federated links.") + .WithDescription( + "Refused while a live connection row names the broker. An absent broker is already removed. The tenant's " + + "intent and completion rows are written around the provider call; the delegated-account review is the " + + "operator's, by runbook. A ticket is checked and not stored."), + typeof(FederationActResponse)); + Describe( + group.MapPost(FederationPrefix + "/{alias}/disable", DisableFederationAsync) + .WithName("PlatformFederationDisable") + .WithSummary("Disable a nonconforming or unreadable owned broker at the provider only; the tenant's row is left to its next readback.") + .WithDescription( + "Sets enabled to false and nothing else, on an instance whose owner marker is proven. A healthy broker with " + + "a live row is refused. A ticket is checked and not stored."), + typeof(FederationActResponse)); + } + + private static async Task ReportFederationAsync( + [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, HttpContext http, + IPlatformOperatorGate gate, IFederationBrokerOperations operations, ILoggerFactory loggers, + CancellationToken cancellationToken) + { + var operation = PlatformOperations.FederationReport; + var (refusal, admission) = await AdmitAsync(http, gate, operation, ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (!TryLimit(limit, out var size)) + { + return InvalidParameter(http, "limit"); + } + + if (http.Request.Query.Keys.Any(key => !FederationReportParameters.Contains(key, StringComparer.Ordinal))) + { + return InvalidParameter(http, "query"); + } + + try + { + var result = await operations.ReportAsync(admission!, cursor, size, cancellationToken); + PlatformOperatorMetrics.Federation(operation, result.Outcome switch + { + FederationReportOutcome.Ok => "ok", + FederationReportOutcome.InvalidCursor => "invalid_cursor", + _ => "unavailable", + }); + return result.Outcome switch + { + FederationReportOutcome.Ok => Results.Ok(new FederationReportResponse( + result.Items, new InspectionPageInfo(result.NextCursor, null, result.NextCursor is not null, false), + result.Scanned, result.Ignored)), + FederationReportOutcome.InvalidCursor => InvalidParameter(http, "cursor"), + _ => UnavailableProblem(http, loggers, operation, new OperatorRecoveryUnavailableException()), + }; + } + catch (AuditWriteFailedException failure) + { + return AuditUnavailableProblem(http, loggers, operation, failure); + } + } + + private static Task RemoveFederationAsync( + string alias, HttpContext http, IPlatformOperatorGate gate, IFederationBrokerOperations operations, ILoggerFactory loggers, + CancellationToken cancellationToken) => + FederationActAsync( + alias, PlatformOperations.FederationRemove, http, gate, loggers, + (admission, cancel) => operations.RemoveAsync(admission, alias, cancel), cancellationToken); + + private static Task DisableFederationAsync( + string alias, HttpContext http, IPlatformOperatorGate gate, IFederationBrokerOperations operations, ILoggerFactory loggers, + CancellationToken cancellationToken) => + FederationActAsync( + alias, PlatformOperations.FederationDisable, http, gate, loggers, + (admission, cancel) => operations.DisableAsync(admission, alias, cancel), cancellationToken); + + private static async Task FederationActAsync( + string alias, + PlatformOperation operation, + HttpContext http, + IPlatformOperatorGate gate, + ILoggerFactory loggers, + Func> act, + CancellationToken cancellationToken) + { + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, operation, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (body is null || !DerivedAliasPattern.IsMatch(alias)) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await act(admission!, cancellationToken); + PlatformOperatorMetrics.Federation(operation, FederationOutcomeToken(result.Outcome)); + return result.Outcome switch + { + FederationActOutcome.Applied => Results.Ok(FederationResponse("applied", alias, result, admission!, http, true)), + FederationActOutcome.AlreadyApplied => Results.Ok(FederationResponse("already_applied", alias, result, admission!, http, false)), + FederationActOutcome.NotFound => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), + FederationActOutcome.NotOwned => ResultProblem(http, Rule("owner", "lockey_not_owned")), + FederationActOutcome.LiveConnection => ResultProblem(http, Rule("connection", "lockey_live_connection")), + FederationActOutcome.NotApplicable => ResultProblem(http, Rule("class", "lockey_not_applicable")), + FederationActOutcome.Refused => ResultProblem(http, Rule("provider", "lockey_provider_refused")), + FederationActOutcome.Unavailable => UnavailableProblem(http, loggers, operation, new OperatorRecoveryUnavailableException()), + _ => UnavailableProblem( + http, loggers, operation, new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true)), + }; + } + catch (AuditWriteFailedException failure) + { + return AuditUnavailableProblem(http, loggers, operation, failure); + } + } + + private static FederationActResponse FederationResponse( + string outcome, string alias, FederationActResult result, PlatformAdmission admission, HttpContext http, bool accountReviewOwed) => + new(outcome, alias, result.TenantId, result.ConnectionId, accountReviewOwed, + admission.Operator.CorrelationId ?? http.TraceIdentifier); + + private static string FederationOutcomeToken(FederationActOutcome outcome) => outcome switch + { + FederationActOutcome.Applied => "applied", + FederationActOutcome.AlreadyApplied => "already_applied", + FederationActOutcome.NotFound => "not_found", + FederationActOutcome.NotOwned => "not_owned", + FederationActOutcome.LiveConnection => "live_connection", + FederationActOutcome.NotApplicable => "not_applicable", + FederationActOutcome.Refused => "refused", + FederationActOutcome.Unavailable => "unavailable", + _ => "uncertain", + }; +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index c02d699b..58ba6d94 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -69,6 +69,7 @@ internal static WebApplication MapLearnStackPlatformOperator(this WebApplication .ProducesProblem(StatusCodes.Status503ServiceUnavailable); MapOnboarding(group); MapRecovery(group); + MapFederation(group); return app; } diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index 4ea9e830..69bb9842 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -470,6 +470,59 @@ public async Task WritePlatformOperatorResultAsync( } } + /// + public async Task WritePlatformOperatorIntentAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(admission); + RefuseGlobalCapture(); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + + // The admission binds the row exactly as it binds the result row, to the attempt slug instead: only an act + // that entered the platform scope and declares a checkpoint can present one, the effect has not happened so + // the outcome is indeterminate, and the identity module's own rows are never written here. + if (!StronglyTypedId.IsAssigned(entry.TenantId) + || entry.ModuleName == "identity" + || !PlatformOperations.IsRegistered(admission.Operation) + || !admission.Operation.NeedsPlatformRole + || admission.Operation.AttemptAuditSlug is not { } attemptSlug + || !string.Equals(entry.Operation, attemptSlug, StringComparison.Ordinal) + || !string.Equals(entry.Reason, admission.Operation.ReasonSlug, StringComparison.Ordinal) + || entry.ActorUserId is not null + || entry.Outcome != AuditOutcome.Indeterminate + || entry.OperationClass != OperationClass.Must + || !string.Equals(entry.CorrelationId, admission.Operator.CorrelationId, StringComparison.Ordinal) + || !MetadataNamesAdmittedOperator(entry, admission)) + { + throw new ArgumentException( + "The platform operator intent row does not match its admission.", nameof(entry)); + } + + try + { + await using var command = connection.CreateCommand(); + command.CommandText = InsertSql; + command.Transaction = transaction; + + Bind(command.Parameters, entry); + + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbException failure) + { + throw new AuditWriteFailedException( + "The platform operator intent row could not be written, so the effect must not start.", + failure); + } + } + /// public Task WriteIdentityRebindIntentAsync( AuditEntryDraft entry, diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs index f8e29ce8..bac1e106 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs @@ -13,6 +13,10 @@ public static class FederationAdapterFactory public static IFederationProvider CreateProvider(KeycloakFederationOptions options, ISecretProvider secrets, IProviderResilience resilience) => new KeycloakFederationProvider(options, secrets, resilience); + /// The operator's adapter: the same client and routes under its own resilience pipeline (ADR-0099 Amendment 10). + public static IFederationOperator CreateOperator(KeycloakFederationOptions options, ISecretProvider secrets, + IProviderResilience resilience) => new KeycloakFederationProvider(options, secrets, resilience); + public static IFederationEgressFetcher CreateEgressFetcher(FederationEgressOptions options) => new FederationEgressFetcher(options); /// The secret key the composition root checks before selecting the real adapter. diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProfile.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProfile.cs index f2541431..0f8889c4 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProfile.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProfile.cs @@ -59,6 +59,33 @@ private static readonly (string Key, string Value)[] SamlConfiguration = internal static string OwnerMarker(FederationBrokerOwner owner) => owner.TenantId.Value.ToString("D", CultureInfo.InvariantCulture) + ":" + owner.ConnectionId.ToString("D", CultureInfo.InvariantCulture); + /// + /// The strict inverse of : exactly a lowercase tenant identifier, a colon and a lowercase + /// UUIDv7 connection identifier, whose derived alias is . Anything else, including a nil or + /// sentinel tenant, a non-v7 connection or an alias that is not the connection's, is not an owner. + /// + internal static bool TryOwnerFromMarker(string? marker, string? alias, out FederationBrokerOwner owner) + { + owner = null!; + if (marker is null || alias is null || marker.Length != 73 || marker[36] != ':' + || !Guid.TryParseExact(marker.AsSpan(0, 36), "D", out var tenant) + || !Guid.TryParseExact(marker.AsSpan(37, 36), "D", out var connection) + || !string.Equals(marker, OwnerMarker(tenant, connection), StringComparison.Ordinal)) + return false; + try + { + owner = new FederationBrokerOwner(LearnStack.SharedKernel.Identifiers.TenantId.From(tenant), connection, alias); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + private static string OwnerMarker(Guid tenant, Guid connection) => + tenant.ToString("D", CultureInfo.InvariantCulture) + ":" + connection.ToString("D", CultureInfo.InvariantCulture); + internal static string ProviderId(FederationBrokerProtocol protocol) => protocol switch { FederationBrokerProtocol.Oidc => "oidc", diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs new file mode 100644 index 00000000..bd6201ec --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs @@ -0,0 +1,274 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Infrastructure.Identity.Federation; + +/// +/// The operator half of the adapter (ADR-0099 Amendment 10): a paged listing of the realm's identity-provider +/// instances, the inspection of one alias, a remove and a marker-proven disable. It reaches the provider only through +/// , adds no realm authority to the admin client and returns closed facts and +/// outcomes: no representation, configuration value, display name, issuer or secret crosses the port. +/// +internal sealed partial class KeycloakFederationProvider +{ + // One page of full representations: a hundred instances of a few kilobytes each, with room to spare. + private const int ListLimit = 1024 * 1024; + + /// + public async Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfLessThan(limit, 1); + return await RunAsync(FederationBrokerPage.Unavailable, async (bearer, token) => + { + var response = await SendAsync( + HttpMethod.Get, KeycloakFederationRoutes.InstancePage(_options, offset, limit), null, bearer, ListLimit, token) + .ConfigureAwait(false); + if (response.Code != HttpStatusCode.OK || response.Body is null) throw Fault(); + try + { + using var document = JsonDocument.Parse(response.Body, new JsonDocumentOptions { MaxDepth = 16 }); + if (document.RootElement.ValueKind != JsonValueKind.Array) throw Fault(); + // A provider that ignored the page size answered outside the admitted shape. + if (document.RootElement.GetArrayLength() > limit) throw Fault(); + var owned = new List(); + var seen = new HashSet(StringComparer.Ordinal); + var ignored = 0; + var scanned = 0; + foreach (var item in document.RootElement.EnumerateArray()) + { + scanned++; + if (TryClassify(item, out var facts) && seen.Add(facts.Owner.Alias)) owned.Add(facts); + else ignored++; + } + + return new FederationBrokerPage(FederationOperatorStatus.Ok, owned, ignored, scanned); + } + catch (JsonException) { throw Fault(); } + finally { CryptographicOperations.ZeroMemory(response.Body); } + }, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task InspectAsync(string alias, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(alias); + return await RunAsync(FederationBrokerInspection.Unavailable, async (bearer, token) => + { + var probe = await ProbeAsync(alias, bearer, token).ConfigureAwait(false); + try + { + switch (probe.Kind) + { + case Probe.Absent: return FederationBrokerInspection.Absent; + case Probe.NotOwned: return FederationBrokerInspection.NotOwned; + } + + var mappers = 0; + if (probe.Facts!.Readable) + { + mappers = await CountMappersCoreAsync(probe.Facts.Owner, bearer, token).ConfigureAwait(false); + } + + return new FederationBrokerInspection(FederationInspectionStatus.Owned, probe.Facts, mappers); + } + finally { probe.Zero(); } + }, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + return await RunAsync(null, async (bearer, token) => + await CountMappersCoreAsync(owner, bearer, token).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + } + + /// + public async Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var sent = false; + var outcome = await RunAsync(FederationOperatorOutcome.Unavailable, async (bearer, token) => + { + var probe = await ProbeAsync(owner.Alias, bearer, token).ConfigureAwait(false); + try + { + if (probe.Kind == Probe.Absent) return FederationOperatorOutcome.AlreadyApplied; + if (probe.Kind == Probe.NotOwned || !Names(probe.Facts!.Owner, owner)) return FederationOperatorOutcome.NotOwned; + } + finally { probe.Zero(); } + + sent = true; + var deleted = await SendAsync(HttpMethod.Delete, KeycloakFederationRoutes.Instance(_options, owner), null, bearer, 0, token) + .ConfigureAwait(false); + switch (deleted.Code) + { + case HttpStatusCode.NoContent or HttpStatusCode.NotFound: + break; + case HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.Forbidden or HttpStatusCode.Unauthorized: + return FederationOperatorOutcome.Refused; + default: + throw Fault(); + } + + // The delete is confirmed by absence: an instance still there is an outcome nobody can state. + var after = await ProbeAsync(owner.Alias, bearer, token).ConfigureAwait(false); + try { return after.Kind == Probe.Absent ? FederationOperatorOutcome.Applied : FederationOperatorOutcome.Uncertain; } + finally { after.Zero(); } + }, cancellationToken).ConfigureAwait(false); + + // A fault after the delete was sent leaves its outcome unknown; before it, nothing happened. + return outcome == FederationOperatorOutcome.Unavailable && sent ? FederationOperatorOutcome.Uncertain : outcome; + } + + /// + public async Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var sent = false; + var outcome = await RunAsync(FederationOperatorOutcome.Unavailable, async (bearer, token) => + { + var probe = await ProbeAsync(owner.Alias, bearer, token).ConfigureAwait(false); + byte[] replacement; + try + { + if (probe.Kind == Probe.Absent) return FederationOperatorOutcome.Refused; + if (probe.Kind == Probe.NotOwned || !Names(probe.Facts!.Owner, owner)) return FederationOperatorOutcome.NotOwned; + if (!probe.Facts.Enabled) return FederationOperatorOutcome.AlreadyApplied; + replacement = DisabledRepresentation(probe.Body!); + } + finally { probe.Zero(); } + + try + { + using var content = new ByteArrayContent(replacement); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + sent = true; + var put = await SendAsync(HttpMethod.Put, KeycloakFederationRoutes.Instance(_options, owner), content, bearer, 0, token) + .ConfigureAwait(false); + switch (put.Code) + { + case HttpStatusCode.NoContent: + break; + case HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound or HttpStatusCode.Forbidden + or HttpStatusCode.Unauthorized: + return FederationOperatorOutcome.Refused; + default: + throw Fault(); + } + } + finally { CryptographicOperations.ZeroMemory(replacement); } + + var after = await ProbeAsync(owner.Alias, bearer, token).ConfigureAwait(false); + try + { + return after is { Kind: Probe.Owned, Facts.Enabled: false } ? FederationOperatorOutcome.Applied : FederationOperatorOutcome.Uncertain; + } + finally { after.Zero(); } + }, cancellationToken).ConfigureAwait(false); + + return outcome == FederationOperatorOutcome.Unavailable && sent ? FederationOperatorOutcome.Uncertain : outcome; + } + + /// + /// The representation the provider returned with enabled false and nothing else changed. The two members the + /// provider computes on every read are dropped, and the secret member keeps the provider's mask literal, which + /// the provider reads as "keep the stored value" (ADR-0099 Amendment 3). This is the one provider write that sends + /// back what the provider returned, which the operator disable needs for a broker the adapter cannot read. + /// + private static byte[] DisabledRepresentation(byte[] returned) + { + if (JsonNode.Parse(returned) is not JsonObject representation) throw Fault(); + representation.Remove("internalId"); + representation.Remove("types"); + representation["enabled"] = false; + return JsonSerializer.SerializeToUtf8Bytes(representation); + } + + private async Task CountMappersCoreAsync(FederationBrokerOwner owner, string bearer, CancellationToken token) + { + var mappers = await SendAsync(HttpMethod.Get, KeycloakFederationRoutes.Mappers(_options, owner), null, bearer, MapperLimit, token) + .ConfigureAwait(false); + if (mappers.Code != HttpStatusCode.OK || mappers.Body is null) throw Fault(); + try + { + using var document = JsonDocument.Parse(mappers.Body, new JsonDocumentOptions { MaxDepth = 16 }); + if (document.RootElement.ValueKind != JsonValueKind.Array) throw Fault(); + return document.RootElement.GetArrayLength(); + } + catch (JsonException) { throw Fault(); } + finally { CryptographicOperations.ZeroMemory(mappers.Body); } + } + + /// Reads one alias and classifies it by its marker; the body stays for a caller that must send it back. + private async Task ProbeAsync(string alias, string bearer, CancellationToken token) + { + var response = await SendAsync(HttpMethod.Get, KeycloakFederationRoutes.InstanceOf(_options, alias), null, bearer, InstanceLimit, token) + .ConfigureAwait(false); + if (response.Code == HttpStatusCode.NotFound) return new ProbeResult(Probe.Absent, null, null); + if (response.Code != HttpStatusCode.OK || response.Body is null) throw Fault(); + try + { + using var document = JsonDocument.Parse(response.Body, new JsonDocumentOptions { MaxDepth = 16 }); + if (!TryClassify(document.RootElement, out var facts) || !string.Equals(facts.Owner.Alias, alias, StringComparison.Ordinal)) + { + CryptographicOperations.ZeroMemory(response.Body); + return new ProbeResult(Probe.NotOwned, null, null); + } + + return new ProbeResult(Probe.Owned, facts, response.Body); + } + catch (JsonException) + { + CryptographicOperations.ZeroMemory(response.Body); + throw Fault(); + } + } + + /// + /// Whether one representation is an instance LearnStack owns: the alias is the derived form, the marker parses + /// strictly to a tenant and a connection whose derived alias it is, and the owner is then read for shape and profile. + /// Everything else is ignored: an unmarked, foreign or marker-mismatched instance is never reported or touched. + /// + private static bool TryClassify(JsonElement item, out FederationBrokerFacts facts) + { + facts = null!; + if (item.ValueKind != JsonValueKind.Object || !item.TryGetProperty("alias", out var aliasElement) + || aliasElement.ValueKind != JsonValueKind.String || aliasElement.GetString() is not { Length: 36 } alias + || !alias.StartsWith(FederationBrokerOwner.AliasPrefix, StringComparison.Ordinal) + || !item.TryGetProperty("config", out var config) || config.ValueKind != JsonValueKind.Object + || !config.TryGetProperty(KeycloakFederationProfile.OwnerKey, out var marker) || marker.ValueKind != JsonValueKind.String + || !KeycloakFederationProfile.TryOwnerFromMarker(marker.GetString(), alias, out var owner)) + return false; + if (KeycloakFederationProfile.Read(item, owner) is { } read) + { + facts = new FederationBrokerFacts(owner, Readable: true, read.Conforms, read.State.Enabled, read.State.Protocol); + return true; + } + + // Unreadable: the marker is the only proof. Anything but an explicit false counts as enabled, because the + // operator's step is to switch an offered sign-in option off. + var enabled = !(item.TryGetProperty("enabled", out var flag) && flag.ValueKind == JsonValueKind.False); + facts = new FederationBrokerFacts(owner, Readable: false, Conforms: false, enabled, Protocol: null); + return true; + } + + private static bool Names(FederationBrokerOwner found, FederationBrokerOwner expected) => + found.TenantId == expected.TenantId && found.ConnectionId == expected.ConnectionId + && string.Equals(found.Alias, expected.Alias, StringComparison.Ordinal); + + private enum Probe { Absent, NotOwned, Owned } + + private readonly record struct ProbeResult(Probe Kind, FederationBrokerFacts? Facts, byte[]? Body) + { + internal void Zero() + { + if (Body is not null) CryptographicOperations.ZeroMemory(Body); + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs index 3b3cdd34..450d82c1 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs @@ -16,10 +16,12 @@ namespace LearnStack.Infrastructure.Identity.Federation; /// client-credentials token per operation, and calls only : create for an absent /// owned alias, read, full-state replace and delete of that alias, and its mapper list. Every read or write first proves /// the provider object's owner marker names this tenant and connection; a foreign or unreadable object is never touched. +/// The same class implements the operator port (ADR-0099 Amendment 10): one instance serves the tenant runner and +/// another, built with its own resilience pipeline, serves the operator, so a sweep cannot starve a tenant's calls. /// The client secret is written, never read back, and never returned. Provider responses, messages and exceptions stay /// inside this namespace: the port sees closed statuses only. /// -internal sealed class KeycloakFederationProvider : IFederationProvider, IDisposable +internal sealed partial class KeycloakFederationProvider : IFederationProvider, IFederationOperator, IDisposable { internal const string SecretKey = "Federation:ClientSecret"; private const int TokenLimit = 16 * 1024; @@ -29,7 +31,7 @@ internal sealed class KeycloakFederationProvider : IFederationProvider, IDisposa private readonly KeycloakFederationOptions _options; private readonly ISecretProvider _secrets; - private readonly IProviderResilience _resilience; + private readonly ResiliencePipeline _pipeline; private readonly HttpClient _client; internal KeycloakFederationProvider(KeycloakFederationOptions options, ISecretProvider secrets, IProviderResilience resilience) @@ -38,10 +40,22 @@ internal KeycloakFederationProvider(KeycloakFederationOptions options, ISecretPr /// Controlled transports are a test seam, never a certificate bypass: a supplied sockets handler is hardened. internal KeycloakFederationProvider(KeycloakFederationOptions options, ISecretProvider secrets, IProviderResilience resilience, HttpMessageHandler handler) + : this(options, secrets, (resilience ?? throw new ArgumentNullException(nameof(resilience))).Pipeline, handler) { } + + /// The operator's adapter: the same client and routes under its own bulkhead and breaker. + internal KeycloakFederationProvider(KeycloakFederationOptions options, ISecretProvider secrets, IProviderResilience resilience) + : this(options, secrets, resilience, new SocketsHttpHandler()) { } + + internal KeycloakFederationProvider(KeycloakFederationOptions options, ISecretProvider secrets, IProviderResilience resilience, + HttpMessageHandler handler) + : this(options, secrets, (resilience ?? throw new ArgumentNullException(nameof(resilience))).Pipeline, handler) { } + + private KeycloakFederationProvider(KeycloakFederationOptions options, ISecretProvider secrets, ResiliencePipeline pipeline, + HttpMessageHandler handler) { _options = options ?? throw new ArgumentNullException(nameof(options)); _secrets = secrets ?? throw new ArgumentNullException(nameof(secrets)); - _resilience = resilience ?? throw new ArgumentNullException(nameof(resilience)); + _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); ArgumentNullException.ThrowIfNull(handler); if (handler is SocketsHttpHandler sockets) { @@ -176,7 +190,7 @@ private async Task RunAsync(T unavailable, Func + return await _pipeline.ExecuteAsync(async token => { var bearer = await TokenAsync(secret!, token).ConfigureAwait(false); return await operation(bearer, token).ConfigureAwait(false); diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationRoutes.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationRoutes.cs index 3ccd5264..37aa774b 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationRoutes.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationRoutes.cs @@ -4,9 +4,10 @@ namespace LearnStack.Infrastructure.Identity.Federation; /// /// The complete set of provider routes the federation adapter may build (ADR-0099 § Ownership and the confined adapter): -/// the realm token endpoint for the admin client's credentials, the identity-provider collection (create only), one owned -/// instance by its derived alias, and that instance's mapper list. No other alias, user, flow, realm, client or -/// required-action route exists here, and no import route with a remote URL. Every route is relative to the configured +/// the realm token endpoint for the admin client's credentials, the identity-provider collection (create, and for the +/// operator one bounded page of the listing), one owned instance by its derived alias, and that instance's mapper list. +/// No other alias, user, flow, realm, client or required-action route exists here, and no import route with a remote +/// URL. Every route is relative to the configured /// realm; an alias comes only from , which admits the derived form alone. /// internal static class KeycloakFederationRoutes @@ -18,9 +19,23 @@ internal static class KeycloakFederationRoutes internal static Uri Instances(KeycloakFederationOptions options) => new(options.AdminRealm, "identity-provider/instances"); + /// One bounded page of the realm's identity-provider instances, in full representation (ADR-0099 Amendment 10). + internal static Uri InstancePage(KeycloakFederationOptions options, int first, int max) + { + if (first < 0 || max < 1) + throw new ArgumentOutOfRangeException(nameof(first), "A page is a non-negative offset and a positive size."); + // The collection route of create, with the one query the listing admits and no other member. + return new(Instances(options), "?first=" + first.ToString(System.Globalization.CultureInfo.InvariantCulture) + + "&max=" + max.ToString(System.Globalization.CultureInfo.InvariantCulture) + "&briefRepresentation=false"); + } + internal static Uri Instance(KeycloakFederationOptions options, FederationBrokerOwner owner) => new(options.AdminRealm, "identity-provider/instances/" + Alias(owner)); + /// One instance by an alias of the derived form: the operator reads it before it knows whose it is. + internal static Uri InstanceOf(KeycloakFederationOptions options, string alias) => + new(options.AdminRealm, "identity-provider/instances/" + DerivedAlias(alias)); + internal static Uri Mappers(KeycloakFederationOptions options, FederationBrokerOwner owner) => new(options.AdminRealm, "identity-provider/instances/" + Alias(owner) + "/mappers"); @@ -28,10 +43,15 @@ private static string Alias(FederationBrokerOwner owner) { ArgumentNullException.ThrowIfNull(owner); // The owner type already refuses anything but lsf- and 32 lowercase hex characters; repeat it at the route. - if (owner.Alias.Length != 36 || !owner.Alias.StartsWith(FederationBrokerOwner.AliasPrefix, StringComparison.Ordinal) - || !owner.Alias.AsSpan(4).ContainsOnlyHexLower()) - throw new ArgumentException("Federation alias is not a derived alias.", nameof(owner)); - return owner.Alias; + return DerivedAlias(owner.Alias); + } + + private static string DerivedAlias(string alias) + { + if (alias is null || alias.Length != 36 || !alias.StartsWith(FederationBrokerOwner.AliasPrefix, StringComparison.Ordinal) + || !alias.AsSpan(4).ContainsOnlyHexLower()) + throw new ArgumentException("Federation alias is not a derived alias.", nameof(alias)); + return alias; } private static bool ContainsOnlyHexLower(this ReadOnlySpan value) diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index 8fc55f44..4137572b 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -148,6 +148,7 @@ public async Task EnterAsync( // not enter a cross-tenant scope unrecorded. var declaredEntry = Declared(EnterOperation); var declaredResult = Declared(admission.Operation.AuditSlug); + var declaredIntent = admission.Operation.AttemptAuditSlug is { } attemptSlug ? Declared(attemptSlug) : null; // 2. The credential. Opening through the guarded facade here is where an absent // ConnectionStrings:PlatformAdmin surfaces — on entry, at the first call, with @@ -184,11 +185,13 @@ public async Task EnterAsync( entry.Id.Value, null); - var current = transaction; return new Handle( connection, - current, - (result, token) => WriteResultAsync(admission, declaredResult, result, connection, current, token), + transaction, + (result, current, token) => WriteResultAsync(admission, declaredResult, result, connection, current, token), + declaredIntent is null + ? null + : (result, current, token) => WriteIntentAsync(admission, declaredIntent, result, connection, current, token), () => PlatformOperatorMetrics.Result(admission.Operation), _logger); } @@ -257,6 +260,37 @@ private async Task WriteResultAsync( NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) + { + var draft = ComposeOperatorRow(admission, declared, result, AuditOutcome.Success); + + await using var services = _scopeFactory.CreateAsyncScope(); + await services.ServiceProvider + .GetRequiredService() + .WritePlatformOperatorResultAsync(draft, admission, connection, transaction, cancellationToken); + } + + /// + /// Writes the act's MUST intent row on the work transaction, through the witness-bound method; the handle + /// commits it before the effect starts (ADR-0099 Amendment 11). + /// + private async Task WriteIntentAsync( + PlatformAdmission admission, + AuditCatalogEntry declared, + PlatformResult intent, + NpgsqlConnection connection, + NpgsqlTransaction transaction, + CancellationToken cancellationToken) + { + var draft = ComposeOperatorRow(admission, declared, intent, AuditOutcome.Indeterminate); + + await using var services = _scopeFactory.CreateAsyncScope(); + await services.ServiceProvider + .GetRequiredService() + .WritePlatformOperatorIntentAsync(draft, admission, connection, transaction, cancellationToken); + } + + private AuditEntryDraft ComposeOperatorRow( + PlatformAdmission admission, AuditCatalogEntry declared, PlatformResult result, AuditOutcome outcome) { ArgumentNullException.ThrowIfNull(result); if (!StronglyTypedId.IsAssigned(result.TenantId)) @@ -271,7 +305,7 @@ private async Task WriteResultAsync( // The ticket stays out of a row a tenant can read: it appears only under the sentinel. var isSentinel = result.TenantId == TenantId.PlatformSentinel; - var draft = new AuditEntryDraft + return new AuditEntryDraft { Id = AuditEntryId.From(_guidFactory.NewUuidV7()), TenantId = result.TenantId, @@ -284,7 +318,7 @@ private async Task WriteResultAsync( OperationClass = declared.OperationClass, EntityType = result.EntityType ?? declared.EntityType?.Name, EntityId = result.EntityId, - Outcome = AuditOutcome.Success, + Outcome = outcome, ErrorKey = null, Reason = admission.Operation.ReasonSlug, BeforeState = result.BeforeState, @@ -296,11 +330,6 @@ private async Task WriteResultAsync( Timestamp = _clock.UtcNow, Metadata = OperatorMetadata(admission, includeTicket: isSentinel, provenance: null), }; - - await using var services = _scopeFactory.CreateAsyncScope(); - await services.ServiceProvider - .GetRequiredService() - .WritePlatformOperatorResultAsync(draft, admission, connection, transaction, cancellationToken); } private const int MaximumStateBytes = 32 * 1024; @@ -442,17 +471,22 @@ private static string ShortPath(string? path) /// private sealed class Handle( NpgsqlConnection connection, - NpgsqlTransaction transaction, - Func writeResult, + NpgsqlTransaction firstTransaction, + Func writeResult, + Func? writeIntent, Action onCommitted, ILogger logger) : IPlatformAdminScopeHandle { private static readonly string[] StatementVerbs = ["SELECT", "INSERT", "UPDATE", "DELETE", "WITH"]; + // Replaced once, at the intent checkpoint: the first transaction commits the intent row alone, and the work + // that follows runs in a fresh one on the same connection. + private NpgsqlTransaction _transaction = firstTransaction; private bool _resolved; private bool _disposed; private bool _faulted; + private bool _intentWritten; private bool _resultWritten; public async Task ExecuteAsync( @@ -500,12 +534,70 @@ public async Task> QueryAsync( } } + public async Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) + { + EnsureUsable(); + if (writeIntent is null) + { + throw new InvalidOperationException("This operation declares no intent checkpoint."); + } + + if (_intentWritten || _resultWritten) + { + throw new InvalidOperationException( + "An intent row is written once, before the result row."); + } + + try + { + await writeIntent(intent, _transaction, cancellationToken); + } + catch (Exception failure) when (failure is not ArgumentException) + { + _faulted = true; + throw; + } + + try + { + // The row commits alone and before the effect: an effect that later fails, or a process that dies, + // leaves it standing. A commit whose outcome is unknown stops the act all the same, because the + // effect must not start on an intent nobody can prove was recorded. + await _transaction.CommitAsync(cancellationToken); + } + catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) + { + _faulted = true; + throw new AuditWriteFailedException( + "The platform operator intent row could not be committed, so the effect must not start.", failure); + } + + try + { + await _transaction.DisposeAsync(); + _transaction = await connection.BeginTransactionAsync(cancellationToken); + } + catch + { + _faulted = true; + throw; + } + + _intentWritten = true; + } + public async Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) { EnsureUsable(); + if (writeIntent is not null && !_intentWritten) + { + throw new InvalidOperationException( + "An operation with an intent checkpoint writes its intent row before its result row."); + } + try { - await writeResult(result, cancellationToken); + await writeResult(result, _transaction, cancellationToken); } catch (Exception failure) when (failure is not ArgumentException) { @@ -529,7 +621,7 @@ public async Task CommitAsync(CancellationToken cancellationToken = default) } _resolved = true; - await transaction.CommitAsync(cancellationToken); + await _transaction.CommitAsync(cancellationToken); onCommitted(); // The connection closes at completion, not at disposal: nothing may run on a @@ -550,7 +642,7 @@ public async ValueTask DisposeAsync() { try { - await transaction.RollbackAsync(); + await _transaction.RollbackAsync(); } catch (Exception failure) when (failure is InvalidOperationException or NpgsqlException) { @@ -574,7 +666,7 @@ private async ValueTask CloseAsync() _disposed = true; try { - await transaction.DisposeAsync(); + await _transaction.DisposeAsync(); } finally { @@ -585,7 +677,7 @@ private async ValueTask CloseAsync() private NpgsqlCommand Build(string sql, IReadOnlyList? parameters) { RequireOneStatement(sql); - var command = new NpgsqlCommand(sql, connection, transaction); + var command = new NpgsqlCommand(sql, connection, _transaction); if (parameters is not null) { foreach (var parameter in parameters) diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index c11551d2..fd29ad29 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -32,6 +32,9 @@ public static class PlatformOperatorMetrics /// Recovery transitions by operation and outcome (ADR-0103 § 10). public const string RecoveryCounterName = "learnstack_platform_operator_recoveries_total"; + /// Federation operator calls by operation and outcome (ADR-0099 Amendment 10). + public const string FederationCounterName = "learnstack_platform_operator_federation_total"; + /// Issuer metadata or key fetches that failed or were refused (no label). public const string MetadataFailureCounterName = "learnstack_platform_operator_metadata_failures_total"; @@ -52,6 +55,9 @@ public static class PlatformOperatorMetrics private static readonly Counter Recoveries = Meter.CreateCounter(RecoveryCounterName, description: "Operator recovery transitions by operation and outcome."); + private static readonly Counter FederationCalls = + Meter.CreateCounter(FederationCounterName, description: "Operator federation calls by operation and outcome."); + private static readonly Counter AuditFailures = Meter.CreateCounter(AuditFailureCounterName, description: "Operator acts refused because the MUST row was not durable."); @@ -126,6 +132,15 @@ public static void RecoveryUnavailable(PlatformOperation operation, bool commitO Recoveries.Add(1, new KeyValuePair("operation", operation.AuditSlug), new KeyValuePair("outcome", commitOutcomeUnknown ? "commit_unknown" : "unavailable")); + /// + /// Counts one federation call by how it ended: a report's ok, invalid_cursor or unavailable, or an + /// act's applied, already_applied, not_found, not_owned, live_connection, + /// not_applicable, refused, unavailable or uncertain. + /// + public static void Federation(PlatformOperation operation, string outcome) => + FederationCalls.Add(1, new KeyValuePair("operation", operation.AuditSlug), + new KeyValuePair("outcome", outcome)); + /// Counts an act that was refused because its MUST row could not be written. public static void AuditFailed(PlatformOperation operation) => AuditFailures.Add(1, new KeyValuePair("operation", operation.AuditSlug)); diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index 30401e47..68e78fd4 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -5,7 +5,7 @@ namespace LearnStack.SharedKernel.Audit; /// -/// The only sanctioned way to put a row in audit_log. Fourteen writes, and +/// The only sanctioned way to put a row in audit_log. Fifteen writes, and /// no update. /// /// @@ -170,6 +170,30 @@ Task WritePlatformOperatorResultAsync( CancellationToken cancellationToken = default) => throw new InvalidOperationException("This audit store cannot write a platform operator result."); + /// + /// Writes the intent row of a platform-scope act whose effect lies outside the database, on the scope's work + /// transaction at its checkpoint, which the scope then commits before the effect (ADR-0099 Amendment 11). + /// + /// + /// + /// Bound like to the admission, with three differences: the + /// operation is the admitted operation's , which only an act with + /// a checkpoint has, the outcome is indeterminate because the effect has not happened, and the act's + /// completion row is the result row that follows. The scope is the only caller. + /// + /// + /// A tenant-readable row carries no ticket, as for the result row. A refused draft or a failed write requires + /// the caller not to start the effect. + /// + /// + Task WritePlatformOperatorIntentAsync( + AuditEntryDraft entry, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) => + throw new NotSupportedException("This audit store cannot write a platform operator intent."); + /// /// Writes the controlled issuer rebind's intent row on the offline tool's own short transaction, before the /// rebind's main transaction begins (ADR-0104 § 8). diff --git a/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs new file mode 100644 index 00000000..90bd0c0e --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs @@ -0,0 +1,144 @@ +namespace LearnStack.SharedKernel.Identity; + +/// +/// What the provider shows about one broker whose owner marker names a tenant and a connection: nonsecret facts only, +/// never a configuration value, display name, issuer or secret (ADR-0099 Amendment 10). +/// +/// The tenant and connection the marker names, with the alias derived from the connection. +/// False when the representation cannot be read as the protocol's admitted shape. +/// True when a readable broker's members and configuration equal the fixed profile exactly. +/// Whether the provider offers the broker as a sign-in option. +/// The brokered protocol of a readable broker; null when it is not readable. +public sealed record FederationBrokerFacts( + FederationBrokerOwner Owner, bool Readable, bool Conforms, bool Enabled, FederationBrokerProtocol? Protocol) +{ + public override string ToString() => nameof(FederationBrokerFacts); +} + +/// How a listing or an inspection ended at the provider. +public enum FederationOperatorStatus +{ + /// The provider answered. + Ok = 1, + + /// The provider could not be reached or answered outside the admitted shape; nothing is known. + Unavailable = 2, +} + +/// +/// One page of the realm's identity-provider instances, classified by marker and shape. +/// +/// Whether the provider answered. +/// The brokers whose marker parses to an owner whose alias is the derived one. +/// The count of listed instances with no marker, a foreign marker or an alias that is not LearnStack's. +/// How many instances the provider returned, which the caller adds to the offset. +public sealed record FederationBrokerPage( + FederationOperatorStatus Status, IReadOnlyList Owned, int Ignored, int Scanned) +{ + /// The page of a provider that could not answer. + public static FederationBrokerPage Unavailable { get; } = new(FederationOperatorStatus.Unavailable, [], 0, 0); + + public override string ToString() => nameof(FederationBrokerPage); +} + +/// What one alias is at the provider. +public enum FederationInspectionStatus +{ + /// No instance has the alias. + Absent = 1, + + /// An instance has the alias and its marker does not name a tenant and connection of LearnStack's. + NotOwned = 2, + + /// The marker names a tenant and a connection, and the alias is the connection's derived one. + Owned = 3, + + /// The provider could not be reached or answered outside the admitted shape. + Unavailable = 4, +} + +/// The inspection of one alias, with the mapper count of an owned readable broker. +/// What the alias is. +/// The facts of an owned broker; null otherwise. +/// The mappers on an owned readable broker; zero otherwise. +public sealed record FederationBrokerInspection(FederationInspectionStatus Status, FederationBrokerFacts? Facts, int MapperCount) +{ + public static FederationBrokerInspection Unavailable { get; } = new(FederationInspectionStatus.Unavailable, null, 0); + + public static FederationBrokerInspection Absent { get; } = new(FederationInspectionStatus.Absent, null, 0); + + public static FederationBrokerInspection NotOwned { get; } = new(FederationInspectionStatus.NotOwned, null, 0); + + public override string ToString() => nameof(FederationBrokerInspection); +} + +/// How an operator remove or disable ended; no raw response crosses the port. +public enum FederationOperatorOutcome +{ + /// The provider's change was made and, for a remove, confirmed. + Applied = 1, + + /// The broker was already absent or already disabled; nothing was sent. + AlreadyApplied, + + /// The provider definitively refused the change; nothing changed. + Refused, + + /// The instance's marker does not name the owner the caller proved; nothing was touched. + NotOwned, + + /// The provider could not be reached before any change was sent; nothing changed. + Unavailable, + + /// A change was sent and its outcome is unknown: the next report shows the broker present or gone. + Uncertain, +} + +/// +/// ADR-0099 Amendment 10's operator port, beside the tenant provider port and never the tenant runner's: +/// a paged listing of the realm's identity-provider instances, an inspection of one alias, a remove and a +/// marker-proven disable. It holds the same admin client and adds no realm authority. Only the operator service and +/// the Infrastructure adapter hold it. +/// +public interface IFederationOperator +{ + /// Lists one page of the realm's instances in the provider's order, from . + Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default); + + /// Reads one alias: whether it is absent, foreign to LearnStack or owned, and its nonsecret facts. + Task InspectAsync(string alias, CancellationToken cancellationToken = default); + + /// Counts the mappers on an owned readable broker; null when the provider could not answer. + Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default); + + /// + /// Deletes the instance after proving its marker names this owner, whether or not it can be read, and confirms + /// that it is gone. The provider deletes the federated links with it. + /// + Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default); + + /// + /// Sets enabled to false at the provider only, after proving the marker: the one provider write that sends + /// back the representation the provider returned, with nothing else changed. + /// + Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default); +} + +/// The fail-closed default while the federation admin client is not configured: nothing is sent. +public sealed class UnconfiguredFederationOperator : IFederationOperator +{ + public Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default) => + Task.FromResult(FederationBrokerPage.Unavailable); + + public Task InspectAsync(string alias, CancellationToken cancellationToken = default) => + Task.FromResult(FederationBrokerInspection.Unavailable); + + public Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => + Task.FromResult(null); + + public Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => + Task.FromResult(FederationOperatorOutcome.Unavailable); + + public Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => + Task.FromResult(FederationOperatorOutcome.Unavailable); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs new file mode 100644 index 00000000..775e2d3a --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs @@ -0,0 +1,100 @@ +namespace LearnStack.SharedKernel.Platform; + +/// One broker that needs an operator's attention: its identity, why, and what the provider shows. +/// The derived alias, which is LearnStack's and no tenant's text. +/// The tenant the owner marker names. +/// The connection the owner marker names. +/// Any of orphan, unreadable_owned and nonconforming; never empty. +/// +/// absent when no row names the connection, deleted for a tombstone, otherwise the live row's lifecycle state. +/// +/// oidc or saml for a readable broker, null otherwise. +/// Whether the provider offers the broker as a sign-in option. +/// The mappers on a readable broker with a live row; null when it was not asked or could not be read. +public sealed record FederationBrokerReportItem( + string Alias, Guid TenantId, Guid ConnectionId, IReadOnlyList Classes, string RowState, string? Protocol, + bool Enabled, int? Mappers); + +/// How a report page ended. +public enum FederationReportOutcome +{ + /// The page was read. + Ok = 1, + + /// The cursor is not one this operation issued; nothing was entered. + InvalidCursor, + + /// The provider could not answer, so nothing is reported. + Unavailable, +} + +/// One page of the report. +/// How it ended. +/// The brokers on the page that have at least one class, in the provider's order. +/// The opaque position of the next page, or null after the last. +/// How many instances the provider returned for the page. +/// How many of them are not LearnStack's: no marker, a foreign marker or a marker that does not match its row. +public sealed record FederationReportResult( + FederationReportOutcome Outcome, IReadOnlyList Items, string? NextCursor, int Scanned, int Ignored) +{ + public static FederationReportResult Of(FederationReportOutcome outcome) => new(outcome, [], null, 0, 0); +} + +/// How a remove or a disable ended. +public enum FederationActOutcome +{ + /// The provider's change was made and confirmed; the account review is owed. + Applied = 1, + + /// The broker was already absent (remove) or already disabled (disable); nothing was sent and no tenant row was written. + AlreadyApplied, + + /// A disable named an alias no instance has. + NotFound, + + /// The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. + NotOwned, + + /// A live connection row names the broker, so a remove refuses; the tenant's own Delete retires it. + LiveConnection, + + /// A disable found a healthy owned broker with a live row: nothing about it needs an operator. + NotApplicable, + + /// The provider definitively refused the change; nothing changed. + Refused, + + /// The provider could not be reached before any change was sent; nothing changed. + Unavailable, + + /// A change was sent and its outcome is unknown: the next report shows the broker present or gone. + Uncertain, +} + +/// The end of an operator remove or disable. +/// How it ended. +/// The tenant the marker names, when an owned broker was found. +/// The connection the marker names, when an owned broker was found. +public sealed record FederationActResult(FederationActOutcome Outcome, Guid? TenantId = null, Guid? ConnectionId = null); + +/// +/// The confined owner of the operator's federation report, remove and disable (ADR-0099 Amendment 10 and 11): it +/// consumes the operator's admission in the platform scope, reads the provider through +/// and the connection rows through the scope's +/// column grants, and writes an intent row and a completion row under the real tenant for each act. +/// +public interface IFederationBrokerOperations +{ + /// Reports one page of the brokers that are orphaned, unreadable or nonconforming; the realm is read first, then the rows. + /// The scope's entry row could not be written; nothing was read. + Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default); + + /// Removes an orphaned or unreadable owned broker after an intent row, and records the completion. + /// A MUST row could not be written; the effect did not start or its outcome is recorded by the intent row alone. + Task RemoveAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default); + + /// Disables a nonconforming or unreachable owned broker at the provider only, with the same two rows. + /// A MUST row could not be written; the effect did not start or its outcome is recorded by the intent row alone. + Task DisableAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index dfff9e11..d3c22b2f 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -54,8 +54,10 @@ internal PlatformOperation( public string AuditSlug { get; } /// - /// The audit slug of the intent row written before the act's own transaction, or null when the act writes - /// no such row. Only an act that runs outside the request pipeline has one (ADR-0104 § 8). + /// The audit slug of the intent row written before the act's effect, or null when the act writes no such row. + /// Only an act that runs outside the request pipeline has one: the rebind tool writes it on its own role + /// (ADR-0104 § 8) and a platform-scope act with an effect outside the database writes it at the scope handle's + /// checkpoint (ADR-0099 Amendment 11). /// public string? AttemptAuditSlug { get; } @@ -132,11 +134,36 @@ public static class PlatformOperations "platform.delivery.reset", "delivery_reset", PlatformPermissions.DeliveryWrite, PlatformOperationExecutor.RecoveryOwner); + /// + /// Report the realm's identity-provider brokers by class, orphans first: read-only in the platform scope, audited + /// by the scope's entry row (ADR-0099 Amendment 10 item 2). + /// + public static PlatformOperation FederationReport { get; } = new( + "platform.federation.report", "federation_report", PlatformPermissions.FederationRead, + PlatformOperationExecutor.PlatformScope); + + /// + /// Remove an orphaned or unreadable owned broker at the provider: an intent row at the scope handle's + /// checkpoint, the provider call, and a completion row (ADR-0099 Amendment 10 item 3). + /// + public static PlatformOperation FederationRemove { get; } = new( + "platform.federation.remove", "federation_remove", PlatformPermissions.FederationAdmin, + PlatformOperationExecutor.PlatformScope, attemptAuditSlug: "platform.federation.remove_attempt"); + + /// + /// Disable a nonconforming or unreachable owned broker at the provider only, with the same two rows + /// (ADR-0099 Amendment 10 item 4). + /// + public static PlatformOperation FederationDisable { get; } = new( + "platform.federation.disable", "federation_disable", PlatformPermissions.FederationAdmin, + PlatformOperationExecutor.PlatformScope, attemptAuditSlug: "platform.federation.disable_attempt"); + /// Every registered operation. public static IReadOnlyList All { get; } = [ KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover, - IdentityAuthorityRebind, DeliveryInspect, DeliveryReplay, DeliveryReset, + IdentityAuthorityRebind, DeliveryInspect, DeliveryReplay, DeliveryReset, FederationReport, FederationRemove, + FederationDisable, ]; /// Whether is one of the registered instances. diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs index 6174fc6d..da68b006 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -44,9 +44,20 @@ public static class PlatformPermissions public static PermissionDefinition DeliveryWrite { get; } = new(PermissionScope.Platform, "platform.delivery.write"); + /// Report the identity-provider brokers a tenant's federation left orphaned or unreadable (ADR-0099 Amendment 10). + public static PermissionDefinition FederationRead { get; } = + new(PermissionScope.Platform, "platform.federation.read"); + + /// Remove an orphaned or unreadable owned broker and disable a nonconforming one (ADR-0099 Amendment 10). + public static PermissionDefinition FederationAdmin { get; } = + new(PermissionScope.Platform, "platform.federation.admin"); + /// Every registered Platform permission. public static IReadOnlyList All { get; } = - [KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin, DeliveryRead, DeliveryWrite]; + [ + KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin, DeliveryRead, DeliveryWrite, + FederationRead, FederationAdmin, + ]; /// Finds a registered Platform permission by its key. public static bool TryGet(string? key, out PermissionDefinition definition) diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs index 3c4461e4..923942b7 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs @@ -70,10 +70,12 @@ public sealed record PlatformResult( /// The work one scope entry allows: a transaction on the platform role, as a facade. /// /// -/// One scope, one transaction, one commit. After or disposal -/// the handle refuses every call and the underlying connection is closed, so nothing a +/// One scope, one commit, and at most one checkpoint. After or +/// disposal the handle refuses every call and the underlying connection is closed, so nothing a /// caller captured can run an autocommit statement on a connection that sees every tenant. -/// Disposing without committing rolls back. +/// Disposing without committing rolls back. An act whose effect lies outside the database writes its +/// intent row at , which commits the work so far and continues in a fresh +/// transaction on the same connection; the completion row and end the scope. /// public interface IPlatformAdminScopeHandle : IAsyncDisposable { @@ -88,6 +90,17 @@ Task> QueryAsync( Func map, CancellationToken cancellationToken = default); + /// + /// Writes the act's MUST intent row, commits it, and continues the scope in a fresh work transaction + /// (ADR-0099 Amendment 11). Only an operation that declares an attempt slug has one, it is written once and + /// before the result row, and nothing after it is rolled back with the effect it announces: a failure here means + /// the effect must not start, and an effect that fails afterwards leaves this row standing. + /// + /// + /// The row could not be written or committed, so the effect must not start. + /// + Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default); + /// /// Writes the act's MUST result row on the work transaction, so it commits with the /// state change or not at all. diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs index ed675559..d431a42e 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs @@ -59,6 +59,8 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.TryAddScoped(); services.TryAddSingleton(FederationOperationBudgets.Default); services.TryAddSingleton(); + // The operator's port (Amendment 10) is its own: the tenant runner never holds it, and it too fails closed. + services.TryAddSingleton(); services.TryAddSingleton(); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetFederationConnectionQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipProfileQuery))); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs new file mode 100644 index 00000000..d86c470b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs @@ -0,0 +1,360 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.Federation; + +/// +/// The confined owner of the operator's federation report, remove and disable (ADR-0099 Amendment 10 and 11). It holds +/// the platform scope and the operator port and nothing of the tenant runner, so the rule that the tenant's provider +/// port is held only by the runner stands. +/// +/// +/// +/// The realm is read first, the rows second. A tenant writes its connection row before it creates the broker, so +/// a broker the realm listed already had a committed row when the row query runs; reading the rows first would call +/// a broker created in between an orphan. The scope is entered before either read, so the admission is spent fresh and +/// the entry row records the attempt even when the provider is down. +/// +/// +/// An act has two rows. The intent row is written at the scope handle's checkpoint and committed before the +/// provider call; the completion row records how the call ended and commits at the end. A crash between them leaves the +/// intent alone, which the next report resolves by showing the broker present or gone. A no-op (an absent broker on a +/// remove, a disabled broker on a disable) and a refusal before the intent write no tenant row: the entry row records +/// the call, and no tenant is known from nothing. +/// +/// +/// The rows name the marker's tenant, never the platform sentinel, even when no tenants row exists for it. +/// They carry closed tokens only: no display name, issuer, configuration or secret, and no ticket, because a tenant can +/// read them. +/// +/// +public sealed class FederationBrokerOperations(IPlatformAdminScope scope, IFederationOperator provider) : IFederationBrokerOperations +{ + private const int MaximumLimit = CursorPagination.MaxLimit; + private const string EntityType = "FederationConnection"; + private const string RowQuery = "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; + private static readonly TimeSpan ReportDeadline = TimeSpan.FromSeconds(10); + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + /// + public async Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.FederationReport); + var offset = 0; + if (cursor is not null && !TryDecode(cursor, out offset)) + { + return FederationReportResult.Of(FederationReportOutcome.InvalidCursor); + } + + var size = Math.Clamp(limit, 1, MaximumLimit); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(ReportDeadline); + + // 1. The realm, before any row. + FederationBrokerPage page; + try + { + page = await provider.ListAsync(offset, size, deadline.Token); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return FederationReportResult.Of(FederationReportOutcome.Unavailable); + } + + if (page.Status != FederationOperatorStatus.Ok) + { + return FederationReportResult.Of(FederationReportOutcome.Unavailable); + } + + // 2. The rows, strictly later, by primary key and through the four granted columns only. + var rows = await ReadRowsAsync(handle, page.Owned.Select(facts => facts.Owner.ConnectionId).Distinct().ToArray(), cancellationToken); + var ignored = page.Ignored; + var candidates = new List<(FederationBrokerFacts Facts, Row? Row)>(); + foreach (var facts in page.Owned) + { + rows.TryGetValue(facts.Owner.ConnectionId, out var row); + if (row is not null && row.TenantId != facts.Owner.TenantId.Value) + { + // The marker and the row disagree about whose it is: never reported, never touched. + ignored++; + continue; + } + + candidates.Add((facts, row)); + } + + // 3. The mappers of what looks healthy, bounded, because an extra mapper is drift only a mapper read shows. + var mappers = await CountMappersAsync( + candidates.Where(item => IsLive(item.Row) && item.Facts is { Readable: true, Conforms: true }) + .Select(item => item.Facts.Owner).ToList(), + deadline.Token, cancellationToken); + + var items = new List(); + foreach (var (facts, row) in candidates) + { + mappers.TryGetValue(facts.Owner.Alias, out var count); + var classes = ClassesOf(facts, row, count ?? 0); + if (classes.Count == 0) + { + continue; + } + + items.Add(new FederationBrokerReportItem( + facts.Owner.Alias, facts.Owner.TenantId.Value, facts.Owner.ConnectionId, classes, RowState(row), + facts.Protocol is { } protocol ? protocol.ToString().ToLowerInvariant() : null, facts.Enabled, count)); + } + + var next = page.Scanned == size ? Encode(offset + page.Scanned) : null; + return new FederationReportResult(FederationReportOutcome.Ok, items, next, page.Scanned, ignored); + } + + /// + public async Task RemoveAsync( + PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.FederationRemove); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var inspection = await provider.InspectAsync(alias, cancellationToken); + switch (inspection.Status) + { + case FederationInspectionStatus.Unavailable: + return new FederationActResult(FederationActOutcome.Unavailable); + case FederationInspectionStatus.Absent: + // Deleting an absent broker is applied, and no tenant is known from nothing: no tenant row. + return new FederationActResult(FederationActOutcome.AlreadyApplied); + case FederationInspectionStatus.NotOwned: + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var facts = inspection.Facts!; + var owner = facts.Owner; + var row = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + if (row is not null && row.TenantId != owner.TenantId.Value) + { + return new FederationActResult(FederationActOutcome.NotOwned); + } + + if (IsLive(row)) + { + // Amendment 10 item 3: a live row refuses, for both classes. The tenant's own Delete retires it. + return Known(FederationActOutcome.LiveConnection, owner); + } + + var classes = ClassesOf(facts, row, inspection.MapperCount); + await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); + + // The row is read again immediately before the delete. A tombstone is terminal and a connection id is fresh, so + // this protects against a stale reading and not against a race, and is cheap enough to keep. + var again = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + FederationActOutcome outcome; + string? cause = null; + if (IsLive(again)) + { + outcome = FederationActOutcome.LiveConnection; + cause = "live_connection"; + } + else + { + outcome = Map(await provider.RemoveAsync(owner, cancellationToken)); + } + + await Complete(handle, owner, classes, row, outcome, cause, cancellationToken); + return Known(outcome, owner); + } + + /// + public async Task DisableAsync( + PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.FederationDisable); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var inspection = await provider.InspectAsync(alias, cancellationToken); + switch (inspection.Status) + { + case FederationInspectionStatus.Unavailable: + return new FederationActResult(FederationActOutcome.Unavailable); + case FederationInspectionStatus.Absent: + return new FederationActResult(FederationActOutcome.NotFound); + case FederationInspectionStatus.NotOwned: + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var facts = inspection.Facts!; + var owner = facts.Owner; + var row = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + if (row is not null && row.TenantId != owner.TenantId.Value) + { + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var classes = ClassesOf(facts, row, inspection.MapperCount); + if (classes.Count == 0) + { + // Nothing about a healthy broker with a live row needs an operator. + return Known(FederationActOutcome.NotApplicable, owner); + } + + if (!facts.Enabled) + { + return Known(FederationActOutcome.AlreadyApplied, owner); + } + + await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); + var outcome = Map(await provider.DisableAsync(owner, cancellationToken)); + await Complete(handle, owner, classes, row, outcome, cause: null, cancellationToken); + return Known(outcome, owner); + } + + private static async Task Complete( + IPlatformAdminScopeHandle handle, FederationBrokerOwner owner, IReadOnlyList classes, Row? row, + FederationActOutcome outcome, string? cause, CancellationToken cancellationToken) + { + var token = OutcomeToken(outcome); + // The account review is owed for any change that may have landed: the provider removes federated links with a + // broker, and nothing here reads them (ADR-0099 Amendment 10 item 7). + var owed = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; + var after = JsonSerializer.Serialize(new AfterState(token, cause, owed), Json); + await handle.WriteResultAsync(Result(owner, classes, row, after), cancellationToken); + await handle.CommitAsync(cancellationToken); + } + + private static PlatformResult Result(FederationBrokerOwner owner, IReadOnlyList classes, Row? row, string? after) => new( + owner.TenantId, EntityType, owner.ConnectionId.ToString("D", CultureInfo.InvariantCulture), + JsonSerializer.Serialize(new BeforeState(classes, RowState(row)), Json), after); + + private static FederationActResult Known(FederationActOutcome outcome, FederationBrokerOwner owner) => + new(outcome, owner.TenantId.Value, owner.ConnectionId); + + private static FederationActOutcome Map(FederationOperatorOutcome outcome) => outcome switch + { + FederationOperatorOutcome.Applied => FederationActOutcome.Applied, + FederationOperatorOutcome.AlreadyApplied => FederationActOutcome.AlreadyApplied, + FederationOperatorOutcome.Refused => FederationActOutcome.Refused, + FederationOperatorOutcome.NotOwned => FederationActOutcome.NotOwned, + FederationOperatorOutcome.Unavailable => FederationActOutcome.Unavailable, + _ => FederationActOutcome.Uncertain, + }; + + private static string OutcomeToken(FederationActOutcome outcome) => outcome switch + { + FederationActOutcome.Applied => "applied", + FederationActOutcome.AlreadyApplied => "already_applied", + FederationActOutcome.NotOwned => "not_owned", + FederationActOutcome.LiveConnection => "refused", + FederationActOutcome.Refused => "refused", + FederationActOutcome.Unavailable => "unavailable", + _ => "uncertain", + }; + + /// The classes of one broker: orphan by row, then unreadable, then nonconforming by profile or mapper. + private static List ClassesOf(FederationBrokerFacts facts, Row? row, int mappers) + { + var classes = new List(3); + if (!IsLive(row)) + { + classes.Add("orphan"); + } + + if (!facts.Readable) + { + classes.Add("unreadable_owned"); + } + else if (!facts.Conforms || mappers > 0) + { + classes.Add("nonconforming"); + } + + return classes; + } + + private static bool IsLive(Row? row) => row is { Deleted: false } && !string.Equals(row.State, "Deleted", StringComparison.Ordinal); + + private static string RowState(Row? row) => row is null ? "absent" : IsLive(row) ? row.State : "deleted"; + + private static async Task> ReadRowsAsync( + IPlatformAdminScopeHandle handle, Guid[] ids, CancellationToken cancellationToken) + { + if (ids.Length == 0) + { + return []; + } + + var rows = await handle.QueryAsync( + RowQuery, [new PlatformSqlParameter("ids", ids)], + reader => new Row(reader.GetGuid(0), reader.GetGuid(1), reader.GetString(2), reader.GetBoolean(3)), cancellationToken); + return rows.ToDictionary(row => row.Id); + } + + /// + /// The mapper count of each owner, one after another, until the page's time runs out: the remainder is unknown, which + /// the report says as null and never as zero. A module runs one operation at a time (ADR-0040), and the provider's + /// own bulkhead would refuse a wider fan-out. + /// + private async Task> CountMappersAsync( + IReadOnlyList owners, CancellationToken deadline, CancellationToken caller) + { + var counts = new Dictionary(StringComparer.Ordinal); + foreach (var owner in owners) + { + try + { + counts[owner.Alias] = await provider.CountMappersAsync(owner, deadline); + } + catch (OperationCanceledException) when (!caller.IsCancellationRequested) + { + break; + } + } + + return counts; + } + + private static void RequireOperation(PlatformAdmission admission, PlatformOperation expected) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, expected)) + { + throw new ArgumentException("The admission is not for this federation operation.", nameof(admission)); + } + } + + private static string Encode(int offset) => + Convert.ToBase64String(Encoding.UTF8.GetBytes("v1~federation~" + offset.ToString(CultureInfo.InvariantCulture))) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static bool TryDecode(string cursor, out int offset) + { + offset = 0; + if (cursor.Length is 0 or > 64) + { + return false; + } + + try + { + var padded = cursor.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight((padded.Length + 3) / 4 * 4, '='); + var parts = Encoding.UTF8.GetString(Convert.FromBase64String(padded)).Split('~'); + return parts is ["v1", "federation", var number] + && int.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out offset) + && string.Equals(Encode(offset), cursor, StringComparison.Ordinal); + } + catch (FormatException) + { + return false; + } + } + + private sealed record Row(Guid Id, Guid TenantId, string State, bool Deleted); + + private sealed record BeforeState(IReadOnlyList Classes, string RowState); + + private sealed record AfterState(string Outcome, string? Cause, bool AccountReviewOwed); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs new file mode 100644 index 00000000..f94983e3 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The one grant the operator's federation report and sweep read through (ADR-0099 Amendment 10 item 5). +/// +/// +/// +/// learnstack_platform receives SELECT of four columns of federation_connections: the +/// connection's id, its tenant, its lifecycle state and its tombstone instant. That is everything the question +/// "does this broker still have a live row" needs, and nothing a tenant authored: no alias, display name, issuer, +/// provider configuration or secret reference is granted, so a statement that names one is refused by PostgreSQL +/// whatever the application does. The platform role is BYPASSRLS, so the grant, and not a policy, is the +/// bound; it holds no write privilege, and the table's guard trigger already admits only the application role to +/// write it. +/// +/// +/// The grant lives in the Identity chain because the table is created there, after the Platform chain has run. +/// +/// +internal static class FederationOperatorProjectionDdl +{ + internal static void Add(MigrationBuilder migration) => migration.Sql(""" + GRANT SELECT (id, tenant_id, state, deleted_at) ON public.federation_connections TO learnstack_platform; + """); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs new file mode 100644 index 00000000..5d0fa2a6 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs @@ -0,0 +1,17 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261120160000_grant_platform_federation_projection")] +public sealed class grant_platform_federation_projection : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => FederationOperatorProjectionDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0099 Amendment 11): a grant a reviewed forward migration retires, so a reversal cannot + // silently leave the operator's report reading a table it no longer has the right to. + throw new NotSupportedException("The platform federation projection grant requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 9efea395..69d98941 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -131,14 +131,27 @@ public void Describe(IAuditCatalogBuilder builder) .DeclareOffPath( "platform.job.dead_letter", OperationType.SecurityEvent, OperationClass.Must) // The three operator recovery operations of ADR-0103: an inspection is audited by the platform scope's - // entry row, which names this slug as its operation, and the two transitions write their own MUST row - // on the outbox-role transaction that makes the change. + // entry row, whose reason is this slug's, and the two transitions write their own MUST row on the + // outbox-role transaction that makes the change. .DeclareOffPath( "platform.delivery.inspect", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.delivery.replay", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.delivery.reset", OperationType.SecurityEvent, OperationClass.Must) + // The three operator federation operations of ADR-0099 Amendment 10. A report is audited by the platform + // scope's entry row; a remove and a disable write an intent row on their attempt slug at the scope + // handle's checkpoint and a completion row on their own slug (Amendment 11), under the real tenant. + .DeclareOffPath( + "platform.federation.report", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.remove", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.remove_attempt", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.disable", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.disable_attempt", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "tenancy.tenant_assertion.reject", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index 0fe5ee4d..3409a5f0 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -516,7 +516,7 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0101, ADR-0103 and ADR-0104 authorize fourteen writes and no update; + // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0099, ADR-0101, ADR-0103 and ADR-0104 authorize fifteen writes and no update; // another method would make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) @@ -525,7 +525,8 @@ public void IAuditStore_Exposes_No_Update_Method() "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync", "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync", - "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync", "WriteOperatorRecoveryAsync"); + "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync", "WriteOperatorRecoveryAsync", + "WritePlatformOperatorIntentAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index 7ea5d7a0..e1b32aa9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -47,7 +47,8 @@ public void Federation_Adapter_Admits_Only_The_Enumerated_Routes() var routes = typeof(FederationAdapterFactory).Assembly.GetType("LearnStack.Infrastructure.Identity.Federation.KeycloakFederationRoutes", true)!; routes.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) .Where(method => method.ReturnType == typeof(Uri)).Select(method => method.Name).Order(StringComparer.Ordinal) - .Should().Equal(["Instance", "Instances", "Mappers", "Token"], "the token endpoint, create, one owned instance and its mappers only"); + .Should().Equal(["Instance", "InstanceOf", "InstancePage", "Instances", "Mappers", "Token"], + "the token endpoint, create, the operator's bounded page and one-alias read, one owned instance and its mappers only"); RouteOffenders(Sources()).Should().BeEmpty( "Fix: build every provider route in KeycloakFederationRoutes, which admits only identity-provider/instances[/{alias}[/mappers]] (ADR-0099)"); } diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs index 031cb444..539eeb32 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs @@ -112,6 +112,19 @@ public void Every_Federation_Request_Has_An_Audit_Catalogue_Entry() "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/PublicSignInReader.cs", ]; + /// + /// The operator's one read of the registry (ADR-0099 Amendment 10 and 11): an orphan is a broker with no row or a + /// tombstoned one, so this reader must see tombstones and is exempt from the shared live predicate. It is pinned + /// instead to exactly this statement, which names the four columns the platform role may select and reads by + /// primary key; a fifth column or another predicate is refused by PostgreSQL and by this census. + /// + private const string OperatorRowReader = IdentityInfrastructure + "Federation/FederationBrokerOperations.cs"; + + private const string OperatorRowQuery = + "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; + + private static readonly string[] AllRawReaders = [.. RawLiveReaders, OperatorRowReader]; + [Fact] public void Raw_Federation_Reads_Share_The_One_Pinned_Live_Predicate() { @@ -126,7 +139,8 @@ public void Raw_Federation_Reads_Share_The_One_Pinned_Live_Predicate() RawLiveOffenders(sources).Should().BeEmpty( "Fix: every raw read of federation_connections lives in one of the three closed readers, and each statement interpolates " + "FederationConnectionReads.LiveSql and spells no tombstone predicate of its own"); - RawReaders(sources).Should().Equal(RawLiveReaders, "the census of raw registry readers is closed at three"); + RawReaders(sources).Should().Equal(AllRawReaders.Order(StringComparer.Ordinal), + "the census of raw registry readers is closed at three tenant readers and the operator's one pinned read"); } [Fact] @@ -141,9 +155,21 @@ public void The_raw_live_predicate_detector_refuses_a_reader_with_its_own_predic [RawLiveReaders[2]] = "\"\"\"\nSELECT alias FROM public.federation_connections " + Shared + " AND state='Active'\n\"\"\";", [IdentityInfrastructure + "Persistence/FederationConnectionStorageDdl.cs"] = "REVOKE ALL ON public.federation_connections FROM PUBLIC; CREATE TRIGGER t BEFORE INSERT OR UPDATE ON public.federation_connections;", + [OperatorRowReader] = "private const string RowQuery = \"" + OperatorRowQuery + "\";", }; RawLiveOffenders(clean).Should().BeEmpty(); - RawReaders(clean).Should().Equal(RawLiveReaders); + RawReaders(clean).Should().Equal(AllRawReaders.Order(StringComparer.Ordinal)); + // The operator's statement is pinned whole: a fifth column, another predicate or a second statement is refused. + foreach (var changed in new[] + { + OperatorRowQuery.Replace("state,", "state, alias,", StringComparison.Ordinal), + OperatorRowQuery.Replace("id = ANY(@ids)", "tenant_id = @tenant", StringComparison.Ordinal), + OperatorRowQuery + " AND state <> 'Deleted'", + }) + { + var widened = new Dictionary(clean) { [OperatorRowReader] = "private const string RowQuery = \"" + changed + "\";" }; + RawLiveOffenders(widened).Should().Equal([OperatorRowReader], "the operator reader is pinned: " + changed); + } var own = new Dictionary(clean) { [RawLiveReaders[1]] = "SELECT alias FROM public.federation_connections WHERE tenant_id=@tenant AND state='Active' AND deleted_at IS NULL", @@ -179,7 +205,7 @@ public void The_raw_live_predicate_detector_refuses_a_reader_with_its_own_predic } // A closed reader that is removed leaves the census short. var dropped = new Dictionary(clean) { [RawLiveReaders[2]] = "public sealed class PublicSignInReader;" }; - RawReaders(dropped).Should().Equal([RawLiveReaders[0], RawLiveReaders[1]]); + RawReaders(dropped).Should().Equal([OperatorRowReader, RawLiveReaders[0], RawLiveReaders[1]]); } private const string IdentityApplication = "Modules/Identity/LearnStack.Modules.Identity.Application/"; @@ -202,7 +228,9 @@ private static List RawReaders(IReadOnlyDictionary sourc /// ; or string delimiter on either side, must interpolate the shared constant and spell no tombstone predicate. /// private static List RawLiveOffenders(IReadOnlyDictionary sources) => - [.. sources.Where(pair => RawRead.Matches(pair.Value).Any(match => !RawLiveReaders.Contains(pair.Key, StringComparer.Ordinal) + [.. sources.Where(pair => RawRead.Matches(pair.Value).Any(match => pair.Key == OperatorRowReader + ? !string.Equals(Statement(pair.Value, match.Index).Trim(), OperatorRowQuery, StringComparison.Ordinal) + : !RawLiveReaders.Contains(pair.Key, StringComparer.Ordinal) || Statement(pair.Value, match.Index) is var statement && (!statement.Contains("{FederationConnectionReads.LiveSql}", StringComparison.Ordinal) || statement.Contains("deleted_at", StringComparison.OrdinalIgnoreCase) diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index 212ff6ad..e39fd8a3 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -569,6 +569,8 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( ["LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation]), Owner(AuditAssembly, "LearnStack.Infrastructure.Audit.AuditConfigService", "LoadAsync"), Owner(InfrastructureAssembly, LifecyclePlatform, "RecordAsync"), Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "CommitAsync"), + // ADR-0044 Amendment 18: the checkpoint commits the intent row alone before the provider is called. + Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "WriteIntentAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.MultiTenancy.CachedHostToTenantResolver", "ReadAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.MultiTenancy.OrganizationScopeValidator", "BelongsToTenantAsync"), Owner("LearnStack.Modules.Tenancy.Infrastructure", "LearnStack.Modules.Tenancy.Infrastructure.FeatureFlags", "LoadTenantFlagsAsync"), diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 32d0dbe0..880b74f2 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -263,6 +263,7 @@ public void Only_The_Operator_Services_Hold_The_Platform_Scope() CompositionFile, KillswitchWriterFile, DeliveryInspectionFile, + FederationOperationsFile, ], "each new operator service is added here deliberately, with its denied proof"); } @@ -310,6 +311,37 @@ public void Only_The_Recovery_Routes_And_Their_Owners_Name_The_Operator_Recovery "each new caller of the inspection is added here deliberately, with its denied proof"); } + [Fact] + public void Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Operator_Ports() + { + // ADR-0099 Amendment 10: the report, the remove and the disable are reachable from the federation routes alone, + // through the one owner, and the operator's provider port is held by that owner and the adapter that implements + // it. The tenant runner holds neither, so the rule that the tenant's provider port is the runner's alone stands. + SourceScan.FilesContaining(SourceScan.SourceRoot, "IFederationBrokerOperations", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs", + FederationOperationsFile, + "LearnStack.Api/Composition/PersistenceCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs", + ], + "each new caller of a federation operator act is added here deliberately, with its denied proof"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IFederationOperator", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Identity/IFederationOperator.cs", + FederationOperationsFile, + "LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs", + "LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs", + "LearnStack.Api/Composition/FederationComposition.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs", + ], + "the operator's provider port is held by the owner, its adapter and the composition that selects it"); + } + + private const string FederationOperationsFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs"; + private const string KillswitchWriterFile = "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs new file mode 100644 index 00000000..d09896be --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs @@ -0,0 +1,587 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Federation; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.FederationConnectionSchemaSeed; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The operator's federation report, remove and disable against a real database and the real platform scope (ADR-0099 +/// Amendment 10 and 11): the rows are read as learnstack_platform through its four granted columns, the realm is +/// a scripted provider, and every act's intent and completion rows are read back as written. +/// +/// +/// The database is an isolated one that holds a tombstone and a live connection of tenant A and a live connection of +/// tenant B, as the shared schema does. A tenant can hold only one live connection, so no test writes a connection row, +/// and every act writes audit rows under tenant A or B: audit_log is append-only, so those rows stay out of the shared +/// schema, whose isolation census counts what each seeded tenant sees. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class FederationBrokerOperationsTests(FederationBrokerOperationsTests.FederationDatabase database) + : IClassFixture +{ + /// One isolated, fully migrated database with tenants A and B and the federation rows of the shared seed. + public sealed class FederationDatabase(SchemaFixture schema) : IAsyncLifetime + { + private DisposableSchemaDatabase? _database; + + public string PlatformConnectionString => _database!.PlatformConnectionString; + + public async Task InitializeAsync() + { + _database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await using (var owner = await PostgresFixture.OpenAsync(_database.MigrationConnectionString)) + { + foreach (var (tenant, slug) in new[] { (SchemaFixture.TenantA, "alpha"), (SchemaFixture.TenantB, "beta") }) + { + await using var transaction = await owner.BeginTransactionAsync(); + await SchemaQueries.ExecuteAsync(owner, transaction, $"SET LOCAL app.tenant_id = '{tenant:D}'"); + await SchemaQueries.ExecuteAsync( + owner, transaction, + "INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row_version) " + + "VALUES (@id, @slug, @slug, 'Trial', now(), @actor, 0)", + ("id", tenant), ("slug", slug), ("actor", SchemaFixture.Actor)); + await transaction.CommitAsync(); + } + } + + await FederationConnectionSchemaSeed.SeedAsync(_database.AppConnectionString); + } + + public async Task DisposeAsync() + { + if (_database is not null) await _database.DisposeAsync(); + } + } + + private static FederationBrokerOwner OwnerOf(Guid connection, Guid? tenant = null) => + new(TenantId.From(tenant ?? SchemaFixture.TenantA), connection, Alias(connection)); + + private static FederationBrokerFacts Facts(FederationBrokerOwner owner, bool readable = true, bool conforms = true, bool enabled = true) => + new(owner, readable, conforms, enabled, readable ? FederationBrokerProtocol.Oidc : null); + + [Fact] + public async Task A_report_names_a_broker_with_no_row_a_tombstone_and_an_unreadable_one_and_not_a_healthy_live_one() + { + var operations = new Scripted(); + var healthy = OwnerOf(LiveA); + var tombstoned = OwnerOf(TombstoneA); + var absent = OwnerOf(Guid.CreateVersion7()); + var unreadableLive = OwnerOf(LiveB, SchemaFixture.TenantB); + operations.Listed = [Facts(healthy), Facts(tombstoned), Facts(absent), Facts(unreadableLive, readable: false)]; + var service = Service(operations); + + var result = await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Ok); + result.Items.Select(item => (item.ConnectionId, string.Join('+', item.Classes), item.RowState)).Should().Equal( + (TombstoneA, "orphan", "deleted"), + (absent.ConnectionId, "orphan", "absent"), + (LiveB, "unreadable_owned", "Draft")); + result.Items.Should().OnlyContain(item => item.Alias.StartsWith("lsf-", StringComparison.Ordinal)); + result.Scanned.Should().Be(4); + // A healthy live broker with no mapper drift is no finding, and its mapper count was asked once. + operations.MapperCalls.Should().Equal(healthy.Alias); + } + + [Fact] + public async Task A_report_enters_the_scope_first_reads_the_realm_next_and_the_rows_only_after_it() + { + // A tenant commits its row before it creates the broker, so a broker the realm listed already has its row when the + // rows are read; a reader that took the rows first would call a broker created in between an orphan. The order + // is observed, not inferred: the scope entry, the listing and the row query are recorded as they happen. + var events = new List(); + var operations = new Scripted { Listed = [Facts(OwnerOf(LiveA))], Events = events }; + var service = new FederationBrokerOperations(new RecordingScope(Scope(false, false), events), operations); + + await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + events.Should().Equal("enter", "list", "query", "mappers"); + } + + [Fact] + public async Task A_report_never_names_a_broker_whose_marker_and_row_disagree_about_the_tenant() + { + var operations = new Scripted(); + var wrongTenant = OwnerOf(LiveA, SchemaFixture.TenantB); + operations.Listed = [Facts(wrongTenant, readable: false)]; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Items.Should().BeEmpty(); + result.Ignored.Should().Be(1, "it is counted and never named"); + } + + [Fact] + public async Task A_report_pages_by_an_opaque_cursor_it_issued_and_refuses_one_it_did_not() + { + var operations = new Scripted { Listed = [.. Enumerable.Range(0, 5).Select(_ => Facts(OwnerOf(Guid.CreateVersion7()), readable: false))] }; + var service = Service(operations); + + var first = await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 2); + var second = await service.ReportAsync(Admission(PlatformOperations.FederationReport), first.NextCursor, 2); + var last = await service.ReportAsync(Admission(PlatformOperations.FederationReport), second.NextCursor, 2); + + (first.Scanned, second.Scanned, last.Scanned).Should().Be((2, 2, 1)); + last.NextCursor.Should().BeNull(); + first.Items.Concat(second.Items).Concat(last.Items).Select(item => item.Alias).Should().OnlyHaveUniqueItems().And.HaveCount(5); + operations.Offsets.Should().Equal(0, 2, 4); + foreach (var forged in new[] { "x", "djF-ZmVkZXJhdGlvbn4tMQ", Convert.ToBase64String("v1~federation~-1"u8) }) + { + var refused = await service.ReportAsync(Admission(PlatformOperations.FederationReport), forged, 2); + refused.Outcome.Should().Be(FederationReportOutcome.InvalidCursor, forged); + } + + operations.Offsets.Should().Equal([0, 2, 4], "a refused cursor reaches no provider and enters no scope"); + } + + [Fact] + public async Task A_report_the_provider_cannot_answer_is_unavailable_and_writes_only_the_scopes_entry_row() + { + var operations = new Scripted { Unavailable = true }; + var admission = Admission(PlatformOperations.FederationReport, ticket: "CHG-1"); + + var result = await Service(operations).ReportAsync(admission, null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Unavailable); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + rows[0].Metadata.Should().Contain("CHG-1", "the entry row is a sentinel row, which carries the ticket"); + } + + [Fact] + public async Task A_remove_of_a_broker_with_a_live_row_is_refused_before_anything_is_written_or_sent() + { + var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, Alias(LiveA)); + + result.Outcome.Should().Be(FederationActOutcome.LiveConnection); + operations.Removed.Should().BeEmpty("a live connection row refuses, for an unreadable broker too"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData("tombstone")] + [InlineData("absent")] + [InlineData("tenant_without_a_row")] + public async Task A_remove_of_an_orphan_writes_an_intent_before_the_provider_call_and_a_completion_after_it_under_the_markers_tenant(string kind) + { + var tenant = kind == "tenant_without_a_row" ? Guid.CreateVersion7() : SchemaFixture.TenantA; + var connection = kind == "tombstone" ? TombstoneA : Guid.CreateVersion7(); + var owner = OwnerOf(connection, tenant); + var operations = new Scripted { Inspected = Facts(owner, readable: false), InspectedMappers = 0 }; + var admission = Admission(PlatformOperations.FederationRemove, ticket: "CHG-5"); + operations.BeforeRemove = async () => + { + // The intent row is already committed when the provider is called: another connection sees it. + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + }; + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.Applied, tenant, connection)); + operations.Removed.Should().ContainSingle().Which.Should().Be(owner); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + (PlatformAdminScope.EnterOperation, "success"), + ("platform.federation.remove_attempt", "indeterminate"), + ("platform.federation.remove", "success")); + rows.Skip(1).Should().OnlyContain(row => row.Tenant == tenant, "the rows name the marker's tenant, never the sentinel"); + rows.Skip(1).Should().OnlyContain(row => !row.Metadata.Contains("CHG-5"), "a tenant can read these rows"); + rows[1].EntityId.Should().Be(connection.ToString("D")); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("applied"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeTrue(); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Contain("orphan"); + } + + [Fact] + public async Task A_remove_of_an_absent_or_foreign_broker_writes_no_tenant_row() + { + var operations = new Scripted { InspectedStatus = FederationInspectionStatus.Absent }; + var absent = Admission(PlatformOperations.FederationRemove); + (await Service(operations).RemoveAsync(absent, Alias(Guid.CreateVersion7()))).Outcome.Should().Be(FederationActOutcome.AlreadyApplied); + + operations.InspectedStatus = FederationInspectionStatus.NotOwned; + var foreign = Admission(PlatformOperations.FederationRemove); + (await Service(operations).RemoveAsync(foreign, Alias(Guid.CreateVersion7()))).Outcome.Should().Be(FederationActOutcome.NotOwned); + + operations.Removed.Should().BeEmpty(); + foreach (var admission in new[] { absent, foreign }) + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData(FederationOperatorOutcome.Uncertain, "uncertain", FederationActOutcome.Uncertain)] + [InlineData(FederationOperatorOutcome.Unavailable, "unavailable", FederationActOutcome.Unavailable)] + [InlineData(FederationOperatorOutcome.Refused, "refused", FederationActOutcome.Refused)] + public async Task A_provider_that_does_not_apply_a_remove_is_recorded_in_the_completion_row( + FederationOperatorOutcome provider, string recorded, FederationActOutcome expected) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = provider }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be(recorded); + } + + [Fact] + public async Task A_failed_intent_write_stops_the_remove_before_the_provider_is_called() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var act = async () => await Service(operations, failIntent: true).RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync(); + operations.Removed.Should().BeEmpty("the effect must not start on an intent nobody recorded"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_failed_completion_write_leaves_the_intent_row_standing_after_the_effect() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var act = async () => await Service(operations, failResult: true).RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync(); + operations.Removed.Should().ContainSingle("the provider call had been made"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + } + + [Theory] + [InlineData("healthy_live", FederationActOutcome.NotApplicable)] + [InlineData("already_disabled", FederationActOutcome.AlreadyApplied)] + public async Task A_disable_that_nothing_needs_writes_no_row_and_sends_nothing(string kind, FederationActOutcome expected) + { + var owner = OwnerOf(LiveA); + var facts = kind == "healthy_live" ? Facts(owner) : Facts(owner, readable: false, enabled: false); + var operations = new Scripted { Inspected = facts }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData("unreadable", false, true, 0)] + [InlineData("profile_drift", true, false, 0)] + [InlineData("mapper_drift", true, true, 2)] + public async Task A_disable_of_a_broker_the_tenant_cannot_reach_or_that_has_drifted_is_applied_with_two_rows( + string kind, bool readable, bool conforms, int mappers) + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable, conforms), InspectedMappers = mappers }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Applied, kind); + operations.Disabled.Should().ContainSingle(); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Contain( + readable ? "nonconforming" : "unreadable_owned"); + before.RootElement.GetProperty("rowState").GetString().Should().Be("Draft", "the tenant's own row is left as found"); + } + + [Fact] + public async Task An_admission_for_another_operation_is_refused_by_each_entry_before_the_provider_or_the_scope() + { + var operations = new Scripted(); + var service = Service(operations); + var wrong = Admission(PlatformOperations.FederationReport); + + var remove = async () => await service.RemoveAsync(wrong, Alias(Guid.CreateVersion7())); + var disable = async () => await service.DisableAsync(wrong, Alias(Guid.CreateVersion7())); + var report = async () => await service.ReportAsync(Admission(PlatformOperations.FederationRemove), null, 5); + + await remove.Should().ThrowAsync(); + await disable.Should().ThrowAsync(); + await report.Should().ThrowAsync(); + operations.Calls.Should().BeEmpty(); + (await RowsAsync(wrong.Operator.CorrelationId!)).Should().BeEmpty("no scope was entered"); + } + + [Fact] + public async Task The_platform_role_reads_exactly_the_four_projection_columns_and_writes_nothing() + { + await using var platform = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT attname FROM pg_attribute + WHERE attrelid = 'public.federation_connections'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'public.federation_connections', attnum, 'SELECT') + ORDER BY attname + """, (NpgsqlConnection)platform); + var granted = new List(); + await using (var reader = await command.ExecuteReaderAsync()) + while (await reader.ReadAsync()) granted.Add(reader.GetString(0)); + granted.Should().Equal("deleted_at", "id", "state", "tenant_id"); + + foreach (var sql in new[] + { + "SELECT alias FROM public.federation_connections", "SELECT display_name FROM public.federation_connections", + "SELECT issuer_or_entity_id FROM public.federation_connections", "SELECT * FROM public.federation_connections", + "SELECT client_id FROM public.federation_connections", "SELECT configuration_digest FROM public.federation_connections", + "UPDATE public.federation_connections SET state = 'Deleted'", "DELETE FROM public.federation_connections", + "INSERT INTO public.federation_connections (id) VALUES (gen_random_uuid())", + }) + { + await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sql)).Should() + .ThrowAsync(sql).Where(failure => failure.SqlState == PostgresErrorCodes.InsufficientPrivilege, sql); + } + + // The granted four read across both tenants, which the role's BYPASSRLS makes possible. + await using var distinct = new NpgsqlCommand( + "SELECT count(DISTINCT tenant_id) FROM public.federation_connections", (NpgsqlConnection)platform); + ((long)(await distinct.ExecuteScalarAsync())!).Should().BeGreaterThanOrEqualTo(2); + } + + private FederationBrokerOperations Service(Scripted operations, bool failIntent = false, bool failResult = false) => + new(Scope(failIntent, failResult), operations); + + private PlatformAdminScope Scope(bool failIntent, bool failResult) + { + var platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + var store = AuditStore(); + return new PlatformAdminScope( + new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + failIntent || failResult ? new FailingStore(store, failIntent, failResult) : store, + new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + } + + private static PlatformAdmission Admission(PlatformOperation operation, string? ticket = null) => TestPlatformAdmissions.Admission( + operation, ticket, correlationId: "00-federation-" + Guid.NewGuid().ToString("N")); + + private async Task> RowsAsync(string correlation) + { + await using var connection = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT operation, outcome::text, tenant_id, metadata::text, coalesce(before_state::text, ''), coalesce(after_state::text, ''), + coalesce(entity_id, '') + FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id + """, (NpgsqlConnection)connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + rows.Add(new AuditRow(reader.GetString(0), reader.GetString(1), reader.GetGuid(2), reader.IsDBNull(3) ? string.Empty : reader.GetString(3), + reader.GetString(4), reader.GetString(5), reader.GetString(6))); + return rows; + } + + private static IServiceScopeFactory AuditStore() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's rows are written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// The real scope, recording the order in which its handle is entered and queried. + private sealed class RecordingScope(IPlatformAdminScope inner, List events) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) + { + events.Add("enter"); + return new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine), events); + } + + private sealed class Handle(IPlatformAdminScopeHandle inner, List events) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + inner.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) + { + events.Add("query"); + return inner.QueryAsync(sql, parameters, map, cancellationToken); + } + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + inner.WriteIntentAsync(intent, cancellationToken); + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + inner.WriteResultAsync(result, cancellationToken); + + public Task CommitAsync(CancellationToken cancellationToken = default) => inner.CommitAsync(cancellationToken); + + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } + + private sealed record AuditRow(string Operation, string Outcome, Guid Tenant, string Metadata, string Before, string After, string EntityId); + + /// Fails the intent or the completion row of the operator, as an outage at that moment would. + private sealed class FailingStore(IServiceScopeFactory inner, bool failIntent, bool failResult) : IServiceScopeFactory + { + public IServiceScope CreateScope() => new Scope(inner.CreateScope(), failIntent, failResult); + + private sealed class Scope(IServiceScope inner, bool failIntent, bool failResult) : IServiceScope, IServiceProvider + { + public IServiceProvider ServiceProvider => this; + + public object? GetService(Type type) => type == typeof(IAuditStore) + ? new Decorator(inner.ServiceProvider.GetRequiredService(), failIntent, failResult) + : inner.ServiceProvider.GetService(type); + + public void Dispose() => inner.Dispose(); + } + + private sealed class Decorator(IAuditStore store, bool failIntent, bool failResult) : IAuditStore + { + public Task WritePlatformScopeAsync(AuditEntryDraft entry, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + store.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + failIntent + ? throw new AuditWriteFailedException("forced intent failure") + : store.WritePlatformOperatorIntentAsync(entry, admission, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorResultAsync(AuditEntryDraft entry, PlatformAdmission admission, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + failResult + ? throw new AuditWriteFailedException("forced result failure") + : store.WritePlatformOperatorResultAsync(entry, admission, connection, transaction, cancellationToken); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + } + + /// A scripted realm: what the provider lists, what it says about one alias, and how a change ends. + private sealed class Scripted : IFederationOperator + { + public IReadOnlyList Listed { get; set; } = []; + public bool Unavailable { get; set; } + public List? Events { get; set; } + public FederationBrokerFacts? Inspected { get; set; } + public int InspectedMappers { get; set; } + public FederationInspectionStatus? InspectedStatus { get; set; } + public FederationOperatorOutcome RemoveOutcome { get; set; } = FederationOperatorOutcome.Applied; + public FederationOperatorOutcome DisableOutcome { get; set; } = FederationOperatorOutcome.Applied; + public Func? BeforeRemove { get; set; } + public List Calls { get; } = []; + public List Offsets { get; } = []; + public List MapperCalls { get; } = []; + public List Removed { get; } = []; + public List Disabled { get; } = []; + + public Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default) + { + Calls.Add("list"); + Events?.Add("list"); + Offsets.Add(offset); + if (Unavailable) return Task.FromResult(FederationBrokerPage.Unavailable); + var page = Listed.Skip(offset).Take(limit).ToList(); + return Task.FromResult(new FederationBrokerPage(FederationOperatorStatus.Ok, page, 0, page.Count)); + } + + public Task InspectAsync(string alias, CancellationToken cancellationToken = default) + { + Calls.Add("inspect"); + return Task.FromResult(InspectedStatus switch + { + FederationInspectionStatus.Absent => FederationBrokerInspection.Absent, + FederationInspectionStatus.NotOwned => FederationBrokerInspection.NotOwned, + FederationInspectionStatus.Unavailable => FederationBrokerInspection.Unavailable, + _ => new FederationBrokerInspection(FederationInspectionStatus.Owned, Inspected, InspectedMappers), + }); + } + + public Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + Calls.Add("mappers"); + Events?.Add("mappers"); + MapperCalls.Add(owner.Alias); + return Task.FromResult(0); + } + + public async Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + Calls.Add("remove"); + Removed.Add(owner); + if (BeforeRemove is { } hook) await hook(); + return RemoveOutcome; + } + + public Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + Calls.Add("disable"); + Disabled.Add(owner); + return Task.FromResult(DisableOutcome); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 76c126d6..891cf7d2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -217,6 +217,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() releaseV4.Should().Throw().WithMessage("Role release adoption requires a reviewed forward migration."); Action operatorResolver = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_operator_subject_resolver().DownOperations; operatorResolver.Should().Throw().WithMessage("Operator subject resolution requires a reviewed forward migration."); + Action authorityRebind = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_identity_authority_rebind().DownOperations; + authorityRebind.Should().Throw().WithMessage("The issuer-rebind storage requires a reviewed forward migration."); Action protectedReceipts = () => _ = new LearnStack.Infrastructure.Persistence.Migrations.add_custom_field_protected_receipts().DownOperations; protectedReceipts.Should().Throw().WithMessage("Retained custom field receipts require a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] @@ -225,8 +227,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), (platform, "20261110013140_add_custom_field_protected_receipts", PlatformReversibleHead, "20261120120000_grant_platform_delivery_inspection", "The platform role's column grants require a reviewed forward migration."), - (identity, "20261119140000_add_operator_subject_resolver", IdentityReversibleHead, - "20261120090000_add_identity_authority_rebind", "The issuer-rebind storage requires a reviewed forward migration."), + (identity, "20261120090000_add_identity_authority_rebind", IdentityReversibleHead, + "20261120160000_grant_platform_federation_projection", "The platform federation projection grant requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, "20261109230218_membership_custom_field_definitions", "Retained custom field definitions require a reviewed forward migration."), }) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index bc168c5e..8a12dae2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -950,6 +950,250 @@ public async Task An_Admission_For_A_Recovery_Act_Opens_No_Platform_Scope_And_Wr (await write.Should().ThrowAsync(slug)).Which.Message.Should().Contain("admission"); } + private static PlatformAdmission FederationAdmission(PlatformOperation operation, string? ticket, string correlation) => + TestPlatformAdmissions.Admission(operation, ticket, correlationId: correlation); + + /// + /// The tenant an operator federation row names in these cases. It has no tenants row, as an orphan's owner may + /// not, and it is not a seeded tenant, because audit_log is append-only and the isolation census that shares this + /// database counts the rows each seeded tenant sees. + /// + private static readonly Guid UnseededFederationTenant = Guid.CreateVersion7(); + + private static PlatformResult FederationIntent(Guid connection, string? after = null) => + new(TenantId.From(UnseededFederationTenant), "FederationConnection", connection.ToString("D"), "{\"classes\":[\"orphan\"]}", after); + + private static async Task> Outcomes( + System.Data.Common.DbConnection connection, string correlation) + { + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT operation, outcome::text, tenant_id, metadata::text FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id"; + command.Parameters.Add(new NpgsqlParameter("c", correlation)); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List<(string, string, Guid, string)>(); + while (await reader.ReadAsync()) rows.Add((reader.GetString(0), reader.GetString(1), reader.GetGuid(2), reader.IsDBNull(3) ? string.Empty : reader.GetString(3))); + return rows; + } + + [Fact] + public async Task An_Intent_Row_Commits_Before_The_Effect_And_Stands_When_The_Act_Is_Abandoned() + { + // ADR-0099 Amendment 11: the effect lies outside the database, so the intent must be durable before it starts. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + var host = $"intent-{Guid.NewGuid():N}.example.com"; + await using (var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, "CHG-7", correlation))) + { + await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + + // The scope continues in a fresh transaction, and an act that then fails is rolled back by disposal. + (await InsertHostAsync(handle, host)).Should().Be(1); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Outcomes(read, correlation); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + rows[0].Tenant.Should().Be(TenantId.PlatformSentinel.Value); + rows[0].Metadata.Should().Contain("CHG-7", "the entry row is a sentinel row, which carries the ticket"); + rows[1].Outcome.Should().Be("indeterminate", "the effect had not happened when the row was written"); + rows[1].Tenant.Should().Be(UnseededFederationTenant, "the row names the tenant the caller named, never the sentinel"); + rows[1].Metadata.Should().NotContain("CHG-7", "a tenant can read this row"); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))).Should().Be(0, + "work after the checkpoint is rolled back with the abandoned scope"); + } + + [Fact] + public async Task The_Completion_Row_And_Commit_End_An_Act_With_A_Checkpoint_In_The_Order_Intent_Then_Result() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + var connection = Guid.CreateVersion7(); + await using (var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, null, correlation))) + { + await handle.WriteIntentAsync(FederationIntent(connection)); + await handle.WriteResultAsync(FederationIntent(connection, "{\"outcome\":\"applied\"}")); + await handle.CommitAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Outcomes(read, correlation); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + (PlatformAdminScope.EnterOperation, "success"), + ("platform.federation.remove_attempt", "indeterminate"), + ("platform.federation.remove", "success")); + rows.Skip(1).Select(row => row.Tenant).Should().OnlyContain(tenant => tenant == UnseededFederationTenant); + } + + [Fact] + public async Task A_Checkpoint_Is_Refused_Where_It_Does_Not_Belong_And_An_Act_That_Has_One_Cannot_Skip_It() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + + // An operation that declares no attempt slug has no checkpoint. + await using (var plain = await Build(dataSource).EnterAsync(Admission())) + { + var intent = async () => await plain.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await intent.Should().ThrowAsync().WithMessage("*declares no intent checkpoint*"); + } + + await using var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationDisable, null, "corr-" + Guid.NewGuid().ToString("N"))); + var early = async () => await handle.WriteResultAsync(FederationIntent(Guid.CreateVersion7())); + await early.Should().ThrowAsync().WithMessage("*intent row before its result row*"); + + await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + var twice = async () => await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await twice.Should().ThrowAsync().WithMessage("*written once*"); + } + + [Fact] + public async Task A_Failed_Intent_Write_Stops_The_Act_Before_Anything_Commits() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + await using (var handle = await Build(dataSource, NullLogger.Instance, IntentFailingStore()).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, null, correlation))) + { + var intent = async () => await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await intent.Should().ThrowAsync(); + + var after = async () => await handle.WriteResultAsync(FederationIntent(Guid.CreateVersion7())); + await after.Should().ThrowAsync("a faulted scope can only be abandoned"); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await Outcomes(read, correlation)).Select(row => row.Operation).Should().Equal( + [PlatformAdminScope.EnterOperation], "only the entry row stands: the effect never started"); + } + + [Fact] + public async Task An_Intent_Row_Cannot_Differ_From_Its_Admission_In_Any_Bound_Attribute() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = FederationAdmission(PlatformOperations.FederationRemove, null, "corr-" + Guid.NewGuid().ToString("N")); + var digest = admission.Operator.SubjectDigest; + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + string Metadata(string issuer, string? ticket = null) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + digest + "\",\"kind\":\"human\"" + + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + var good = new AuditEntryDraft + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.From(UnseededFederationTenant), + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "platform", + Operation = "platform.federation.remove_attempt", + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = "FederationConnection", + EntityId = Guid.CreateVersion7().ToString("D"), + Outcome = AuditOutcome.Indeterminate, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = Metadata(admission.Operator.Issuer), + }; + await audit.WritePlatformOperatorIntentAsync(good, admission, connection, transaction); + + var refused = new Dictionary + { + ["the result slug"] = good with { Operation = "platform.federation.remove" }, + ["another operation"] = good with { Operation = "platform.federation.disable_attempt" }, + ["a success outcome"] = good with { Outcome = AuditOutcome.Success }, + ["a non-null actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["no metadata"] = good with { Metadata = null }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["another issuer"] = good with { Metadata = Metadata("https://elsewhere.example.test/realms/x") }, + ["another reason"] = good with { Reason = "other_reason" }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["the identity module"] = good with { ModuleName = "identity" }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["a ticket on a tenant row"] = good with { Metadata = Metadata(admission.Operator.Issuer, "INC-1") }, + }; + foreach (var (attribute, draft) in refused) + { + var act = async () => await audit.WritePlatformOperatorIntentAsync(draft, admission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + + // An operation with no attempt slug presents no intent, whatever the draft says. + var killswitch = Admission(); + var wrong = async () => await audit.WritePlatformOperatorIntentAsync(good, killswitch, connection, transaction); + await wrong.Should().ThrowAsync(); + + // The offline rebind has an attempt slug too, and writes it on its own role through its own method: its admission + // is not one this writer takes, whatever the draft says. + var rebind = FederationAdmission(PlatformOperations.IdentityAuthorityRebind, null, "corr-" + Guid.NewGuid().ToString("N")); + var offline = good with + { + Operation = "identity.authority.rebind_attempt", + Reason = rebind.Operation.ReasonSlug, + CorrelationId = rebind.Operator.CorrelationId, + Metadata = Metadata(rebind.Operator.Issuer), + }; + var rebound = async () => await audit.WritePlatformOperatorIntentAsync(offline, rebind, connection, transaction); + (await rebound.Should().ThrowAsync()).Which.Message.Should().Contain("admission"); + } + + private static IServiceScopeFactory IntentFailingStore() => + new ServiceCollection() + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// Writes the entry row for real and fails the intent row, as an outage at the checkpoint would. + private sealed class IntentFailingAuditStore : IAuditStore + { + private readonly IAuditStore _inner = AuditStoreScopeFactory().CreateScope().ServiceProvider.GetRequiredService(); + + public Task WritePlatformScopeAsync( + AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + _inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorIntentAsync( + AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + throw new AuditWriteFailedException("forced intent failure"); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + [Fact] public async Task Commit_Without_A_Result_Row_Is_Refused_And_The_Work_Rolls_Back() { diff --git a/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs index d3e16509..fc743154 100644 --- a/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs @@ -160,6 +160,12 @@ public Task> QueryAsync( (IReadOnlyList)(object)Enumerable.Repeat(true, LockedRows).ToList()); } + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) + { + Steps.Add("intent"); + return Task.CompletedTask; + } + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) { Steps.Add("result"); diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index e716c421..cc1d0546 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -48,6 +48,7 @@ public sealed class PlatformOperatorHttpTests : IAsyncLifetime private RecordingToggle _toggle = null!; private RecordingRecovery _recovery = null!; private RecordingInspection _inspection = null!; + private RecordingBrokers _brokers = null!; private CapturingLogs _logs = null!; private HttpClient _client = null!; @@ -58,6 +59,7 @@ public async Task InitializeAsync() _toggle = new RecordingToggle(); _recovery = new RecordingRecovery(); _inspection = new RecordingInspection(); + _brokers = new RecordingBrokers(); _logs = new CapturingLogs(); _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, services: registrations => @@ -66,6 +68,7 @@ public async Task InitializeAsync() registrations.AddSingleton(_ => LoggerFactory.Create(builder => builder.AddProvider(_logs))); registrations.AddSingleton(_recovery); registrations.AddScoped(_ => _inspection); + registrations.AddScoped(_ => _brokers); }); _client = _factory.CreateClient(); } @@ -653,6 +656,174 @@ public async Task An_Unavailable_Owner_Logs_Its_Cause_Under_Its_Own_Event_Id_Whi _logs.Entries.Should().NotContain(line => line.Id == 7109); } + private const string Fed = "/api/platform/v1/federation/brokers"; + private const string BrokerAlias = "lsf-019a192954507bbb8df1516e8e002502"; + + [Fact] + public async Task A_Federation_Report_Passes_Its_Page_On_Clamps_The_Limit_And_Answers_The_Envelope() + { + var response = await Call(HttpMethod.Get, Fed + "?limit=500&cursor=abc&ticket=CHG-5", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _brokers.Calls.Should().ContainSingle().Which; + (call.Operation, call.Argument, call.Limit).Should().Be(("report", "abc", 100)); + call.Admission.Operation.Should().BeSameAs(PlatformOperations.FederationReport); + call.Admission.Ticket.Should().Be("CHG-5"); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next\"").And.Contain("\"scanned\":3").And.Contain("\"ignored\":1"); + } + + [Theory] + [InlineData("limit=0", "limit")] + [InlineData("state=terminal_requested", "query")] + [InlineData("limt=5", "query")] + public async Task A_Federation_Report_Refuses_A_Bad_Or_Unknown_Parameter_And_Names_It_Without_Echo(string query, string field) + { + var response = await Call(HttpMethod.Get, Fed + "?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("errors").TryGetProperty(field, out _).Should().BeTrue(field); + text.Should().NotContain("limt"); + _brokers.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Cursor_The_Federation_Owner_Refuses_And_An_Unavailable_Provider_Are_Answered_As_Their_Problems() + { + _brokers.Report = FederationReportResult.Of(FederationReportOutcome.InvalidCursor); + var refused = await Call(HttpMethod.Get, Fed + "?cursor=forged", Valid()); + refused.StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await refused.Content.ReadAsStringAsync()).Should().Contain("cursor"); + + _brokers.Report = FederationReportResult.Of(FederationReportOutcome.Unavailable); + var unavailable = await Call(HttpMethod.Get, Fed, Valid()); + unavailable.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + unavailable.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await unavailable.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + } + + [Theory] + [InlineData("remove", "FederationRemove")] + [InlineData("disable", "FederationDisable")] + public async Task A_Federation_Act_Runs_Under_An_Admission_For_Exactly_Its_Operation_And_Answers_The_Review_Owed( + string verb, string operationName) + { + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/{verb}", Valid(), """{"ticket":"CHG-9"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _brokers.Calls.Should().ContainSingle().Which; + (call.Operation, call.Argument).Should().Be((verb, BrokerAlias)); + call.Admission.Operation.Should().BeSameAs(operationName == "FederationRemove" + ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + call.Admission.Ticket.Should().Be("CHG-9"); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain("\"outcome\":\"applied\"").And.Contain("\"accountReviewOwed\":true").And.Contain(BrokerAlias); + } + + [Theory] + [InlineData("not-an-alias")] + [InlineData("lsf-ABCDEF0123456789ABCDEF0123456789")] + [InlineData("lsf-0123456789abcdef0123456789abcde")] + [InlineData("kc-019a192954507bbb8df1516e8e002502")] + public async Task A_Federation_Act_Names_Only_A_Derived_Alias_And_Calls_Nothing_Otherwise(string alias) + { + var response = await Call(HttpMethod.Post, $"{Fed}/{alias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _brokers.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData(FederationActOutcome.AlreadyApplied, HttpStatusCode.OK, "already_applied")] + [InlineData(FederationActOutcome.NotFound, HttpStatusCode.NotFound, "not_found")] + [InlineData(FederationActOutcome.NotOwned, HttpStatusCode.Conflict, "lockey_not_owned")] + [InlineData(FederationActOutcome.LiveConnection, HttpStatusCode.Conflict, "lockey_live_connection")] + [InlineData(FederationActOutcome.NotApplicable, HttpStatusCode.Conflict, "lockey_not_applicable")] + [InlineData(FederationActOutcome.Refused, HttpStatusCode.Conflict, "lockey_provider_refused")] + public async Task A_Federation_Act_Answers_Each_Outcome_With_Its_Status_And_The_Reason_On_The_Field_It_Concerns( + FederationActOutcome outcome, HttpStatusCode status, string expected) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(status); + (await response.Content.ReadAsStringAsync()).Should().Contain(expected); + } + + [Fact] + public async Task An_Unknown_Or_Unavailable_Federation_Outcome_Is_A_Retryable_503_Whose_Body_Agrees_With_Its_Status() + { + foreach (var (outcome, unknown) in new[] { (FederationActOutcome.Unavailable, false), (FederationActOutcome.Uncertain, true) }) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, outcome.ToString()); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.TryGetProperty("errors", out var errors).Should().Be(unknown); + if (unknown) errors.GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + } + + [Fact] + public async Task A_Failed_Federation_Audit_Write_Is_The_Retryable_Audit_503_And_Is_Counted() + { + _brokers.Failure = new AuditWriteFailedException("forced"); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + await AssertProblem(response, "audit_unavailable"); + } + + [Theory] + [InlineData(FedKey.None)] + [InlineData(FedKey.Read)] + [InlineData(FedKey.Admin)] + public async Task The_Federation_Read_And_Admin_Keys_Admit_Only_Their_Own_Routes_And_The_Delivery_Keys_Neither(FedKey held) + { + var key = held switch + { + FedKey.Read => PlatformPermissions.FederationRead.Key, + FedKey.Admin => PlatformPermissions.FederationAdmin.Key, + _ => PlatformPermissions.DeliveryWrite.Key, + }; + var brokers = new RecordingBrokers(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => registrations.AddScoped(_ => brokers), + permissions: [key]); + using var client = single.CreateClient(); + + async Task Send(HttpMethod method, string path, string? json) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + Valid() } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return (await client.SendAsync(request)).StatusCode; + } + + (await Send(HttpMethod.Get, Fed, null)).Should().Be(held == FedKey.Read ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + (await Send(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", "{}")).Should().Be( + held == FedKey.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + (await Send(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", "{}")).Should().Be( + held == FedKey.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + brokers.Calls.Count.Should().Be(held == FedKey.None ? 0 : held == FedKey.Read ? 1 : 2); + } + + public enum FedKey + { + None, + Read, + Admin, + } + [Theory] [InlineData("limit=0", "limit")] [InlineData("limit=-3", "limit")] @@ -943,12 +1114,18 @@ public async Task The_Production_Composition_Resolves_The_Recovery_Owner_And_The "/api/platform/v1/asynchronous-work/quarantined-jobs", "/api/platform/v1/asynchronous-work/event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay", "/api/platform/v1/asynchronous-work/outbox-messages/{tenantId}/{eventId}/reset", + "/api/platform/v1/federation/brokers", + "/api/platform/v1/federation/brokers/{alias}/remove", + "/api/platform/v1/federation/brokers/{alias}/disable", ]; /// The verb each operator route answers: reads are GET, recovery acts are POST, the rest are idempotent PUTs. - private static string VerbOf(string route) => route.Contains("/asynchronous-work/", StringComparison.Ordinal) - ? route.EndsWith("/replay", StringComparison.Ordinal) || route.EndsWith("/reset", StringComparison.Ordinal) ? "post" : "get" - : "put"; + private static string VerbOf(string route) => + route.Contains("/asynchronous-work/", StringComparison.Ordinal) + ? route.EndsWith("/replay", StringComparison.Ordinal) || route.EndsWith("/reset", StringComparison.Ordinal) ? "post" : "get" + : route.Contains("/federation/", StringComparison.Ordinal) + ? route.EndsWith("/remove", StringComparison.Ordinal) || route.EndsWith("/disable", StringComparison.Ordinal) ? "post" : "get" + : "put"; [Fact] public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() @@ -983,7 +1160,7 @@ public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_S } [Fact] - public void The_Operator_Surface_Is_Exactly_The_Eleven_Authorized_Endpoints_Under_Its_Prefix() + public void The_Operator_Surface_Is_Exactly_The_Fourteen_Authorized_Endpoints_Under_Its_Prefix() { // The tenant surface census excludes this surface by exact type (it has its own scheme), so // its population is closed here instead: every routed endpoint under /api/platform (whatever @@ -1179,6 +1356,34 @@ public Task ToggleAsync( } } + private sealed class RecordingBrokers : IFederationBrokerOperations + { + public List<(string Operation, PlatformAdmission Admission, string? Argument, int Limit)> Calls { get; } = []; + public FederationReportResult Report { get; set; } = new(FederationReportOutcome.Ok, [], "next", 3, 1); + public FederationActResult Act { get; set; } = new(FederationActOutcome.Applied, Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501"), + Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502")); + public Exception? Failure { get; set; } + + public Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) + { + Calls.Add(("report", admission, cursor, limit)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Report); + } + + public Task RemoveAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) => + Record("remove", admission, alias); + + public Task DisableAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) => + Record("disable", admission, alias); + + private Task Record(string operation, PlatformAdmission admission, string alias) + { + Calls.Add((operation, admission, alias, 0)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Act); + } + } + private sealed class RecordingRecovery : IOperatorRecovery { public List<(PlatformAdmission Admission, object Request)> Calls { get; } = []; @@ -1272,7 +1477,8 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) var held = permissions ?? [ PlatformPermissions.KillswitchWrite.Key, PlatformPermissions.DeliveryRead.Key, - PlatformPermissions.DeliveryWrite.Key, + PlatformPermissions.DeliveryWrite.Key, PlatformPermissions.FederationRead.Key, + PlatformPermissions.FederationAdmin.Key, ]; for (var index = 0; index < held.Length; index++) { diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs new file mode 100644 index 00000000..01369afe --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs @@ -0,0 +1,168 @@ +using System.Net; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.Federation; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using Polly; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// ADR-0099 Amendment 10 against the pinned provider: the operator's listing, inspection, remove and disable through the +/// same confined admin client, which holds manage-identity-providers and nothing wider. Each case builds its own +/// brokers and removes them, so the realm the other cases share ends as it began. +/// +public sealed partial class FederationProviderTests +{ + private KeycloakFederationProvider OperatorAdapter() => + new(new KeycloakFederationOptions(Keycloak.Issuer), new Secrets(KeycloakFixture.FederationAdminSecret), new OperatorResilience(), + KeycloakHttp.CreateHandler(Keycloak.RootCertificate)); + + private sealed class OperatorResilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "federation"; + } + + private async Task OwnedBrokerAsync(KeycloakFederationProvider tenant, bool unreadable) + { + var owner = FederationKeycloakFixture.Owner(); + (await tenant.ApplyAsync(new(Oidc(owner, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)))) + .Should().Be(FederationProviderResult.Applied); + if (unreadable) + { + // Out of band, as an operator in the provider's own console might: the broker keeps its marker and loses its issuer. + using var admin = await Keycloak.CreateAdminClientAsync(); + var damaged = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + owner.Alias)).GetRawText())!.AsObject(); + damaged["config"]!.AsObject().Remove("issuer"); + (await admin.PutAsync("identity-provider/instances/" + owner.Alias, damaged)).Should().Be(HttpStatusCode.NoContent); + } + + return owner; + } + + [Fact] + public async Task The_operator_lists_the_realm_in_bounded_pages_and_classifies_owned_unreadable_and_foreign_instances() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var healthy = await OwnedBrokerAsync(tenant, unreadable: false); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + var unmarked = FederationKeycloakFixture.Owner(); + var manual = KeycloakFederationProfile.Representation(Oidc(unmarked, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)); + manual["config"]!.AsObject().Remove(KeycloakFederationProfile.OwnerKey); + (await admin.PostAsync("identity-provider/instances", manual)).Should().Be(HttpStatusCode.Created); + try + { + var owned = new Dictionary(StringComparer.Ordinal); + var ignored = 0; + for (var offset = 0; ; offset += 2) + { + var page = await op.ListAsync(offset, 2); + page.Status.Should().Be(FederationOperatorStatus.Ok, "the federation client's one role is enough to list"); + page.Scanned.Should().BeLessThanOrEqualTo(2); + foreach (var facts in page.Owned) owned[facts.Owner.Alias] = facts; + ignored += page.Ignored; + if (page.Scanned < 2) break; + } + + owned[healthy.Alias].Should().Match(facts => facts.Readable && facts.Conforms && facts.Enabled, + "the pinned provider masks the secret in the listing, so a healthy broker reads as conforming"); + owned[broken.Alias].Should().Match(facts => !facts.Readable && !facts.Conforms); + owned.Should().NotContainKey(unmarked.Alias, "an unmarked instance is never reported"); + ignored.Should().BeGreaterThanOrEqualTo(1); + owned.Values.Should().OnlyContain(facts => facts.Owner.Alias.StartsWith("lsf-", StringComparison.Ordinal)); + + var inspection = await op.InspectAsync(healthy.Alias); + (inspection.Status, inspection.Facts!.Owner.TenantId, inspection.MapperCount).Should().Be((FederationInspectionStatus.Owned, healthy.TenantId, 0)); + (await op.InspectAsync(unmarked.Alias)).Should().Be(FederationBrokerInspection.NotOwned); + (await op.InspectAsync(FederationKeycloakFixture.Owner().Alias)).Should().Be(FederationBrokerInspection.Absent); + } + finally + { + foreach (var alias in new[] { healthy.Alias, broken.Alias, unmarked.Alias }) + await admin.DeleteAsync("identity-provider/instances/" + alias); + } + } + + [Fact] + public async Task The_operator_removes_an_unreadable_orphan_and_the_provider_deletes_its_federated_links_and_nothing_else() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + var unmarked = FederationKeycloakFixture.Owner(); + var manual = KeycloakFederationProfile.Representation(Oidc(unmarked, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)); + manual["config"]!.AsObject().Remove(KeycloakFederationProfile.OwnerKey); + (await admin.PostAsync("identity-provider/instances", manual)).Should().Be(HttpStatusCode.Created); + var user = await admin.UserAsync("demo-learner@tenant-a.test"); + var userId = user.GetProperty("id").GetString()!; + (await admin.PostAsync($"users/{userId}/federated-identity/{broken.Alias}", new JsonObject { ["userId"] = "external-1", ["userName"] = "external-1" })) + .Should().Be(HttpStatusCode.NoContent, "a link exists to be lost"); + (await admin.GetAsync($"users/{userId}/federated-identity")).GetArrayLength().Should().BeGreaterThan(0); + try + { + // The tenant adapter will not touch an unreadable broker; the operator removes it on its marker alone. + (await tenant.DeleteAsync(broken)).Should().Be(FederationProviderResult.Foreign); + var stored = (await admin.GetAsync("identity-provider/instances/" + unmarked.Alias)).GetRawText(); + + (await op.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + (await admin.GetAsync("identity-provider/instances")).EnumerateArray() + .Select(instance => instance.GetProperty("alias").GetString()).Should().NotContain(broken.Alias); + (await admin.GetAsync($"users/{userId}/federated-identity")).EnumerateArray() + .Select(link => link.GetProperty("identityProvider").GetString()).Should().NotContain(broken.Alias, + "the provider deletes the federated links with the broker, which is why an account review is owed"); + (await admin.GetAsync($"users/{userId}")).GetProperty("id").GetString().Should().Be(userId, "the account itself stays"); + (await op.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + // Dirty control: a derived alias with no marker is never deleted, and stays as it was found. + var other = new FederationBrokerOwner(unmarked.TenantId, unmarked.ConnectionId, unmarked.Alias); + (await op.RemoveAsync(other)).Should().Be(FederationOperatorOutcome.NotOwned); + JsonNode.DeepEquals(JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + unmarked.Alias)).GetRawText()), + JsonNode.Parse(stored)).Should().BeTrue(); + } + finally + { + foreach (var alias in new[] { broken.Alias, unmarked.Alias }) + await admin.DeleteAsync("identity-provider/instances/" + alias); + } + } + + [Fact] + public async Task The_operator_disables_an_unreadable_broker_by_sending_back_what_the_provider_returned_with_only_enabled_changed() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + try + { + var before = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetRawText())!.AsObject(); + + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + var after = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetRawText())!.AsObject(); + after["enabled"]!.GetValue().Should().BeFalse(); + after["config"]!["clientSecret"]!.GetValue().Should().Be(FederationClientSecret.MaskLiteral, + "the provider kept the stored secret when it read its own mask back"); + // Nothing else moved: compare everything the provider computes on each read away. + foreach (var key in new[] { "internalId", "types" }) + { + before.Remove(key); + after.Remove(key); + } + + before["enabled"] = false; + JsonNode.DeepEquals(after, before).Should().BeTrue("only enabled differs from what the provider held"); + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + } + finally + { + await admin.DeleteAsync("identity-provider/instances/" + broken.Alias); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs index 818b5ac9..95fb698b 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs @@ -273,8 +273,11 @@ public async Task Every_admitted_request_targets_the_enumerated_routes_only() await adapter.ApplyAsync(new(State(enabled: true), null)); await adapter.ReadAsync(Owner); await adapter.DeleteAsync(Owner); + using var operatorAdapter = CreateOperator(provider); + await operatorAdapter.ListAsync(0, 2); var admitted = new[] { + "GET /admin/realms/learnstack/identity-provider/instances", "POST /realms/learnstack/protocol/openid-connect/token", "POST /admin/realms/learnstack/identity-provider/instances", "GET /admin/realms/learnstack/identity-provider/instances/" + Owner.Alias, @@ -283,12 +286,336 @@ public async Task Every_admitted_request_targets_the_enumerated_routes_only() "GET /admin/realms/learnstack/identity-provider/instances/" + Owner.Alias + "/mappers", }; provider.Requests.Select(request => request.Method + " " + request.Path).Distinct().Should().BeSubsetOf(admitted); - provider.Requests.Should().OnlyContain(request => request.Query.Length == 0); + // Only the listing carries a query, and it is exactly the bounded page: no search, no filter, no other member. + provider.Requests.Where(request => request.Query.Length != 0).Should().OnlyContain( + request => request.Method == "GET" && request.Path == "/admin/realms/learnstack/identity-provider/instances" + && request.Query == "?first=0&max=2&briefRepresentation=false"); } private static KeycloakFederationProvider Create(FakeKeycloak provider, string? secret = AdminSecret) => new(new KeycloakFederationOptions(Issuer), new Secrets(secret), new Resilience(), provider); + private static KeycloakFederationProvider CreateOperator(FakeKeycloak provider, string? secret = AdminSecret) => + new(new KeycloakFederationOptions(Issuer), new Secrets(secret), new OperatorResilience(), provider); + + private static FederationBrokerOwner OwnerOf(Guid? connection = null, TenantId? tenant = null) + { + var id = connection ?? Guid.CreateVersion7(); + return new(tenant ?? Tenant, id, FederationBrokerOwner.AliasPrefix + id.ToString("N")); + } + + private static FederationBrokerState StateFor(FederationBrokerOwner owner, bool enabled = true) => State(enabled) with { Owner = owner }; + + /// A broker as the provider stores it after a tenant's create: conforming, with its secret. + private static JsonObject Stored(FederationBrokerOwner owner, bool enabled = true) => + KeycloakFederationProfile.Representation(StateFor(owner, enabled), Fresh()); + + /// An owned broker the adapter cannot read: its issuer is gone, as when an operator edited it in the provider. + private static JsonObject Unreadable(FederationBrokerOwner owner, bool enabled = true) + { + var broker = Stored(owner, enabled); + broker["config"]!.AsObject().Remove("issuer"); + return broker; + } + + private static string Foreign() => "lsf-" + new string('0', 32); + + [Fact] + public async Task A_listing_classifies_owned_brokers_and_ignores_everything_else() + { + var provider = new FakeKeycloak(); + var healthy = OwnerOf(); + var broken = OwnerOf(); + var drifted = OwnerOf(); + provider.Brokers[healthy.Alias] = Stored(healthy); + provider.Brokers[broken.Alias] = Unreadable(broken, enabled: false); + provider.Brokers[drifted.Alias] = Stored(drifted); + provider.Brokers[drifted.Alias]["config"]!["extra"] = "not-in-the-profile"; + // Not LearnStack's: an alias nobody derived, a derived alias with no marker, and a marker for another connection. + provider.Brokers["corporate-sso"] = new JsonObject { ["alias"] = "corporate-sso", ["config"] = new JsonObject() }; + var unmarked = OwnerOf(); + provider.Brokers[unmarked.Alias] = new JsonObject { ["alias"] = unmarked.Alias, ["config"] = new JsonObject() }; + var mismatched = OwnerOf(); + var stolen = Stored(mismatched); + stolen["config"]![KeycloakFederationProfile.OwnerKey] = $"{Tenant.Value:D}:{Guid.CreateVersion7():D}"; + provider.Brokers[mismatched.Alias] = stolen; + using var adapter = CreateOperator(provider); + + var page = await adapter.ListAsync(0, 20); + + page.Status.Should().Be(FederationOperatorStatus.Ok); + page.Scanned.Should().Be(6); + page.Ignored.Should().Be(3); + page.Owned.Select(facts => facts.Owner.Alias).Should().BeEquivalentTo([healthy.Alias, broken.Alias, drifted.Alias]); + var byAlias = page.Owned.ToDictionary(facts => facts.Owner.Alias); + byAlias[healthy.Alias].Should().Match(facts => facts.Readable && facts.Conforms && facts.Enabled + && facts.Protocol == FederationBrokerProtocol.Oidc); + byAlias[broken.Alias].Should().Match(facts => !facts.Readable && !facts.Conforms && !facts.Enabled + && facts.Protocol == null); + byAlias[drifted.Alias].Should().Match(facts => facts.Readable && !facts.Conforms); + provider.Requests.Where(request => request.Path.Contains("identity-provider", StringComparison.Ordinal)) + .Select(request => request.Method + " " + request.Path + request.Query).Should().Equal( + "GET /admin/realms/learnstack/identity-provider/instances?first=0&max=20&briefRepresentation=false"); + page.ToString().Should().NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme"); + } + + [Fact] + public async Task A_listing_pages_by_offset_and_a_provider_that_ignores_the_page_size_is_unavailable() + { + var provider = new FakeKeycloak(); + var owners = Enumerable.Range(0, 5).Select(_ => OwnerOf()).OrderBy(owner => owner.Alias, StringComparer.Ordinal).ToArray(); + foreach (var owner in owners) provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + var first = await adapter.ListAsync(0, 2); + var second = await adapter.ListAsync(2, 2); + var last = await adapter.ListAsync(4, 2); + + (first.Scanned, second.Scanned, last.Scanned).Should().Be((2, 2, 1)); + first.Owned.Concat(second.Owned).Concat(last.Owned).Select(facts => facts.Owner.Alias).Should().Equal(owners.Select(owner => owner.Alias)); + + provider.ListIgnoresPaging = true; + (await adapter.ListAsync(0, 2)).Status.Should().Be(FederationOperatorStatus.Unavailable); + } + + [Theory] + [InlineData("object")] + [InlineData("5xx")] + public async Task A_listing_that_is_not_an_array_or_that_the_provider_fails_is_unavailable_and_returns_nothing(string defect) + { + var provider = new FakeKeycloak { ListDefect = defect }; + using var adapter = CreateOperator(provider); + + (await adapter.ListAsync(0, 5)).Should().Be(FederationBrokerPage.Unavailable); + } + + [Fact] + public async Task An_inspection_reports_absent_foreign_and_owned_with_the_mapper_count_of_a_readable_broker() + { + var provider = new FakeKeycloak { Mappers = 2 }; + var mine = OwnerOf(); + var broken = OwnerOf(); + provider.Brokers[mine.Alias] = Stored(mine); + provider.Brokers[broken.Alias] = Unreadable(broken); + provider.Brokers[Foreign()] = new JsonObject { ["alias"] = Foreign(), ["config"] = new JsonObject() }; + using var adapter = CreateOperator(provider); + + (await adapter.InspectAsync(OwnerOf().Alias)).Should().Be(FederationBrokerInspection.Absent); + (await adapter.InspectAsync(Foreign())).Should().Be(FederationBrokerInspection.NotOwned); + var owned = await adapter.InspectAsync(mine.Alias); + (owned.Status, owned.MapperCount, owned.Facts!.Owner.TenantId).Should().Be((FederationInspectionStatus.Owned, 2, Tenant)); + var unreadable = await adapter.InspectAsync(broken.Alias); + (unreadable.Status, unreadable.MapperCount, unreadable.Facts!.Readable).Should().Be((FederationInspectionStatus.Owned, 0, false)); + var notDerived = async () => await adapter.InspectAsync("not-a-derived-alias"); + await notDerived.Should().ThrowAsync("no route is built from an alias that is not the derived form"); + } + + [Fact] + public async Task A_remove_deletes_an_owned_broker_readable_or_not_and_confirms_its_absence() + { + var provider = new FakeKeycloak(); + var readable = OwnerOf(); + var broken = OwnerOf(); + provider.Brokers[readable.Alias] = Stored(readable); + provider.Brokers[broken.Alias] = Unreadable(broken); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(readable)).Should().Be(FederationOperatorOutcome.Applied); + (await adapter.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + provider.Brokers.Should().BeEmpty(); + provider.Requests.Count(request => request.Method == "DELETE").Should().Be(2); + // The provider is read before the delete and again after it, so the outcome is the absence and not a status. + provider.Requests.Where(request => request.Path.EndsWith(readable.Alias, StringComparison.Ordinal)) + .Select(request => request.Method).Should().Equal("GET", "DELETE", "GET"); + } + + [Fact] + public async Task A_remove_of_an_absent_broker_is_already_applied_and_sends_nothing() + { + var provider = new FakeKeycloak(); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(OwnerOf())).Should().Be(FederationOperatorOutcome.AlreadyApplied); + + provider.Requests.Where(request => !request.Path.EndsWith("/token", StringComparison.Ordinal)).Select(request => request.Method) + .Should().Equal("GET"); + } + + [Fact] + public async Task A_remove_never_touches_an_instance_whose_marker_is_not_the_owner_the_caller_proved() + { + var provider = new FakeKeycloak(); + var claimed = OwnerOf(); + var other = Stored(claimed); + other["config"]![KeycloakFederationProfile.OwnerKey] = $"{Guid.CreateVersion7():D}:{claimed.ConnectionId:D}"; + provider.Brokers[claimed.Alias] = other; + var unmarked = OwnerOf(); + provider.Brokers[unmarked.Alias] = new JsonObject { ["alias"] = unmarked.Alias, ["config"] = new JsonObject() }; + using var adapter = CreateOperator(provider); + + // Another tenant's marker on the claimed connection, and an unmarked derived alias. + (await adapter.RemoveAsync(claimed)).Should().Be(FederationOperatorOutcome.NotOwned); + (await adapter.RemoveAsync(unmarked)).Should().Be(FederationOperatorOutcome.NotOwned); + + provider.Brokers.Should().HaveCount(2); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + } + + [Theory] + [InlineData("refused", FederationOperatorOutcome.Refused)] + [InlineData("fails", FederationOperatorOutcome.Uncertain)] + public async Task A_delete_the_provider_refuses_changes_nothing_and_one_that_fails_after_it_was_sent_is_uncertain( + string kind, FederationOperatorOutcome expected) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { DeleteStatus = kind == "refused" ? HttpStatusCode.Conflict : HttpStatusCode.InternalServerError }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(expected); + + provider.Brokers.Should().ContainKey(owner.Alias); + } + + [Fact] + public async Task A_delete_the_provider_accepts_and_does_not_perform_is_uncertain_because_absence_is_the_confirmation() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { IgnoreDelete = true }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Uncertain); + } + + [Theory] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", true)] + [InlineData("019A1929-5450-7BBB-8DF1-516E8E002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019A1929-5450-7BBB-8DF1-516E8E002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502 ", false)] + [InlineData(" 019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501;019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929545 07bbb8df1516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("00000000-0000-0000-0000-000000000000:019a1929-5450-7bbb-8df1-516e8e002502", false)] // leakwatch:ignore + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-4bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502:x", false)] + [InlineData("", false)] + public void The_owner_marker_is_parsed_strictly_and_names_only_the_connections_own_derived_alias(string marker, bool valid) + { + var alias = "lsf-019a192954507bbb8df1516e8e002502"; + + KeycloakFederationProfile.TryOwnerFromMarker(marker, alias, out var owner).Should().Be(valid, marker); + + if (valid) + { + (owner.TenantId.Value, owner.ConnectionId).Should().Be( + (Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501"), Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502"))); + } + + // Another connection's alias never matches this marker, however well formed it is. + KeycloakFederationProfile.TryOwnerFromMarker( + "019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", "lsf-019a192954507bbb8df1516e8e002503", out _) + .Should().BeFalse(); + KeycloakFederationProfile.TryOwnerFromMarker(null, alias, out _).Should().BeFalse(); + KeycloakFederationProfile.TryOwnerFromMarker("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", null, out _) + .Should().BeFalse(); + } + + [Fact] + public async Task A_provider_that_cannot_be_reached_before_any_change_is_sent_is_unavailable_and_not_uncertain() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { TokenDefect = "extra-role" }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + (await adapter.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + provider.Requests.Select(request => request.Method).Should().NotContain(["DELETE", "PUT"]); + } + + [Fact] + public async Task A_disable_sends_back_what_the_provider_returned_with_only_enabled_changed_and_keeps_the_stored_secret() + { + var provider = new FakeKeycloak(); + var broken = OwnerOf(); + provider.Brokers[broken.Alias] = Unreadable(broken, enabled: true); + var before = provider.Brokers[broken.Alias].DeepClone().AsObject(); + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + var after = provider.Brokers[broken.Alias]; + after["enabled"]!.GetValue().Should().BeFalse(); + // Nothing else moved, the computed members were never sent, and the secret the provider holds is the one it held. + before["enabled"] = false; + JsonNode.DeepEquals(after, before).Should().BeTrue("only enabled differs from what the provider held"); + after.ContainsKey("internalId").Should().BeFalse(); + after.ContainsKey("types").Should().BeFalse(); + after["config"]!["clientSecret"]!.GetValue().Should().Be(TenantSecret); + var put = provider.Requests.Single(request => request.Method == "PUT"); + put.Body.Should().NotContain(TenantSecret, "the secret travels as the provider's own mask, never as a value this adapter read"); + put.Body.Should().Contain("**********"); + } + + [Fact] + public async Task A_disable_of_a_disabled_broker_sends_nothing_and_one_that_is_not_the_proved_owners_is_never_written() + { + var provider = new FakeKeycloak(); + var off = OwnerOf(); + provider.Brokers[off.Alias] = Unreadable(off, enabled: false); + var claimed = OwnerOf(); + var other = Stored(claimed); + other["config"]![KeycloakFederationProfile.OwnerKey] = $"{Guid.CreateVersion7():D}:{claimed.ConnectionId:D}"; + provider.Brokers[claimed.Alias] = other; + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(off)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + (await adapter.DisableAsync(claimed)).Should().Be(FederationOperatorOutcome.NotOwned); + (await adapter.DisableAsync(OwnerOf())).Should().Be(FederationOperatorOutcome.Refused, "there is nothing to disable"); + + provider.Requests.Should().NotContain(request => request.Method == "PUT"); + } + + [Theory] + [InlineData("fails", FederationOperatorOutcome.Uncertain)] + [InlineData("refused", FederationOperatorOutcome.Refused)] + [InlineData("ignored", FederationOperatorOutcome.Uncertain)] + public async Task A_disable_is_confirmed_by_reading_the_instance_again(string kind, FederationOperatorOutcome expected) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak + { + WriteStatus = kind == "fails" ? HttpStatusCode.InternalServerError : kind == "refused" ? HttpStatusCode.Conflict : null, + IgnorePut = kind == "ignored", + }; + provider.Brokers[owner.Alias] = Unreadable(owner, enabled: true); + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(owner)).Should().Be(expected); + + provider.Brokers[owner.Alias]["enabled"]!.GetValue().Should().BeTrue("the provider did not take the change"); + } + + [Fact] + public async Task The_operator_port_never_returns_a_secret_or_provider_text() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { Mappers = 1 }; + provider.Brokers[owner.Alias] = Stored(owner); + using var adapter = CreateOperator(provider); + + var results = new object?[] + { + await adapter.ListAsync(0, 5), await adapter.InspectAsync(owner.Alias), await adapter.CountMappersAsync(owner), + await adapter.DisableAsync(owner), await adapter.RemoveAsync(owner), + }; + + string.Join('|', results.Select(result => result?.ToString())).Should() + .NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme").And.NotContain("idp.example.com"); + } + private static FederationClientSecret Fresh() => FederationClientSecret.TryCreate(TenantSecret, out var secret) ? secret! : throw new InvalidOperationException(); @@ -316,6 +643,12 @@ private sealed class Resilience : IProviderResilience public string PortName => "federation"; } + private sealed class OperatorResilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "federation"; + } + internal sealed record Recorded(string Method, string Path, string Query, string Body); /// A scripted provider holding brokers by alias, as the pinned Admin REST API stores and masks them. @@ -326,6 +659,11 @@ private sealed class FakeKeycloak : HttpMessageHandler internal int Mappers { get; set; } internal string? TokenDefect { get; init; } internal HttpStatusCode? WriteStatus { get; init; } + internal HttpStatusCode? DeleteStatus { get; init; } + internal string? ListDefect { get; init; } + internal bool ListIgnoresPaging { get; set; } + internal bool IgnorePut { get; init; } + internal bool IgnoreDelete { get; init; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -345,6 +683,16 @@ protected override async Task SendAsync(HttpRequestMessage Brokers[alias] = created; return new(HttpStatusCode.Created); } + if (request.Method == HttpMethod.Get && path == prefix) + { + if (ListDefect == "5xx") return new(HttpStatusCode.InternalServerError); + if (ListDefect == "object") return Json(HttpStatusCode.OK, new JsonObject()); + var query = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query); + var page = Brokers.Values.OrderBy(broker => broker["alias"]!.GetValue(), StringComparer.Ordinal) + .Skip(int.Parse(query["first"]!)); + if (!ListIgnoresPaging) page = page.Take(int.Parse(query["max"]!)); + return Json(HttpStatusCode.OK, new JsonArray([.. page.Select(View)])); + } var rest = path[(prefix.Length + 1)..]; var mappers = rest.EndsWith("/mappers", StringComparison.Ordinal); var key = mappers ? rest[..^"/mappers".Length] : rest; @@ -352,15 +700,12 @@ protected override async Task SendAsync(HttpRequestMessage if (request.Method == HttpMethod.Get) { if (!Brokers.TryGetValue(key, out var broker)) return new(HttpStatusCode.NotFound); - var view = broker.DeepClone().AsObject(); - if (view["config"]!.AsObject().ContainsKey("clientSecret")) view["config"]!["clientSecret"] = "**********"; - view["internalId"] = Guid.NewGuid().ToString(); - view["types"] = new JsonArray("USER_AUTHENTICATION"); - return Json(HttpStatusCode.OK, view); + return Json(HttpStatusCode.OK, View(broker)); } if (request.Method == HttpMethod.Put) { if (WriteStatus is { } status) return new(status); + if (IgnorePut) return new(HttpStatusCode.NoContent); if (!Brokers.TryGetValue(key, out var existing)) return new(HttpStatusCode.NotFound); var replacement = JsonNode.Parse(body)!.AsObject(); var config = replacement["config"]!.AsObject(); @@ -370,10 +715,24 @@ protected override async Task SendAsync(HttpRequestMessage return new(HttpStatusCode.NoContent); } if (request.Method == HttpMethod.Delete) + { + if (DeleteStatus is { } deleteStatus) return new(deleteStatus); + if (IgnoreDelete) return new(HttpStatusCode.NoContent); return new(Brokers.TryRemove(key, out _) ? HttpStatusCode.NoContent : HttpStatusCode.NotFound); + } return new(HttpStatusCode.MethodNotAllowed); } + /// What the provider returns for a stored broker: the secret masked and the computed members added. + private static JsonNode View(JsonObject broker) + { + var view = broker.DeepClone().AsObject(); + if (view["config"]!.AsObject().ContainsKey("clientSecret")) view["config"]!["clientSecret"] = "**********"; + view["internalId"] = Guid.NewGuid().ToString(); + view["types"] = new JsonArray("USER_AUTHENTICATION"); + return view; + } + private static HttpResponseMessage Json(HttpStatusCode status, JsonNode value) => new(status) { Content = new StringContent(value.ToJsonString(), Encoding.UTF8, "application/json") }; diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 3492ffcb..32e7c42e 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -92,11 +92,14 @@ public async Task The_Rebind_Operation_Is_Admitted_Only_For_The_Identity_Authori [InlineData("platform.delivery.inspect", "platform.delivery.read")] [InlineData("platform.delivery.replay", "platform.delivery.write")] [InlineData("platform.delivery.reset", "platform.delivery.write")] - public async Task A_Recovery_Operation_Is_Admitted_Only_For_Its_Own_Delivery_Permission(string slug, string permission) + [InlineData("platform.federation.report", "platform.federation.read")] + [InlineData("platform.federation.remove", "platform.federation.admin")] + [InlineData("platform.federation.disable", "platform.federation.admin")] + public async Task An_Operator_Operation_Is_Admitted_Only_For_Its_Own_Permission(string slug, string permission) { - // ADR-0103 Decision table: inspecting needs platform.delivery.read, and the two acts need platform.delivery.write. The pair - // is pinned both ways: the table says which key each operation binds, and no other Platform key, the other - // delivery key and the killswitch key included, admits it. + // ADR-0103 Decision table and ADR-0099 Amendment 10: a read needs the read key and an act needs the write or + // admin key. The pair is pinned both ways: the table says which key each operation binds, and no other + // Platform key, the sibling key and the killswitch key included, admits it. var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == slug); operation.Permission.Key.Should().Be(permission); @@ -356,6 +359,15 @@ public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() catalogue.TryGetOffPath(operation.AuditSlug, out var declared) .Should().BeTrue($"'{operation.AuditSlug}' must be declared so its result row can be recorded"); declared.OperationClass.Should().Be(OperationClass.Must); + + // An operation with a checkpoint writes an intent row on its attempt slug, which must be declared too. + if (operation.AttemptAuditSlug is { } attempt) + { + catalogue.TryGetOffPath(attempt, out var declaredAttempt) + .Should().BeTrue($"'{attempt}' must be declared so its intent row can be recorded"); + declaredAttempt.OperationClass.Should().Be(OperationClass.Must); + declaredAttempt.OperationType.Should().Be(OperationType.SecurityEvent); + } } } @@ -364,6 +376,11 @@ public void The_Registry_Is_Closed_And_Every_Operation_Names_A_Registered_Platfo { PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.AuditSlug); PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.ReasonSlug); + + // An attempt slug is its own row kind: no two operations share one and none equals any result slug. + var attempts = PlatformOperations.All.Select(operation => operation.AttemptAuditSlug).OfType().ToArray(); + attempts.Should().OnlyHaveUniqueItems(); + attempts.Should().NotIntersectWith(PlatformOperations.All.Select(operation => operation.AuditSlug)); foreach (var operation in PlatformOperations.All) { PlatformPermissions.TryGet(operation.Permission.Key, out var registered).Should().BeTrue(); diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index 06ef6642..d7d4f510 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -271,6 +271,13 @@ dead-lettered row is a sibling seam, `WriteOperatorRecoveryAsync` carries the admitted operator and the fence before and after, the row names the real event tenant with no actor and no ticket, and the outbox role needs no new policy arm because it bypasses row security and already holds `INSERT`. +The platform scope's intent seam, `WritePlatformOperatorIntentAsync` +([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), is the sibling for an +operator act whose effect is outside the database: the scope handle's checkpoint writes +the intent row on the operation's attempt slug with the outcome `indeterminate`, commits +it, and only then lets the provider be called; the result row follows on a fresh +transaction. An effect that fails afterwards leaves the intent row standing, and the +result row is refused before an intent that its operation declares. Absent optional causal IDs are valid and do not alone invalidate the stored trace. Closed terminal values use bounded metadata; `Reason` stays for platform entry. Audit failure retains terminal work for retry without delivery; uncertain COMMIT diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index 029d4087..df2ac851 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1329,3 +1329,35 @@ Accepted [ADR-0101](0101-platform-operator-authority.md), The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +## Amendment 18 — Platform scope intent checkpoint (2026-11-20) + +Accepted [ADR-0099](0099-confined-tenant-federation.md) Amendment 10 gives two operator +acts an effect outside the database, in the identity provider: a removal and a disable +of a broker. The maintainer approved this seam before it was written, because the +platform scope of Amendment 17 writes one result row and closes at commit, which leaves +nothing durable before such an effect. [ADR-0099](0099-confined-tenant-federation.md) +Amendment 11 records the implementation. + +- **One new witness-bound write, the fifteenth.** `IAuditStore.WritePlatformOperatorIntentAsync` + writes the intent row of a platform-scope act on its `PlatformOperation.AttemptAuditSlug`, + with the outcome `indeterminate`, the same closed reason, correlation id and + `metadata.operator` as the result row, the actor NULL and the class MUST. Like the + result method it is bound to the admission, takes the real target tenant, refuses a + ticket on a tenant-readable row and refuses the identity module's own rows. An + operation with no attempt slug, or one that does not enter the platform scope (the + offline rebind, whose intent has its own method), presents none. +- **A checkpoint on the scope handle.** `IPlatformAdminScopeHandle.WriteIntentAsync` + writes that row on the work transaction, commits it, and continues the scope in a fresh + transaction on the same connection. It is allowed once, only for an operation that + declares an attempt slug, and the result row of such an operation is refused before it. + A failure to write or to commit the intent row throws `AuditWriteFailedException` and + the effect must not start; an effect that fails afterwards leaves the intent row + standing, as § 10 requires of the entry row. The scope still ends at the result row and + the commit, or by disposal, which rolls back whatever followed the checkpoint. +- **Declared like every off-path slug.** The attempt slugs are declared off-path + MUST/SecurityEvent in the Tenancy catalogue source beside the entry and result slugs, + and the scope refuses entry when any of them is undeclared. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index 734e7336..d6864155 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1110,6 +1110,12 @@ grow from four to five by one paged listing of identity-provider instances. and a completion row after it, as Amendment 2 does for the tenant path, under the real tenant, with a closed reason slug, `metadata.operator` and a follow-up note that an account review is owed. A lost completion is found by the next report. + + > **Erratum (2026-11-20, Amendment 11 item 3).** Amendment 2 is the Keycloak pin and + > has no intent-first pattern; the pattern the tenant path follows is the Decision's + > § Intent-first operations. The platform scope could not write the intent row before + > a provider call, so the seam it needed is + > [ADR-0044 Amendment 18](0044-audit-write-path.md). 7. **Account review.** It is a runbook step. No LearnStack credential may enumerate or remove realm users (Decision Q1), Keycloak keeps link events for seven days and no owner notification channel exists before Phase 08a. @@ -1118,3 +1124,84 @@ grow from four to five by one paged listing of identity-provider instances. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 11 — Federation operator steps: implementation contract (2026-11-20) + +Step 5 of the platform-authority packet implements Amendment 10. Each item below fixes +something the record left open or states where the code corrected it. The maintainer +approved items 3 and 6 before they were written. None of them changes Amendment 10's +choice of option, its two permissions, its classes or its refusal to enumerate or remove +realm users. + +1. **Where the code lives.** `IFederationOperator` sits beside the tenant provider port + and is held by the operator's owner, `FederationBrokerOperations` (Identity + Infrastructure), and by the adapter that implements it, the operator half of the + same Keycloak class. A second instance of that class is built with its own resilience + pipeline of the fixed shape, so a sweep cannot starve a tenant's calls. The routes are + `GET /api/platform/v1/federation/brokers`, `POST .../{alias}/remove` and + `POST .../{alias}/disable`, behind the keys [ADR-0101](0101-platform-operator-authority.md) + § 5 fixed, `platform.federation.read` and `platform.federation.admin`, and each runs + the gate first. +2. **The grant is an Identity-chain migration.** `federation_connections` is created in + the Identity chain, which runs after the Platform chain, so the column grant of item + 5 is a hand-written forward-only Identity migration. The raw-reader census of + Standard 21 admits the operator's one statement beside the three tenant readers, + pinned whole: it reads by primary key through the four granted columns and sees + tombstones, which the shared live predicate would hide. +3. **Two rows around the provider call.** The tenant path's pattern is the Decision's + § Intent-first operations, not Amendment 2. The platform scope could write one result + row and no row before a provider call, so the seam is the scope handle's checkpoint + and a fifteenth `IAuditStore` write + ([ADR-0044 Amendment 18](0044-audit-write-path.md)): one admission, an intent row + with the outcome `indeterminate` on `platform.federation.remove_attempt` or + `platform.federation.disable_attempt`, committed before the provider call, and a + completion row on `platform.federation.remove` or `platform.federation.disable` with + the outcome and whether an account review is owed. The rows name the tenant the owner + marker names, never the platform sentinel, even when no `tenants` row exists, and + carry closed tokens only: no display name, issuer, configuration or secret, and no + ticket. An absent broker on a remove, a disabled broker on a disable, a refusal for a + live row, an unowned alias and a provider that is unavailable before any change + write no tenant row: the scope's entry row records the call, and nothing is known to + name a tenant. A provider that fails after a change was sent is recorded `uncertain` + in the completion row and answered `503` with the reason `outcome_unknown`. +4. **The report.** One call is one page of the provider's listing, from an opaque offset + cursor bound to the operation, 1 to 100 instances, in full representation. The realm + is read first and the rows second, because a tenant writes its row before it creates + the broker; the scope is entered before both, so the admission is spent fresh. A + broker is reported when its row is absent or a tombstone (`orphan`), when its + marker proves it LearnStack's and its representation does not read as an admitted + shape (`unreadable_owned`), or when it reads and differs from the fixed profile or + carries a mapper (`nonconforming`); a mapper is drift only a mapper read shows, so + the mappers of what looks healthy are counted one after another within the page's + ten seconds and an unread count is reported unknown, never zero. An instance with no + marker, a marker that does not parse strictly to a tenant and a connection whose + derived alias it is, or a marker that disagrees with its row about the tenant, is + counted and never named. +5. **The live-row refusal is literal.** A remove refuses while a live row names the + broker, for an unreadable owned broker as well. Such a broker is disabled by the + operator and removed by the tenant's own Delete, which this step leaves as the + residual Amendment 10 item 3 implies. +6. **Disable sends back what the provider returned.** An unreadable owned broker cannot + be rebuilt from the fixed profile, so the operator disable is the one provider write + that does not build its body from the allow-list: it reads the instance, proves the + marker, drops the two members the provider computes on every read, sets `enabled` to + false and writes the rest back, with the secret as the provider's own mask, which the + provider reads as "keep the stored value" (Amendment 3). It is confirmed by reading + the instance again. This is a bounded exception to the fixed broker profile, limited + to the operator port, and Amendment 9 item 5's "repair" is read as this disable. + "One the tenant cannot reach" means an unreadable or nonconforming owned broker; a + tenant that is archived or deleted with a live row is P03-10's. +7. **Verified against the pinned provider.** The federation admin client's one role, + `manage-identity-providers`, lists instances, the listing carries each member and the + owner marker with the secret masked, `first` and `max` page it, a write of the + returned representation with `enabled` false is accepted, and deleting a broker + deletes its federated links and leaves the account. So the admitted routes grow by + the one paged listing of Amendment 10, and "adds no realm authority" holds. The + route census admits the listing's collection route with its one exact query. +8. **Residual.** There is still no provider-side fence, so a tenant create that lands + after a sweep produces a new orphan, which the next report finds, and the disable is a + read and a write the tenant's own write can interleave with; the tenant's next readback + detects the drift. The account review stays a runbook step. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/glossary.md b/docs/glossary.md index 4ca3a1f7..65984e96 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -14,6 +14,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | | **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | | **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act and an inspection run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | +| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, and cannot list or remove a realm user, so the account review a remove owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), [runbook](runbooks/federation-operator.md)). | | **Operator recovery** | The operator's inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and its two fenced transitions: a **replay** resets one dead-lettered subscriber delivery and a **producer reset** resets one retry-exhausted outbox row, which renews its six-attempt budget. Each transition carries a **fence**, the state the operator read at inspection (for a replay the replay count, the dead-letter instant to the microsecond and the terminal reason; for a reset the attempts and the instant), and is refused with a stale-fence conflict when the row no longer shows it. It writes a MUST audit row on the same transaction. Job recovery and a dashboard do not exist ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md), [runbook](runbooks/operator-recovery.md)). | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index 9cb680ab..8e363234 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -769,6 +769,47 @@ entered on the re-authentication form. with unchanged provenance ([Security § Federation host binding](../../standards/11-security.md#federation-host-binding)). +### Operator federation steps (P03-9 Step 5) + +[ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md) and +[Amendment 11](../../decisions/0099-confined-tenant-federation.md) give the platform +operator a report, a remove and a disable of the identity-provider brokers a tenant's +federation left orphaned, unreadable or nonconforming. The operator's procedure is the +[federation operator runbook](../../runbooks/federation-operator.md); this section is +the module's side of it. + +- **Two ports, one adapter.** `IFederationOperator` (SharedKernel) sits beside + `IFederationProvider` and is held only by `FederationBrokerOperations` (Identity + Infrastructure) and the operator half of the Keycloak adapter, never by the tenant + runner. The operator adapter is a second instance with its own resilience pipeline, + on the same confined client, so a sweep cannot starve a tenant's calls. Its + fail-closed default reports every call unavailable until the federation admin client + is configured. +- **One service, three acts.** `FederationBrokerOperations` implements + `IFederationBrokerOperations` (SharedKernel). It consumes the operator's + `PlatformAdmission` in the platform scope, reads the realm page first and the + connection rows second, and classifies each marked broker as `orphan`, + `unreadable_owned` or `nonconforming`. A broker whose marker does not parse strictly + to a tenant and connection whose derived alias it is, or whose marker disagrees with + its row about the tenant, is counted and never named. +- **Rows read.** `learnstack_platform` holds `SELECT` of `id`, `tenant_id`, `state` and + `deleted_at` on `federation_connections` and nothing more + ([Standard 05](../../standards/05-database.md#federation-operator-projection)); the + Identity migration `20261120160000_grant_platform_federation_projection` carries it. + The one statement that reads the table as the platform role reads by primary key and + sees tombstones, which `FederationConnectionReads.Live` hides from the tenant paths. +- **Two rows around the provider call.** A remove or a disable writes an intent row on + `platform.federation.remove_attempt` or `platform.federation.disable_attempt` at the + platform scope handle's checkpoint + ([ADR-0044 Amendment 18](../../decisions/0044-audit-write-path.md)), commits it, calls + the provider, and writes the completion row on `platform.federation.remove` or + `platform.federation.disable`. Both name the tenant the owner marker names and carry + closed tokens only. The audit matrix is in + [Tenancy's audit.md](../tenancy/audit.md), whose catalogue holds these slugs. +- **No realm user is read or removed.** A remove deletes the broker and the provider + deletes its federated links; the account review is the realm administrator's, by + runbook. + ## Entity-relationship diagram ```mermaid diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index fc61f00b..5086243d 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -275,3 +275,13 @@ baseline provider-credential-rotation row covers `rotate_secret`. no personal data. `GetPublicSignInQuery` is an explicit Off public read: it is anonymous and returns only the host tenant's Active alias and display name ([Standard 18](../../standards/18-audit-coverage.md)). + +The platform operator's report, remove and disable of orphaned or broken brokers +([ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md)) are not +Identity operations and are not in this table. They run at the platform scope, outside +the request pipeline, and write the off-path slugs `platform.federation.report`, +`platform.federation.remove_attempt`, `platform.federation.remove`, +`platform.federation.disable_attempt` and `platform.federation.disable`, which +[Tenancy's audit matrix](../tenancy/audit.md) classifies and Tenancy's catalogue source +registers. Their rows name the tenant the owner marker names and entity +`FederationConnection`. diff --git a/docs/modules/identity/providers.md b/docs/modules/identity/providers.md index 1c5fdd42..9924cd8e 100644 --- a/docs/modules/identity/providers.md +++ b/docs/modules/identity/providers.md @@ -77,6 +77,8 @@ The adapter builds every route in `KeycloakFederationRoutes`, and only these: | `PUT admin/realms/learnstack/identity-provider/instances/{alias}` | Full-state replace of an owned broker. Refused without a call when it would change the stored issuer or SAML entity identifier, or, without a fresh secret, the token endpoint, client identifier or client authentication ([ADR-0099 Amendment 5](../../decisions/0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14)) | | `DELETE admin/realms/learnstack/identity-provider/instances/{alias}` | Delete of an owned broker; an absent alias is already deleted | | `GET admin/realms/learnstack/identity-provider/instances/{alias}/mappers` | Mapper count for the readback; any mapper is drift | +| `GET admin/realms/learnstack/identity-provider/instances?first={n}&max={m}&briefRepresentation=false` | The operator's bounded page of the realm's listing ([Operator access](#operator-access)); no other query member | +| `GET admin/realms/learnstack/identity-provider/instances/{alias}` (operator) | The operator's read of one derived alias before it knows whose it is; the tenant adapter reads only its own owner's alias | The `{alias}` is only `lsf-` and the connection identifier's 32 lowercase hexadecimal characters, from `FederationBrokerOwner`. No other alias, user, flow, realm, client or @@ -88,6 +90,37 @@ records the decision). The pinned 26.7.5 parser was observed to return `validateSignature=true` for metadata whose `WantAuthnRequestsSigned` is false; the adapter never forwards its output either way. +### Operator access + +[ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md) and +Amendment 11 give the platform operator four acts on this realm through the same +confined client, `manage-identity-providers`, and no wider role: a **report** (the +listing joined to the registry), an **inspection** of one alias, a **remove** of an +owner-marked broker that the registry no longer holds live, and a **disable** of an +owner-marked broker at the provider only. + +- The operator holds `IFederationOperator`, a port beside `IFederationProvider` that + the tenant runner never holds; its adapter is the same internal sealed class with its + own resilience pipeline. +- A broker is the platform's to touch only when its marker parses strictly + (`lsf-` alias, `{tenant:D}:{connection:D}`) **and** the alias is the connection's + derived one. An unmarked instance, a foreign marker and an alias that is not + LearnStack's are counted and never named. +- A remove deletes by alias and confirms the alias is gone. The provider deletes the + federated links of that broker with it and keeps the accounts; the runbook owes an + account review. +- A disable is the one provider write that is not the fixed profile: the broker can be + unreadable (that is why it is disabled rather than rewritten), so the adapter reads + the raw representation, sets `enabled=false` and puts it back with the secret mask + the provider returned. Nothing else in the representation changes, and the pinned + provider keeps the stored secret when it reads its own mask back. +- A report is one page, no larger than the API's cursor limit, and its cursor is the + provider offset the next page starts at. A listing the provider cannot answer reports + `unavailable`, never an empty realm. +- Federation destinations, secrets, display names, issuers and configuration values + never cross the operator port: facts are an alias, an owner, readable, conforming, + enabled, protocol and a mapper count. + ### Ownership and readback - Every write carries `config.learnstackOwner` = `{tenantId}:{connectionId}`. The diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 79a02a84..5ce0ba89 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -149,6 +149,11 @@ unmarked row is one a shipped command already raises. | outbox, delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | | delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | +| `federation_connections` and the realm's identity-provider instances | `platform.federation.report` `(off-path)` | **MUST** (`security-event`) | An operator's report of the brokers that are orphaned, unreadable or nonconforming ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `federation_report` is this slug's, with the operator attribution and ticket in `metadata.operator`; the scope reads and changes nothing, so it writes no result row, and it does not say which page was read | +| `federation_connections` | `platform.federation.remove_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's removal of an orphaned or unreadable owned broker, written at the platform scope handle's checkpoint and committed before the provider call ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 11). Outcome `indeterminate`, under the tenant the owner marker names (never the platform sentinel, even when no `tenants` row exists), no actor, the closed reason `federation_remove`, the operator attribution in `metadata.operator`, no ticket because a tenant can read the row, and `before_state` holding the broker's classes and the connection row's state; the entity is the connection | +| `federation_connections` | `platform.federation.remove` `(off-path)` | **MUST** (`security-event`) | The completion row of that removal, written through the witness-bound result method on the work transaction that follows the checkpoint, in the same shape with the outcome `success` and `after_state` holding the closed outcome (`applied`, `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`) and whether an account review is owed, because the provider deletes the federated links with a broker. A lost completion leaves the intent row alone, which the next report resolves | +| `federation_connections` | `platform.federation.disable_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's disable of a nonconforming or unreadable owned broker, in the shape of the removal's intent under the closed reason `federation_disable` | +| `federation_connections` | `platform.federation.disable` `(off-path)` | **MUST** (`security-event`) | The completion row of that disable, in the shape of the removal's completion; the provider is changed and the tenant's row is left to its next readback ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10 item 4) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | | `Tenant` | `tenancy.tenant.create` | **MUST** | The root of a customer's data; its existence is a contractual fact | | `Tenant` | `tenancy.tenant.change_status` `(planned)` | **MUST** | Suspension withdraws access; an operator must be able to say who and when | diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index f1d4962f..7ea734c8 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -111,7 +111,7 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi the widening it needs is an ADR's to make, not a migration's. The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) -is separate and never assignable to a Role. Tenancy owns four keys in it today. +is separate and never assignable to a Role. Tenancy owns six keys in it today. `platform.killswitch.write` authorizes the operator surface to toggle `platform_killswitches`. `platform.tenant.write` authorizes the operator's production tenant provisioning and host mapping @@ -126,8 +126,16 @@ asynchronous work and its two fenced recovery transitions ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)): they run in the platform scope and on the dispatcher's outbox role, not through the pipeline, and write the off-path slugs `platform.delivery.inspect`, `platform.delivery.replay` and -`platform.delivery.reset` in [Tenancy's audit matrix](audit.md). Operators hold the keys -by configuration ([Standard 19](../../standards/19-permissions.md)). +`platform.delivery.reset` in [Tenancy's audit matrix](audit.md). +`platform.federation.read` and `platform.federation.admin` authorize the operator's +report of orphaned, unreadable and nonconforming identity-provider brokers and its +remove and disable of one +([ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md), +[runbook](../../runbooks/federation-operator.md)): they run in the platform scope, not +through the pipeline, and write the off-path slugs `platform.federation.report`, +`platform.federation.remove_attempt`, `platform.federation.remove`, +`platform.federation.disable_attempt` and `platform.federation.disable`. Operators hold +the keys by configuration ([Standard 19](../../standards/19-permissions.md)). ## Bounded human administration contract diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 5db58fa2..2d527808 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 937 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,008 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -522,6 +522,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20)](#p03-9-step-4--operator-recovery-of-asynchronous-work-2026-11-20) — 59 lines - [P03-9 Step 4 — review round 1 and its fixes (2026-11-20)](#p03-9-step-4--review-round-1-and-its-fixes-2026-11-20) — 49 lines - [P03-9 Step 4 — review round 2 and its fixes (2026-11-20)](#p03-9-step-4--review-round-2-and-its-fixes-2026-11-20) — 39 lines + - [P03-9 Step 5 — federation operator steps (2026-11-20)](#p03-9-step-5--federation-operator-steps-2026-11-20) — 71 lines @@ -25116,3 +25117,74 @@ tie-break and the executor kind of the result writer. - **The platform role's loss of `SELECT` on the correlation and actor columns of `outbox_messages`.** It constrains P03-10 and Phase 11, which need a named grant or another principal for a predicate that reads them; Phase 11's text now says so. + +### P03-9 Step 5 — federation operator steps (2026-11-20) + +Step 5 delivers [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md): +a report, a remove and a disable of the identity-provider brokers a tenant's federation +left orphaned, unreadable or nonconforming, and no way to list or remove a realm user. +Amendment 11 records where the code corrected Amendment 10, and +[ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md) records the audit seam it +needed. The maintainer chose the audit shape (a checkpoint on the platform scope handle, +a fifteenth `IAuditStore` write) and accepted the bounded raw round trip of the disable +before any code was written. + +Delivered: + +- **The seam.** `platform.federation.read` and `platform.federation.admin`; the three + operations `platform.federation.report`, `platform.federation.remove` and + `platform.federation.disable`, the last two with attempt slugs + (`platform.federation.remove_attempt`, `platform.federation.disable_attempt`) declared + off-path MUST/SecurityEvent in the Tenancy catalogue. +- **The audit checkpoint.** `IPlatformAdminScopeHandle.WriteIntentAsync` writes the + intent row on the attempt slug with the outcome `indeterminate`, commits it, and + continues in a fresh transaction on the same connection, once, and a result row is + refused before it. `IAuditStore.WritePlatformOperatorIntentAsync` is the fifteenth + write, witness-bound like the result method, refusing a ticket on a tenant-readable + row and the identity module's own rows. +- **The ports.** `IFederationOperator` beside the tenant provider port, with a + fail-closed default and a second adapter instance with its own resilience pipeline; + `IFederationBrokerOperations` with its closed result types, owned by + `FederationBrokerOperations` in Identity Infrastructure. The adapter's route census + grows from four builders to six (a bounded page of the listing and a read by derived + alias), and the owner marker is parsed strictly: an `lsf-` alias and a + `{tenant:D}:{connection:D}` marker that round-trips. +- **The rows read.** An Identity-chain forward-only migration, + `20261120160000_grant_platform_federation_projection`, grants `learnstack_platform` + `SELECT` of four columns of `federation_connections`; the raw-reader census admits the + operator's one statement, pinned whole. +- **The routes.** `GET /api/platform/v1/federation/brokers`, and `POST` of + `.../{alias}/remove` and `.../{alias}/disable`, gate first, served in `platform-v1`; + the counter `learnstack_platform_operator_federation_total`. +- **Documents.** The runbook `federation-operator.md`, ADR-0044 Amendment 18, ADR-0099 + Amendment 11 with an erratum beside the item that cited a pattern Amendment 2 does not + hold, Standards 04, 05, 10, 11, 18, 19, 20 and 21, Architecture 31, the Identity and + Tenancy module documents, the runbooks index, operator access and the glossary. + +Where the code corrected Amendment 10 (ADR-0099 Amendment 11): + +- The intent-first pattern is the Decision's § Intent-first operations, not + Amendment 2, which is the Keycloak pin. +- A remove refuses while a live row names the broker, an unreadable owned broker + included: such a broker is disabled by the operator and deleted by the tenant. +- The disable of an unreadable broker is the one provider write that sends back what the + provider returned, with only `enabled` changed, because the fixed profile cannot be + rebuilt from a representation that does not read. +- A mapper is drift only a mapper read shows, so the mappers of a healthy broker are + counted one after another within the page's ten seconds and an unread count is + reported unknown, never zero. +- The report reads the realm first and the rows second, because a tenant writes its row + before it creates the broker. + +Proof, against real PostgreSQL as each role and the pinned Keycloak 26.7.5: the +listing's pages, the three classes and the foreign, unmarked and mismatched instances +that are counted and never named; a remove of an unreadable orphan that deletes the +federated links and leaves the account and a control broker byte-identical; a disable +that changes `enabled` alone; the intent row committed before the provider call and +surviving a failure after it; no tenant row for an absent broker, an unowned alias, a +live row or an unavailable provider; the result row refused before the intent, the +intent refused twice and for an operation with no attempt slug; the exact column grant +and the refused columns; each route's statuses, bodies and permission held alone; and +the route, port-holder and raw-reader censuses with their planted violations. A +mutation sweep over the new guards killed every mutant but one equivalent: a marker +length check that the marker's round trip makes redundant. diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index 2c8c8ff3..fe0343de 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -13,3 +13,4 @@ begins this directory with the platform operator runbooks; | [Tenant onboarding](tenant-onboarding.md) | A production tenant must be provisioned, mapped to a host and given its first administrator, or an administrator must be recovered | | [Identity issuer rebind](identity-issuer-rebind.md) | The tenant identity provider keeps its realm and users but changes address, and the stored issuer must follow without re-keying anyone | | [Operator recovery](operator-recovery.md) | An event or delivery is dead-lettered, a job is quarantined, and an operator must inspect it or reset one delivery or outbox row under a fence | +| [Federation operator](federation-operator.md) | A tenant's identity-provider broker is orphaned, unreadable or nonconforming, and an operator must report it, remove it or disable it, and an account review is owed | diff --git a/docs/runbooks/federation-operator.md b/docs/runbooks/federation-operator.md new file mode 100644 index 00000000..44b1ec39 --- /dev/null +++ b/docs/runbooks/federation-operator.md @@ -0,0 +1,256 @@ +# Federation operator: orphaned and broken brokers + +How an operator finds the identity-provider brokers a tenant's federation left +orphaned, unreadable or nonconforming, and removes or disables one. Decided in +[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md) and +implemented as Amendment 11. There is **no dashboard** and **no way to list or remove +a realm user**: this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/federation/brokers` | Reports one page of brokers that need an operator (a **report**) | `platform.federation.read` | +| `POST /api/platform/v1/federation/brokers/{alias}/remove` | Deletes an orphaned or unreadable owned broker at the provider (a **remove**) | `platform.federation.admin` | +| `POST /api/platform/v1/federation/brokers/{alias}/disable` | Sets `enabled=false` on a nonconforming or unreadable owned broker, at the provider only (a **disable**) | `platform.federation.admin` | + +Authentication, the token profile and how a grant is given are in [Platform operator +access](operator-access.md). The served operator document, `platform-v1`, is the +contract for these routes, and it is the only client there is. + +All three run on `ConnectionStrings:PlatformAdmin` and on the federation admin client +(`Federation:ClientSecret`; see the [adapter +specification](../modules/identity/providers.md#tenant-federation-adapter)). With no +client secret configured every call answers `503` at once and nothing is sent to the +provider. The report needs the Identity migration +`20261120160000_grant_platform_federation_projection` applied; without it the first +report fails with a permission error in the API's log. + +## Which brokers the platform may touch + +A broker is the platform's only when **both** hold: + +- its alias is `lsf-` and 32 lowercase hexadecimal characters, the form LearnStack + derives from a connection identifier, and +- its owner marker parses strictly to a tenant and a connection whose derived alias is + that alias. + +Everything else in the realm (an unmarked instance, a marker naming another connection, +an alias that is not LearnStack's) is **counted and never named**: the report's +`ignored` says how many, and no act accepts such an alias. + +A broker the platform may touch is reported in at most three classes: + +| Class | Meaning | +|---|---| +| `orphan` | No live connection row names it: the row is absent (`rowState` `absent`) or a tombstone (`deleted`) | +| `unreadable_owned` | The marker proves it LearnStack's and its representation no longer reads as an admitted OIDC or SAML broker | +| `nonconforming` | It reads, and differs from the fixed profile or carries a mapper ([Fixed broker profile](../modules/identity/providers.md#fixed-broker-profile)) | + +A broker that conforms and has a live row is not reported. + +## What is not here + +- **Listing or removing realm users.** No LearnStack credential may enumerate or remove + them ([ADR-0099 Decision Q1](../decisions/0099-confined-tenant-federation.md)). The + account review below is yours, with your own realm authority. +- **Removing a broker a live row still names.** Disable it here and let the tenant's + own *Delete* retire the connection; a removal is refused while a live row exists. +- **Repairing a broker.** There is no rewrite from the fixed profile on this surface. + The tenant's next readback corrects its own broker; an unreadable one is disabled + here and deleted by the tenant. +- **A broker whose tenant is archived or deleted with a live row.** That is + [P03-10](../roadmap/phase-03-identity-admin.md)'s. +- **A provider-side fence.** A tenant's create that lands after a sweep produces a new + orphan, which the next report finds. + +## When to look + +- A tenant reports a sign-in option that does nothing, or a provider that was removed + in the tenant's own screen and still offers a button. +- A broker in the provider's console carries a LearnStack alias (`lsf-` and 32 hex + characters) that no connection in the tenant's own screen explains. +- After a failed tenant create or delete whose intent row has no completion row + (see [Check it worked](#check-it-worked)). +- As a periodic sweep: the report is read-only and cheap, so run it page by page. + +## Report + +Each page is one entered platform scope, so each page writes one +`platform.admin_scope.enter` audit row with the reason `federation_report`, your +attribution and your ticket. It does not say which page you read. Pass the ticket as +`?ticket=`: 1 to 64 letters, digits or `.` `_` `:` `/` `#` `-`, and percent-encode `#` +as `%23`. + +```sh +curl -s -H "Authorization: Bearer $TOKEN" \ + "$API/api/platform/v1/federation/brokers?limit=50&ticket=CHG-123" +``` + +- `limit` is 1 to 100 (default 20; a larger value is clamped, and zero or less is + refused with `errors.limit`). Only `limit`, `cursor` and `ticket` are accepted; any + other parameter is refused with `errors.query` and nothing is read. +- A page is one slice of the provider's own listing, `scanned` instances long, and the + answer holds `items` (the brokers on that slice that need attention), `scanned`, + `ignored` and a `pageInfo` whose `nextCursor` you send back as `cursor`. **An empty + `items` with a `nextCursor` is not the end**: the slice held nothing to report. Read + until `hasNext` is false. A cursor belongs to this route. +- Each item carries `alias`, `tenantId`, `connectionId`, `classes`, `rowState`, + `protocol`, `enabled` and `mappers`. `mappers` is the count on a readable broker with + a live row; `null` means it was not read or could not be, **never zero**. +- The realm is read **first** and the connection rows second, because a tenant writes + its row before it creates its broker. A tenant that creates a broker while your page + is being read cannot be taken for an orphan. A broker whose class is `orphan` on one + page can still gain a row before you act; the remove re-reads the row. +- A report the provider cannot answer is `503`, never an empty realm. + +## Choose: remove or disable + +| The broker is | Do | +|---|---| +| `orphan`, readable or not | **Remove** it | +| `unreadable_owned` with a live row | **Disable** it, and ask the tenant to delete the connection; a remove is refused | +| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback corrects it, and until then the sign-in option fails closed | +| healthy with a live row | Neither: a disable is refused with `not_applicable` | + +A **remove** also deletes the broker's federated links, which is why [an account +review](#account-review-after-a-remove) is owed. A **disable** changes only `enabled` +at the provider and the tenant's own row is left to its next readback. + +## Act + +A ticket is optional and is **checked, not stored**: the audit rows are readable by +the tenant, so they never carry one. The body is `{}` or `{"ticket":"CHG-123"}`. + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/federation/brokers/$ALIAS/remove" -d '{"ticket":"CHG-123"}' +``` + +Use `.../disable` the same way. + +Each act proves the owner marker at the provider, re-reads the connection row +immediately before the change, writes an **intent** row, changes the provider, reads +it back, and writes a **completion** row. + +| Answer | Meaning | +|---|---| +| `200`, `outcome: applied` | The provider's change was made and confirmed. `accountReviewOwed` is `true` for a remove, which deleted federated links | +| `200`, `outcome: already_applied` | The broker was already absent (remove) or already disabled (disable). Nothing was sent and **no tenant row was written** | +| `404` | A disable named an alias no instance has | +| `409`, `errors.owner` = `lockey_not_owned` | The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. Nothing was touched | +| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names the broker, so a remove is refused. Disable it, and the tenant deletes the connection | +| `409`, `errors.class` = `lockey_not_applicable` | A disable found a healthy owned broker with a live row | +| `409`, `errors.provider` = `lockey_provider_refused` | The provider definitively refused the change. Nothing changed | +| `400` | The alias is not a derived one, or the body or the ticket is malformed. A refusal at the gate carries no per-field errors | +| `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.federation.admin` for an act), the body size or type, or the request budget | +| `503`, `audit_unavailable` | A MUST row could not be written, so nothing changed (or only the intent row is recorded). Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | The provider or the database could not be reached before any change was sent. Nothing changed. Retry after the delay | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, or a fault followed it. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | + +A client that never received an answer (a timeout, a gateway error) is in the same +position as an unknown outcome. + +## An unknown outcome + +There is no provider-side fence, so reconcile by reading, in this order: + +1. Read the report again, or read the one alias. A remove that landed leaves no + instance with that alias; a disable that landed shows `enabled` false. +2. If it did not land, repeating the act is safe: it re-proves the marker and the row. +3. To tell your act from another operator's, read the tenant's audit rows by the + `correlationId` of the failed response, as in [Check it worked](#check-it-worked). + +A repeat of an act that had landed answers `already_applied` and writes no row; that +alone cannot say whose act it was. + +## Account review after a remove + +The provider deletes **the broker's federated links** with the broker and keeps the +accounts. A person who signed in only through that provider still has an account, and +has lost the way into it. LearnStack cannot list or repair these accounts, and +Keycloak keeps link events for seven days only, so the review is a realm +administrator's, in the provider's own console under their own authority: + +1. If the removal is not urgent, **note the linked users before you remove**: the + console lists a user's identity-provider links. +2. After the remove, review the accounts that depended on it: whether each has another + credential or sign-in route, and whether its sessions must be ended. +3. Tell the tenant's owner. No owner notification channel exists before + [Phase 08a](../roadmap/phase-08a-assessment-notifications.md), so this is by hand. + +An `accountReviewOwed` of `true` in the answer, and the same member in the completion +row's `after_state`, are the reminder. Nothing in LearnStack closes the review. + +## Check it worked + +1. Read the report again: the broker is gone (a remove) or shows `enabled` false (a + disable). +2. Read the audit trail. The rows are in the **tenant's** trail: they name the tenant + the owner marker names, even when no tenant row exists, with no actor, your + attribution in `metadata.operator` and **no ticket**. There is no audit API: read + them as the application role announcing the tenant, by the response's + `correlationId`, with the query and the digest recipe of [Tenant + onboarding](tenant-onboarding.md#reading-the-record). + - `platform.federation.remove_attempt` or `platform.federation.disable_attempt`, + outcome `indeterminate`, the **intent**, committed before the provider was + touched. Its `before_state` holds the broker's `classes` and the connection + row's `rowState`. + - `platform.federation.remove` or `platform.federation.disable`, outcome `success`, + the **completion**, whose `after_state` holds the closed `outcome` (`applied`, + `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`) and + `accountReviewOwed`. +3. An **intent row with no completion row** is a completion that was lost: the provider + may have been changed. The next report resolves it, as step 1 does. + +A refusal before the intent (an absent broker, an unowned alias, a live row, an +unavailable provider) writes **no tenant row**: the scope's entry row, +`platform.admin_scope.enter` with the reason `federation_remove` or +`federation_disable`, records that an act was attempted and nothing is known to name a +tenant. + +## A 503 that does not clear + +Find the cause in the API's host log by the response's `correlationId` (warning 7110; +it carries the operation and whether the outcome is unknown, and the exception holds the +cause): + +- **The provider.** The federation admin client's token or an admin call failed. The + adapter's circuit may be open after repeated failures; it closes by itself. A + `Federation:ClientSecret` that is not configured, or one the realm refuses, never + clears until it is fixed. +- **The database or the credential.** `ConnectionStrings:PlatformAdmin` cannot connect. + A refused credential or a missing grant is a `500` and the log names it. + +## Signals + +`learnstack_platform_operator_federation_total{operation,outcome}` counts every call. +`operation` is `platform.federation.report`, `platform.federation.remove_attempt` or +`platform.federation.disable_attempt`; `outcome` is `ok`, `invalid_cursor`, +`applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, +`not_applicable`, `refused`, `unavailable` or `uncertain`. A rising `uncertain` means +completions are being lost or the provider is failing mid-change; a rising +`not_owned` is an operator naming aliases that are not LearnStack's. The admission, +refusal and audit-failure counters are in [Platform operator +access](operator-access.md#signals). Each report page logs the scope-entry line 7001, as +a killswitch act does. + +## Limits + +- **Pages are slices of the realm.** A realm with many instances takes many pages; + there is no filter by tenant, class or alias. +- **Disable is a read and a write.** The tenant's own write can interleave with it, and + the tenant's next readback detects the drift + ([ADR-0099 Amendment 11](../decisions/0099-confined-tenant-federation.md)). +- **A disable sends back what the provider returned.** An unreadable broker cannot be + rebuilt from the fixed profile, so the operator disable is the one provider write that + does not build its body from the allow-list. It changes `enabled` and nothing else, + and keeps the stored secret. + +## Not recoverable here + +- A broker with no marker, or a marker that is not LearnStack's: the realm + administrator's, in the provider's console. +- A federated link that a remove deleted. +- A realm user, a session, a credential or an owner notice. +- A dashboard. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 3a2ce479..da6bf86a 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -22,7 +22,7 @@ The surface does not exist until an issuer is configured; with none, every | `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | | `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, as a time span such as `00:15:00`; at most one hour, default 15 minutes | | `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | -| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act and the [recovery](operator-recovery.md) inspections run under. Required for them: without it the first one fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | +| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act, the [recovery](operator-recovery.md) inspections and the [federation](federation-operator.md) report, remove and disable run under. Required for them: without it the first one fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | | `ConnectionStrings:OutboxDispatcher` | The dispatcher's outbox-role credential, which the two recovery acts (replay and reset) use through the dispatcher's own stores. Without it they cannot run, as the dispatcher cannot | List settings are indexed in environment variables, and the double underscore is the @@ -45,7 +45,10 @@ The registered permissions are `platform.killswitch.write` tool reads the same `PlatformOperator__*` settings from its own environment and is not an API route. `platform.delivery.read` and `platform.delivery.write` are the two permissions of [operator recovery](operator-recovery.md): the first for the inspection -routes and the second for a replay or a producer reset. +routes and the second for a replay or a producer reset. `platform.federation.read` and +`platform.federation.admin` are the two permissions of the [federation +operator](federation-operator.md): the first for the report and the second for a remove +or a disable. A Self-Hosted issuer other than the shipped realm must issue access tokens that meet the profile below. If it cannot, no operator can act, by design. @@ -180,8 +183,9 @@ the response. |---|---| | `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate; `operation` is the audit slug, for example `tenancy.killswitch.toggle` | | `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `request_aborted`, `metadata_stale`, `metadata_unavailable`, `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_algorithm`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `invalid_ticket`, `missing_permission`, `unknown_operation`, `invalid_witness` | -| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by an operator act: the killswitch toggle in the platform scope, and a replay or a reset on the dispatcher's outbox role | +| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by an operator act: the killswitch toggle and a federation remove or disable (the completion row) in the platform scope, and a replay or a reset on the dispatcher's outbox role | | `learnstack_platform_operator_recoveries_total{operation,outcome}` | Recovery transitions by how they ended; see the [recovery runbook](operator-recovery.md#signals) | +| `learnstack_platform_operator_federation_total{operation,outcome}` | Federation reports, removes and disables by how they ended; see the [federation runbook](federation-operator.md#signals) | | `learnstack_platform_operator_acts_total{operation,outcome}` | Onboarding acts by how they ended (`applied`, `replayed`, `refused`, `failed`); see the [onboarding runbook](tenant-onboarding.md#signals) | | `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | | `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs, new keys are not learned; a fetch that failed is not retried for 30 seconds, and once the keys held are more than 15 minutes old with a later fetch failed, every operator is refused (`metadata_stale`) | @@ -190,10 +194,11 @@ A log line accompanies each. Search by event id: 7102 (Warning) a refused act, 7 (Warning) a refused credential with its cause, 7106 (Warning) a metadata failure, 7105 (Error) a refused audit write, and 7101 (Error) a grant configuration that failed validation on reload; while 7101 appears every operator act is refused until the -configuration is valid. Every admitted killswitch act and every recovery inspection page -logs a Warning with event 7001 and the text "Platform-admin scope entered" (other hosts -reuse the number for unrelated lines, so match the text too); the onboarding acts and the -two recovery acts do not enter the platform scope and log no 7001. Event 7109 (Warning) +configuration is valid. Every admitted killswitch act, recovery inspection page and +federation report, remove or disable logs a Warning with event 7001 and the text +"Platform-admin scope entered" (other hosts reuse the number for unrelated lines, so +match the text too); the onboarding acts and the two recovery acts do not enter the +platform scope and log no 7001. Event 7109 (Warning) is an onboarding act the request pipeline itself refused as forbidden, which is a defect. Event 7110 (Warning) is a recovery or an inspection the owner could not finish, with whether its commit's outcome is unknown; see the [recovery diff --git a/docs/standards/04-api-design.md b/docs/standards/04-api-design.md index ea16cc42..1370543f 100644 --- a/docs/standards/04-api-design.md +++ b/docs/standards/04-api-design.md @@ -52,7 +52,12 @@ Examples: Platform operator endpoints live under `/api/platform/v1/...`, outside the tenant `/api/v1` contract and its OpenAPI document, and require a Platform-scope permission -([ADR-0101](../decisions/0101-platform-operator-authority.md)). +([ADR-0101](../decisions/0101-platform-operator-authority.md)). The federation routes +(`GET /api/platform/v1/federation/brokers` and the `remove` and `disable` acts under it, +[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)) take an +optional checked, never stored `ticket`, answer a refusal on the field it concerns and +answer an act whose outcome is unknown `503` `dependency_unavailable` with +`errors.outcome`. **P02d-4 Accepted contract — 2026-10-03.** Steps 2–3 deliver all four GET/HEAD read pairs; Step 4 delivers the contract/SDK controls. Institution diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index d65a0c88..22ce546e 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -1100,7 +1100,7 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | `membership_role_assignments` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | | `roles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | | `role_permission_grants` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | -| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | — | — | +| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | — | `SELECT` of `id`, `tenant_id`, `state` and `deleted_at` only ([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 11); exact [projection grant](#federation-operator-projection) | | `tenants` | `SELECT, INSERT, UPDATE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `organizations` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `tenant_domains` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT` | — | @@ -6266,6 +6266,26 @@ columns: that is NULL because a nullable pending or test column is NULL refuses: the guard fails closed. +### Federation operator projection + +**Derives from:** [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment +10 item 5 and Amendment 11 item 2. The operator's report asks one question of the +registry, whether a broker the realm lists still has a live row, and reads it as +`learnstack_platform` through four columns, which the platform role's `BYPASSRLS` +makes readable across tenants and the grant alone bounds: + +```sql +GRANT SELECT (id, tenant_id, state, deleted_at) ON public.federation_connections TO learnstack_platform; +``` + +The platform role receives no other privilege on the table: a statement that names the +alias, display name, issuer, client identifier, configuration digest or any other column +is refused by PostgreSQL, and so is every write. The grant is a forward-only migration +of the Identity chain, because the table is created there after the Platform chain has +run. The reader is the one statement of the operator's owner, which sees tombstones +and reads by primary key; the architecture census pins it whole, and tests read the granted +columns, refuse every other, and read two tenants' rows through the role. + ### Federation host-alias read **Derives from:** [ADR-0099 Amendment 6](../decisions/0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index d69d7012..2630d9e8 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -478,6 +478,7 @@ backend treat business rejections as system failures. | `learnstack_platform_operator_admissions_total` | counter | outcome (`admitted`, `refused`), operation (a registered slug or `unknown`) | | `learnstack_platform_operator_refusals_total` | counter | cause (a closed set: token, profile and gate causes; [runbook](../runbooks/operator-access.md#signals)) | | `learnstack_platform_operator_results_total` | counter | operation | +| `learnstack_platform_operator_federation_total` | counter | operation (`platform.federation.report`, `platform.federation.remove`, `platform.federation.disable`), outcome (a report's `ok`, `invalid_cursor`, `unavailable`; an act's `applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, `not_applicable`, `refused`, `unavailable`, `uncertain`; [runbook](../runbooks/federation-operator.md#signals)) | | `learnstack_platform_operator_recoveries_total` | counter | operation (`platform.delivery.replay`, `platform.delivery.reset`), outcome (`applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable`, `commit_unknown`; [runbook](../runbooks/operator-recovery.md#signals)) | | `learnstack_platform_operator_audit_failures_total` | counter | operation | | `learnstack_platform_operator_metadata_failures_total` | counter | none | diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index b908974f..962ddd83 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -167,8 +167,13 @@ LearnStack runs **two Keycloak realms** per mTLS client certificate; and the platform operator prefix accepts operator tokens of its pinned issuer only, for its own audience. The operator's onboarding acts ([ADR-0102](../decisions/0102-production-tenant-onboarding.md)) run on the application - role, under row security, through the ordinary pipeline; the one `BYPASSRLS` use of - the operator surface remains the killswitch writer. The executor that installs an + role, under row security, through the ordinary pipeline; the `BYPASSRLS` uses of the + operator surface are the platform scope's callers (the killswitch writer, the recovery + inspections and the federation report, remove and disable of + [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)), each behind + an entry row and a per-act admission. The federation acts reach the identity provider + only through the confined admin client and its operator port, after an intent row the + scope handle commits, and never read or remove a realm user. The executor that installs an act's tenant context accepts only an admission the gate minted for that act within the last 30 seconds and spends it once, and the seeder refuses to run outside a Development deployment. The controlled issuer rebind diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 170ebd58..fbd4c50a 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -240,7 +240,15 @@ will raise them — which this standard requires it to do. `platform.delivery.replay` and `platform.delivery.reset` are written on the dispatcher's outbox-role transaction through one witness-bound method, under the real event tenant, with no actor, the operator attribution and the fence in - `metadata`, and no ticket, because a tenant can read the row. + `metadata`, and no ticket, because a tenant can read the row. The operator federation + operations of [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10 + and 11 are `(off-path)` as well: `platform.federation.report` is audited by the + platform scope's entry row, and `platform.federation.remove` and + `platform.federation.disable` each write an intent row on their `_attempt` slug at the + scope handle's checkpoint, with the outcome `indeterminate`, committed before the + provider call ([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), and a + completion row on their own slug. Both rows name the tenant the owner marker names + and carry no ticket and no tenant-authored text. ## Baseline Coverage (LearnStack Core Modules) diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 8fd4d24c..1268a56b 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read` and `platform.delivery.write` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read`, `platform.delivery.write`, `platform.federation.read` and `platform.federation.admin` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | @@ -109,6 +109,8 @@ not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authori | `platform.identity_authority.admin` | `identity.authority.rebind` (the controlled issuer rebind, an offline tool and not a route) | P03-9 Step 3 | | `platform.delivery.read` | `platform.delivery.inspect` (metadata-only inspection of dead-lettered work and quarantined jobs, in the platform scope) | P03-9 Step 4 | | `platform.delivery.write` | `platform.delivery.replay`, `platform.delivery.reset` (the two fenced transitions, on the dispatcher's outbox role) | P03-9 Step 4 | +| `platform.federation.read` | `platform.federation.report` (the report of orphaned, unreadable and nonconforming identity-provider brokers, in the platform scope) | P03-9 Step 5 | +| `platform.federation.admin` | `platform.federation.remove`, `platform.federation.disable` (the two provider changes, each with an intent and a completion row) | P03-9 Step 5 | The five onboarding acts of [ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index c447a77f..c0cea240 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -486,6 +486,12 @@ after its outcome settled; the timeout is 2.5 s, the circuit breaker on, and the bulkhead exactly 4 without a queue. These values are fixed: the composition root refuses any other value at startup, and refuses breaker parameters outside the ranges the provider specification states. +The same class implements the operator port `IFederationOperator` +([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10 and 11), +held only by the operator's owner and by the adapter, and built as a second instance +with its own `IProviderResilience` pipeline of the same fixed +shape so that an operator sweep cannot starve a tenant's calls; its fail-closed default +is registered beside the provider's. It adds one provider route, a paged listing of the realm's instances. The operator egress allow-list `Federation:Egress:AllowedHosts` is composition configuration, never tenant input. The [provider specification](../modules/identity/providers.md#tenant-federation-adapter) owns diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index c347c104..b45b0569 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**389 test methods run in +**390 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -217,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**292 rules in this catalogue are Implemented, and 174 of them are in that assembly.** +**293 rules in this catalogue are Implemented, and 175 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -3788,12 +3788,13 @@ which decides identity, multiplicity, capture and classification; `The_AppendOnly_Sweep_Can_Actually_Fail`, that checks the pattern against the shapes it must catch and the shapes it must not, because with no offending statement anywhere the sweep passes whether it works or matches nothing; and a reflection check, - `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly fourteen + `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly fifteen write methods and no update: the event/job seams ship in Phase 02b, ADR-0072's two global seams in P03-1 Step 3, the two trusted authorization seams in P03-2, the operator result seam of ADR-0101 in P03-9 Step 1, the two controlled-rebind seams - of ADR-0104 in P03-9 Step 3 and the operator recovery seam of ADR-0103 in P03-9 - Step 4. None + of ADR-0104 in P03-9 Step 3, the operator recovery seam of ADR-0103 in P03-9 + Step 4 and the platform scope's intent seam of ADR-0044 Amendment 18 in P03-9 + Step 5. None of the three sanctioned redaction sites exists yet — they land in Phase 03 and Phase 11 — so the exemption set ships with the rule **empty**, as exact paths: the first site to land adds its own path, so it is exempted by name rather than the pattern @@ -6040,6 +6041,24 @@ structural test proves — and what it does not. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 4). - **Phase:** P03-9. +#### `Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Operator_Ports` + +- **Asserts:** the files, by their path under `backend/src`, that name + `IFederationBrokerOperations` are exactly the port, its one owner, the persistence + composition and the federation routes, and the files that name `IFederationOperator` + are exactly the port, the owner, the adapter that implements it, its factory, the + federation composition and the Identity foundation registration that gives it a + fail-closed default. The tenant runner is in neither list. Adding a caller is a + deliberate edit here, with its denied proof. +- **Why it matters:** the removal and the disable change the realm's identity providers + for every tenant, and the tenant's provider port is held by the runner alone; a second + holder of the operator port, or a handler that reached the owner, would make a + cross-tenant provider change from a path the operator gate does not guard. +- **Source:** [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 5). +- **Phase:** P03-9. + #### `Only_The_Operator_Services_Hold_The_Platform_Scope` - **Asserts:** the files, by their path under `backend/src`, that name @@ -7823,9 +7842,12 @@ sign-in read). The #### `Federation_Adapter_Admits_Only_The_Enumerated_Routes` -- **Asserts:** `KeycloakFederationRoutes` builds exactly four routes (token, the - identity-provider collection, one owned instance and its mappers), and no string - literal in the adapter namespace names another Admin, identity-provider, +- **Asserts:** `KeycloakFederationRoutes` builds exactly six routes (token, the + identity-provider collection, one bounded page of that collection, one owned instance, + one instance by a derived alias and its mappers; the page and the by-alias read serve + the operator of + [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)), and no + string literal in the adapter namespace names another Admin, identity-provider, authentication, user, client or role path. The unit test `KeycloakFederationProviderTests.Every_admitted_request_targets_the_enumerated_routes_only` checks the same set behaviourally against a scripted provider. diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 5585493a..949fd996 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -96,6 +96,7 @@ "LearnStack.Tests.Integration.Database.EntitlementExpiryReversalTests", "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests", "LearnStack.Tests.Integration.Database.FeatureFlagsTests", + "LearnStack.Tests.Integration.Database.FederationBrokerOperationsTests", "LearnStack.Tests.Integration.Database.FederationConnectionStorageTests", "LearnStack.Tests.Integration.Database.FederationHttpTests", "LearnStack.Tests.Integration.Database.FixedSeedPrerequisiteReadTests", From c991e16703574a568dc35ece99e6368914506b05 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 23:29:07 +0300 Subject: [PATCH 21/28] fix(platform): close P03-9 step 5 review round 1 findings A completion row is written on a bounded token detached from the request, and a completion lost after a provider change answers the unknown outcome instead of "nothing changed". The report counts healthy-looking brokers whose mappers it could not read. A transient database fault is a 503 with its cause logged, and any failure to commit the intent row stops the act. The maintainer chose to let the operator remove an unreadable owned broker even when a live row names it, because the tenant's Delete cannot reach one (ADR-0099 Amendment 12, with an erratum beside Amendment 11 item 5). The ticket text, the Standard 05 grant column, the runbook, the served contract and the stale census text are corrected, the audit-writing service tests run on an isolated database, and a real brokered sign-in proves a disable keeps the secret. ADR: 0099 Module: Identity, Platform Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 8 +- .../PlatformOperatorEndpoints.Federation.cs | 33 +- .../KeycloakFederationProvider.Operator.cs | 24 +- .../Messaging/OperatorRecoveryFaults.cs | 6 +- .../MultiTenancy/PlatformAdminScope.cs | 4 +- .../Identity/IFederationOperator.cs | 4 +- .../Platform/IFederationBrokerOperations.cs | 17 +- .../Platform/PlatformOperation.cs | 2 +- .../Federation/FederationBrokerOperations.cs | 134 ++++++-- .../FederationAdapterConventionTests.cs | 25 ++ .../PlatformAdminScopeConventionTests.cs | 25 +- .../FederationBrokerOperationsTests.cs | 315 ++++++++++++++++-- .../PlatformOperatorHttpTests.cs | 129 ++++++- .../FederationProviderTests.Operator.cs | 48 ++- .../KeycloakFederationProviderTests.cs | 21 +- docs/architecture/31-audit-subsystem.md | 9 +- docs/decisions/0044-audit-write-path.md | 32 +- .../0099-confined-tenant-federation.md | 78 ++++- docs/glossary.md | 4 +- docs/modules/identity/providers.md | 19 +- docs/modules/tenancy/audit.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 70 +++- docs/runbooks/federation-operator.md | 108 +++--- docs/runbooks/operator-access.md | 4 +- docs/standards/04-api-design.md | 7 +- docs/standards/05-database.md | 2 +- .../21-architecture-tests-catalogue.md | 36 +- 27 files changed, 962 insertions(+), 204 deletions(-) diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index 8f3f0a01..ca15ecfb 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -218,15 +218,15 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation private static readonly (string Status, string Description)[] Statuses = [ - ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit or errors.cursor."), + ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit, errors.cursor or, for the federation report, errors.query (a parameter it does not take). A federation act names only an alias of the form lsf- and 32 lowercase hexadecimal characters."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), - ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, or a recovery names no such row."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200."), + ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, a recovery names no such row, or a federation disable names an alias no identity-provider instance has."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200. A federation act answers 409 with the reason on errors.owner (the instance's owner marker is not LearnStack's, or names another tenant than its row), errors.connection (a live connection row still names a broker that reads: a remove is refused; an unreadable owned broker is removed even so), errors.class (a disable found a healthy broker with a live row) or errors.provider (the provider definitively refused the change; nothing changed). A repeat of a federation act that had landed answers 200 already_applied and writes no row of its own."), ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), ("500", "internal_error: an unexpected failure. An act's final commit may have landed: read the state before changing it. An exact repeat of an onboarding act answers 200; a repeat of a recovery that had landed answers 409 on errors.fence."), - ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written, a connection or an ordered lock could not be taken, or a read failed, so nothing changed. Retry after the delay. A recovery's dependency_unavailable can carry errors.outcome = lockey_outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed recovery answers a repeat 409 on errors.fence."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written, a connection or an ordered lock could not be taken, or a read failed, so nothing changed. Retry after the delay. A recovery's dependency_unavailable can carry errors.outcome = lockey_outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed recovery answers a repeat 409 on errors.fence. A federation act's dependency_unavailable carries it when a provider change was sent and its completion could not be recorded or its answer was lost: read the report or the alias before repeating."), ]; } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs index 29a72844..eba96bb2 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs @@ -15,9 +15,9 @@ internal sealed record FederationActBody( [property: RegularExpression(TicketPattern.Value)] string? Ticket); -/// One page of the federation report. +/// One page of the federation report; MappersUnread counts healthy-looking brokers whose mappers were not read. internal sealed record FederationReportResponse( - IReadOnlyList Items, InspectionPageInfo PageInfo, int Scanned, int Ignored); + IReadOnlyList Items, InspectionPageInfo PageInfo, int Scanned, int Ignored, int MappersUnread); /// What an applied or repeated federation act answers; the account review is the operator's to start. internal sealed record FederationActResponse( @@ -50,9 +50,11 @@ private static void MapFederation(RouteGroupBuilder group) .WithName("PlatformFederationRemove") .WithSummary("Remove an orphaned or unreadable owned broker at the provider; the provider deletes its federated links.") .WithDescription( - "Refused while a live connection row names the broker. An absent broker is already removed. The tenant's " + "Refused while a live connection row names a broker that reads; an unreadable owned broker is removed even " + + "with a live row, because nothing else can. An absent broker is already removed. The tenant's " + "intent and completion rows are written around the provider call; the delegated-account review is the " - + "operator's, by runbook. A ticket is checked and not stored."), + + "operator's, by runbook. A ticket is checked and recorded only on the platform scope's entry row, never " + + "on a tenant's row."), typeof(FederationActResponse)); Describe( group.MapPost(FederationPrefix + "/{alias}/disable", DisableFederationAsync) @@ -60,7 +62,8 @@ private static void MapFederation(RouteGroupBuilder group) .WithSummary("Disable a nonconforming or unreadable owned broker at the provider only; the tenant's row is left to its next readback.") .WithDescription( "Sets enabled to false and nothing else, on an instance whose owner marker is proven. A healthy broker with " - + "a live row is refused. A ticket is checked and not stored."), + + "a live row is refused. A ticket is checked and recorded only on the platform scope's entry row, never on " + + "a tenant's row."), typeof(FederationActResponse)); } @@ -99,7 +102,7 @@ private static async Task ReportFederationAsync( { FederationReportOutcome.Ok => Results.Ok(new FederationReportResponse( result.Items, new InspectionPageInfo(result.NextCursor, null, result.NextCursor is not null, false), - result.Scanned, result.Ignored)), + result.Scanned, result.Ignored, result.Unread)), FederationReportOutcome.InvalidCursor => InvalidParameter(http, "cursor"), _ => UnavailableProblem(http, loggers, operation, new OperatorRecoveryUnavailableException()), }; @@ -108,6 +111,12 @@ private static async Task ReportFederationAsync( { return AuditUnavailableProblem(http, loggers, operation, failure); } + catch (OperatorRecoveryUnavailableException failure) + { + // A database fault the owner translated: nothing was changed, and the cause is in the log. + PlatformOperatorMetrics.Federation(operation, "unavailable"); + return UnavailableProblem(http, loggers, operation, failure); + } } private static Task RemoveFederationAsync( @@ -159,14 +168,21 @@ private static async Task FederationActAsync( FederationActOutcome.NotApplicable => ResultProblem(http, Rule("class", "lockey_not_applicable")), FederationActOutcome.Refused => ResultProblem(http, Rule("provider", "lockey_provider_refused")), FederationActOutcome.Unavailable => UnavailableProblem(http, loggers, operation, new OperatorRecoveryUnavailableException()), - _ => UnavailableProblem( + FederationActOutcome.Uncertain => UnavailableProblem( http, loggers, operation, new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true)), + _ => throw new InvalidOperationException("A federation outcome the route does not answer."), }; } catch (AuditWriteFailedException failure) { return AuditUnavailableProblem(http, loggers, operation, failure); } + catch (OperatorRecoveryUnavailableException failure) + { + // A database fault the owner translated: nothing was changed, and the cause is in the log. + PlatformOperatorMetrics.Federation(operation, "unavailable"); + return UnavailableProblem(http, loggers, operation, failure); + } } private static FederationActResponse FederationResponse( @@ -184,6 +200,7 @@ private static FederationActResponse FederationResponse( FederationActOutcome.NotApplicable => "not_applicable", FederationActOutcome.Refused => "refused", FederationActOutcome.Unavailable => "unavailable", - _ => "uncertain", + FederationActOutcome.Uncertain => "uncertain", + _ => throw new InvalidOperationException("A federation outcome the route does not count."), }; } diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs index bd6201ec..e3c85cd9 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs @@ -54,12 +54,12 @@ public async Task ListAsync(int offset, int limit, Cancell } /// - public async Task InspectAsync(string alias, CancellationToken cancellationToken = default) + public async Task InspectAsync(string brokerAlias, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(alias); + ArgumentNullException.ThrowIfNull(brokerAlias); return await RunAsync(FederationBrokerInspection.Unavailable, async (bearer, token) => { - var probe = await ProbeAsync(alias, bearer, token).ConfigureAwait(false); + var probe = await ProbeAsync(brokerAlias, bearer, token).ConfigureAwait(false); try { switch (probe.Kind) @@ -183,11 +183,19 @@ public async Task DisableAsync(FederationBrokerOwner /// private static byte[] DisabledRepresentation(byte[] returned) { - if (JsonNode.Parse(returned) is not JsonObject representation) throw Fault(); - representation.Remove("internalId"); - representation.Remove("types"); - representation["enabled"] = false; - return JsonSerializer.SerializeToUtf8Bytes(representation); + try + { + if (JsonNode.Parse(returned) is not JsonObject representation) throw Fault(); + representation.Remove("internalId"); + representation.Remove("types"); + representation["enabled"] = false; + return JsonSerializer.SerializeToUtf8Bytes(representation); + } + // A body that is not JSON, or an object that repeats a member, is not a representation to send back. + catch (Exception failure) when (failure is JsonException or ArgumentException or InvalidOperationException) + { + throw Fault(); + } } private async Task CountMappersCoreAsync(FederationBrokerOwner owner, string bearer, CancellationToken token) diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs index be1e7443..92d99566 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs @@ -7,13 +7,13 @@ namespace LearnStack.Infrastructure.Messaging; /// refused credential, a missing grant or a missing table is a deployment defect, and answering it with a retryable /// 503 would invite a retry loop that cannot succeed. /// -internal static class OperatorRecoveryFaults +public static class OperatorRecoveryFaults { /// /// A database fault that Npgsql calls transient, a timeout, or the server's own statement timeout, which the /// dispatcher's role sets to the length of its bounded call and which Npgsql does not class as transient. /// - internal static bool IsTransientDatabaseFault(Exception failure, CancellationToken caller) => failure switch + public static bool IsTransientDatabaseFault(Exception failure, CancellationToken caller) => failure switch { PostgresException { SqlState: PostgresErrorCodes.QueryCanceled } => true, NpgsqlException { IsTransient: true } => true, @@ -26,6 +26,6 @@ internal static class OperatorRecoveryFaults /// A transient database fault, or one of the owner's own refusals: the lane is busy, the pool is exhausted or the /// store is sealed by an unconfirmed cleanup, each of which is an . /// - internal static bool IsUnavailable(Exception failure, CancellationToken caller) => + public static bool IsUnavailable(Exception failure, CancellationToken caller) => failure is InvalidOperationException || IsTransientDatabaseFault(failure, caller); } diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index 4137572b..4ba422c0 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -565,8 +565,10 @@ public async Task WriteIntentAsync(PlatformResult intent, CancellationToken canc // effect must not start on an intent nobody can prove was recorded. await _transaction.CommitAsync(cancellationToken); } - catch (Exception failure) when (failure is NpgsqlException or OperationCanceledException or IOException) + catch (Exception failure) { + // Any failure of the commit, a connection already broken included, stops the effect: it must not start on + // an intent nobody can prove was recorded (ADR-0044 Amendment 18). _faulted = true; throw new AuditWriteFailedException( "The platform operator intent row could not be committed, so the effect must not start.", failure); diff --git a/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs index 90bd0c0e..6babc2f2 100644 --- a/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs +++ b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs @@ -106,7 +106,7 @@ public interface IFederationOperator Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default); /// Reads one alias: whether it is absent, foreign to LearnStack or owned, and its nonsecret facts. - Task InspectAsync(string alias, CancellationToken cancellationToken = default); + Task InspectAsync(string brokerAlias, CancellationToken cancellationToken = default); /// Counts the mappers on an owned readable broker; null when the provider could not answer. Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default); @@ -130,7 +130,7 @@ public sealed class UnconfiguredFederationOperator : IFederationOperator public Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default) => Task.FromResult(FederationBrokerPage.Unavailable); - public Task InspectAsync(string alias, CancellationToken cancellationToken = default) => + public Task InspectAsync(string brokerAlias, CancellationToken cancellationToken = default) => Task.FromResult(FederationBrokerInspection.Unavailable); public Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => diff --git a/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs index 775e2d3a..db50eb16 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs @@ -34,8 +34,14 @@ public enum FederationReportOutcome /// The opaque position of the next page, or null after the last. /// How many instances the provider returned for the page. /// How many of them are not LearnStack's: no marker, a foreign marker or a marker that does not match its row. +/// +/// How many brokers that read as healthy and live had no mapper count, because the provider failed or the page's time ran +/// out: an extra mapper is drift only a mapper read shows, so these are unknown and not clean, and the next page of the +/// same size may read them. +/// public sealed record FederationReportResult( - FederationReportOutcome Outcome, IReadOnlyList Items, string? NextCursor, int Scanned, int Ignored) + FederationReportOutcome Outcome, IReadOnlyList Items, string? NextCursor, int Scanned, int Ignored, + int Unread = 0) { public static FederationReportResult Of(FederationReportOutcome outcome) => new(outcome, [], null, 0, 0); } @@ -55,7 +61,10 @@ public enum FederationActOutcome /// The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. NotOwned, - /// A live connection row names the broker, so a remove refuses; the tenant's own Delete retires it. + /// + /// A live connection row names a broker that reads, so a remove refuses; the tenant's own Delete retires the pair. An + /// unreadable owned broker is removed even with a live row (ADR-0099 Amendment 12). + /// LiveConnection, /// A disable found a healthy owned broker with a live row: nothing about it needs an operator. @@ -92,9 +101,9 @@ Task ReportAsync( /// Removes an orphaned or unreadable owned broker after an intent row, and records the completion. /// A MUST row could not be written; the effect did not start or its outcome is recorded by the intent row alone. - Task RemoveAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default); + Task RemoveAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default); /// Disables a nonconforming or unreachable owned broker at the provider only, with the same two rows. /// A MUST row could not be written; the effect did not start or its outcome is recorded by the intent row alone. - Task DisableAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default); + Task DisableAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default); } diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index d3c22b2f..1ea94eca 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -135,7 +135,7 @@ public static class PlatformOperations PlatformOperationExecutor.RecoveryOwner); /// - /// Report the realm's identity-provider brokers by class, orphans first: read-only in the platform scope, audited + /// Report the realm's identity-provider brokers by class, in the provider's order: read-only in the platform scope, audited /// by the scope's entry row (ADR-0099 Amendment 10 item 2). /// public static PlatformOperation FederationReport { get; } = new( diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs index d86c470b..a7b9c523 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs @@ -1,6 +1,9 @@ +using System.Data.Common; using System.Globalization; using System.Text; using System.Text.Json; +using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Pagination; using LearnStack.SharedKernel.Platform; @@ -28,6 +31,12 @@ namespace LearnStack.Modules.Identity.Infrastructure.Federation; /// the call, and no tenant is known from nothing. /// /// +/// The completion is settled on its own budget. Once a change may have been sent, a caller that leaves or a +/// completion that cannot be written must not turn into "nothing changed": the completion row is written on a bounded +/// token detached from the request, as the tenant runner completes on one, and a completion that still fails after a change +/// answers . The intent row then stands alone, which the next report resolves. +/// +/// /// The rows name the marker's tenant, never the platform sentinel, even when no tenants row exists for it. /// They carry closed tokens only: no display name, issuer, configuration or secret, and no ticket, because a tenant can /// read them. @@ -39,11 +48,43 @@ public sealed class FederationBrokerOperations(IPlatformAdminScope scope, IFeder private const string EntityType = "FederationConnection"; private const string RowQuery = "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; private static readonly TimeSpan ReportDeadline = TimeSpan.FromSeconds(10); + private static readonly TimeSpan CompletionBudget = TimeSpan.FromSeconds(3); private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); /// - public async Task ReportAsync( - PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) + public Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => + GuardAsync(() => ReportCoreAsync(admission, cursor, limit, cancellationToken), cancellationToken); + + /// + public Task RemoveAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + GuardAsync(() => RemoveCoreAsync(admission, brokerAlias, cancellationToken), cancellationToken); + + /// + public Task DisableAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + GuardAsync(() => DisableCoreAsync(admission, brokerAlias, cancellationToken), cancellationToken); + + /// + /// A transient database fault is the unavailable owner it is, with its cause kept for the route's log, and never a raw + /// 500. It is raised only where nothing was changed: a completion that fails after a change is answered inside + /// as the unknown outcome, before it can reach this guard. + /// + private static async Task GuardAsync(Func> operation, CancellationToken cancellationToken) + { + try + { + return await operation(); + } + catch (Exception failure) when (OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) + { + throw new OperatorRecoveryUnavailableException(cause: failure); + } + } + + private async Task ReportCoreAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken) { RequireOperation(admission, PlatformOperations.FederationReport); var offset = 0; @@ -97,9 +138,16 @@ public async Task ReportAsync( deadline.Token, cancellationToken); var items = new List(); + var unread = 0; foreach (var (facts, row) in candidates) { mappers.TryGetValue(facts.Owner.Alias, out var count); + if (count is null && IsLive(row) && facts is { Readable: true, Conforms: true }) + { + // A mapper is drift only a mapper read shows: this broker is unknown, not clean, and the page says so. + unread++; + } + var classes = ClassesOf(facts, row, count ?? 0); if (classes.Count == 0) { @@ -112,16 +160,15 @@ public async Task ReportAsync( } var next = page.Scanned == size ? Encode(offset + page.Scanned) : null; - return new FederationReportResult(FederationReportOutcome.Ok, items, next, page.Scanned, ignored); + return new FederationReportResult(FederationReportOutcome.Ok, items, next, page.Scanned, ignored, unread); } - /// - public async Task RemoveAsync( - PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) + private async Task RemoveCoreAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken) { RequireOperation(admission, PlatformOperations.FederationRemove); await using var handle = await scope.EnterAsync(admission, cancellationToken); - var inspection = await provider.InspectAsync(alias, cancellationToken); + var inspection = await provider.InspectAsync(brokerAlias, cancellationToken); switch (inspection.Status) { case FederationInspectionStatus.Unavailable: @@ -141,9 +188,9 @@ public async Task RemoveAsync( return new FederationActResult(FederationActOutcome.NotOwned); } - if (IsLive(row)) + if (RefusesRemoval(facts, row)) { - // Amendment 10 item 3: a live row refuses, for both classes. The tenant's own Delete retires it. + // Amendment 10 item 3: a live row refuses a broker that reads. The tenant's own Delete retires it. return Known(FederationActOutcome.LiveConnection, owner); } @@ -155,27 +202,26 @@ public async Task RemoveAsync( var again = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); FederationActOutcome outcome; string? cause = null; - if (IsLive(again)) + if (RefusesRemoval(facts, again)) { outcome = FederationActOutcome.LiveConnection; cause = "live_connection"; } else { - outcome = Map(await provider.RemoveAsync(owner, cancellationToken)); + outcome = await ChangeAsync(token => provider.RemoveAsync(owner, token), cancellationToken); } - await Complete(handle, owner, classes, row, outcome, cause, cancellationToken); + outcome = await CompleteAsync(handle, owner, classes, row, outcome, cause); return Known(outcome, owner); } - /// - public async Task DisableAsync( - PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) + private async Task DisableCoreAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken) { RequireOperation(admission, PlatformOperations.FederationDisable); await using var handle = await scope.EnterAsync(admission, cancellationToken); - var inspection = await provider.InspectAsync(alias, cancellationToken); + var inspection = await provider.InspectAsync(brokerAlias, cancellationToken); switch (inspection.Status) { case FederationInspectionStatus.Unavailable: @@ -207,22 +253,56 @@ public async Task DisableAsync( } await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); - var outcome = Map(await provider.DisableAsync(owner, cancellationToken)); - await Complete(handle, owner, classes, row, outcome, cause: null, cancellationToken); + var outcome = await ChangeAsync(token => provider.DisableAsync(owner, token), cancellationToken); + outcome = await CompleteAsync(handle, owner, classes, row, outcome, cause: null); return Known(outcome, owner); } - private static async Task Complete( + /// + /// The provider's change, with a caller that leaves recorded as an unknown outcome: the change may already have been + /// sent, and the adapter rethrows the caller's cancellation without saying which side of the send it fell on. + /// + private static async Task ChangeAsync( + Func> change, CancellationToken cancellationToken) + { + try + { + return Map(await change(cancellationToken)); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return FederationActOutcome.Uncertain; + } + } + + /// + /// Writes and commits the completion row on a bounded token detached from the request, and returns the outcome the + /// caller is to answer. A completion that cannot be written is the audit failure it is when nothing changed; after a + /// change that landed or may have, the intent row stands alone and the answer is the unknown outcome, never + /// "nothing changed, repeat it". + /// + private static async Task CompleteAsync( IPlatformAdminScopeHandle handle, FederationBrokerOwner owner, IReadOnlyList classes, Row? row, - FederationActOutcome outcome, string? cause, CancellationToken cancellationToken) + FederationActOutcome outcome, string? cause) { var token = OutcomeToken(outcome); // The account review is owed for any change that may have landed: the provider removes federated links with a // broker, and nothing here reads them (ADR-0099 Amendment 10 item 7). var owed = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; var after = JsonSerializer.Serialize(new AfterState(token, cause, owed), Json); - await handle.WriteResultAsync(Result(owner, classes, row, after), cancellationToken); - await handle.CommitAsync(cancellationToken); + using var budget = new CancellationTokenSource(CompletionBudget); + try + { + await handle.WriteResultAsync(Result(owner, classes, row, after), budget.Token); + await handle.CommitAsync(budget.Token); + return outcome; + } + catch (Exception failure) when ( + outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain + && failure is AuditWriteFailedException or DbException or OperationCanceledException or IOException) + { + return FederationActOutcome.Uncertain; + } } private static PlatformResult Result(FederationBrokerOwner owner, IReadOnlyList classes, Row? row, string? after) => new( @@ -274,6 +354,14 @@ private static List ClassesOf(FederationBrokerFacts facts, Row? row, int return classes; } + /// + /// A live connection row refuses the removal of a broker that reads: the tenant's own Delete retires that pair. A broker + /// that does not read is the exception (ADR-0099 Amendment 12 item 1), because the tenant's Delete treats it as foreign + /// and fails (Amendment 9 item 5), so nothing else could ever remove it; it already fails closed, and the tenant's + /// next readback finds it absent. + /// + private static bool RefusesRemoval(FederationBrokerFacts facts, Row? row) => facts.Readable && IsLive(row); + private static bool IsLive(Row? row) => row is { Deleted: false } && !string.Equals(row.State, "Deleted", StringComparison.Ordinal); private static string RowState(Row? row) => row is null ? "absent" : IsLive(row) ? row.State : "deleted"; @@ -294,7 +382,7 @@ private static async Task> ReadRowsAsync( /// /// The mapper count of each owner, one after another, until the page's time runs out: the remainder is unknown, which - /// the report says as null and never as zero. A module runs one operation at a time (ADR-0040), and the provider's + /// the report counts as and never as zero. A module runs one operation at a time (ADR-0040), and the provider's /// own bulkhead would refuse a wider fan-out. /// private async Task> CountMappersAsync( diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index e1b32aa9..60e92aba 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -53,6 +53,31 @@ public void Federation_Adapter_Admits_Only_The_Enumerated_Routes() "Fix: build every provider route in KeycloakFederationRoutes, which admits only identity-provider/instances[/{alias}[/mappers]] (ADR-0099)"); } + [Fact] + public void The_one_admitted_query_is_the_listing_page_and_no_provider_file_builds_another() + { + // ADR-0099 Amendment 11 item 7: the census admits the listing's collection route with its one exact query. The + // route builder names the three fragments of it, in order, and no other query fragment exists in the adapter. + var adapter = Sources().Where(source => source.Key.StartsWith(AdapterDirectory, StringComparison.Ordinal)).ToList(); + QueryLiterals(adapter.Single(source => source.Key == RoutesSource).Value).Should().Equal( + ["?first=", "&max=", "&briefRepresentation=false"]); + adapter.Where(source => source.Key != RoutesSource).SelectMany(source => QueryLiterals(source.Value)).Should().BeEmpty( + "Fix: a provider query string is built in KeycloakFederationRoutes alone"); + } + + [Fact] + public void The_query_detector_sees_a_planted_fragment() + { + QueryLiterals("var uri = \"identity-provider/instances?search=\" + term; var x = \"&briefRepresentation=false\";") + .Should().Equal(["identity-provider/instances?search=", "&briefRepresentation=false"]); + QueryLiterals("var clean = \"identity-provider/instances\";").Should().BeEmpty(); + } + + /// The string literals of a source that hold a query separator, with whole-line comments set aside first. + private static List QueryLiterals(string source) => + [.. Regex.Matches(Regex.Replace(source, @"^\s*//.*$", string.Empty, RegexOptions.Multiline), @"""(?:[^""\\\r\n]|\\.)*""") + .Select(match => match.Value[1..^1]).Where(literal => literal.Contains('?') || literal.Contains('&'))]; + [Fact] public void The_route_detector_refuses_planted_routes() { diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 880b74f2..afca3a2b 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -317,7 +317,9 @@ public void Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Opera // ADR-0099 Amendment 10: the report, the remove and the disable are reachable from the federation routes alone, // through the one owner, and the operator's provider port is held by that owner and the adapter that implements // it. The tenant runner holds neither, so the rule that the tenant's provider port is the runner's alone stands. - SourceScan.FilesContaining(SourceScan.SourceRoot, "IFederationBrokerOperations", except: null) + // The scan names the owner's class, not only its port: every file naming the interface names this substring too, so a + // holder of the concrete owner is found as well. + SourceScan.FilesContaining(SourceScan.SourceRoot, "FederationBrokerOperations", except: null) .Should().BeEquivalentTo( [ "LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs", @@ -339,6 +341,27 @@ public void Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Opera "the operator's provider port is held by the owner, its adapter and the composition that selects it"); } + [Fact] + public void The_Federation_Port_Census_Finds_A_Planted_Holder_Of_Either_Port_Or_The_Concrete_Owner() + { + var planted = Directory.CreateTempSubdirectory("federation-holder-"); + try + { + File.WriteAllText(Path.Combine(planted.FullName, "ViaPort.cs"), "class A(IFederationBrokerOperations operations) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaOwner.cs"), "class B(FederationBrokerOperations owner) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaProvider.cs"), "class C(IFederationOperator provider) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "Clean.cs"), "class D(IFederationProvider tenantProvider) { }"); + + SourceScan.FilesContaining(planted.FullName, "FederationBrokerOperations", except: null) + .Should().BeEquivalentTo(["ViaPort.cs", "ViaOwner.cs"]); + SourceScan.FilesContaining(planted.FullName, "IFederationOperator", except: null).Should().BeEquivalentTo(["ViaProvider.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + } + private const string FederationOperationsFile = "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs"; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs index d09896be..64dc2ed5 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs @@ -41,14 +41,19 @@ public sealed class FederationDatabase(SchemaFixture schema) : IAsyncLifetime { private DisposableSchemaDatabase? _database; + /// A tenant with no connection row, for the case where a live row appears after the intent. + public static readonly Guid TenantC = Guid.Parse("33333333-3333-7333-8333-333333333333"); + public string PlatformConnectionString => _database!.PlatformConnectionString; + public string AppConnectionString => _database!.AppConnectionString; + public async Task InitializeAsync() { _database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); await using (var owner = await PostgresFixture.OpenAsync(_database.MigrationConnectionString)) { - foreach (var (tenant, slug) in new[] { (SchemaFixture.TenantA, "alpha"), (SchemaFixture.TenantB, "beta") }) + foreach (var (tenant, slug) in new[] { (SchemaFixture.TenantA, "alpha"), (SchemaFixture.TenantB, "beta"), (FederationDatabase.TenantC, "gamma") }) { await using var transaction = await owner.BeginTransactionAsync(); await SchemaQueries.ExecuteAsync(owner, transaction, $"SET LOCAL app.tenant_id = '{tenant:D}'"); @@ -165,19 +170,45 @@ public async Task A_report_the_provider_cannot_answer_is_unavailable_and_writes_ rows[0].Metadata.Should().Contain("CHG-1", "the entry row is a sentinel row, which carries the ticket"); } - [Fact] - public async Task A_remove_of_a_broker_with_a_live_row_is_refused_before_anything_is_written_or_sent() + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + public async Task A_remove_of_a_broker_that_reads_with_a_live_row_is_refused_before_anything_is_written_or_sent(bool readable, bool conforms) { - var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable: false) }; + // Readable and drifted, or readable and clean: the tenant's own Delete retires such a pair, so the operator refuses. + var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable, conforms), InspectedMappers = conforms ? 0 : 1 }; var admission = Admission(PlatformOperations.FederationRemove); var result = await Service(operations).RemoveAsync(admission, Alias(LiveA)); result.Outcome.Should().Be(FederationActOutcome.LiveConnection); - operations.Removed.Should().BeEmpty("a live connection row refuses, for an unreadable broker too"); + operations.Removed.Should().BeEmpty(); (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); } + [Fact] + public async Task A_remove_of_an_unreadable_owned_broker_is_applied_even_with_a_live_row_because_the_tenants_delete_cannot_reach_it() + { + // The tenant's Delete reports an unreadable owned broker as foreign and fails, so a live row would otherwise hold it + // forever (ADR-0099 Amendment 12). The rows record the live state the operator found, and the tenant's row is left. + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.Applied, SchemaFixture.TenantA, LiveA)); + operations.Removed.Should().ContainSingle(); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("rowState").GetString().Should().Be("Draft", "the live row is recorded as found"); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Equal("unreadable_owned"); + (await ScalarAsync("SELECT count(*) FROM public.federation_connections WHERE id = @id AND state <> 'Deleted'", LiveA)) + .Should().Be(1, "the operator never writes the tenant's row"); + } + [Theory] [InlineData("tombstone")] [InlineData("absent")] @@ -266,19 +297,228 @@ public async Task A_failed_intent_write_stops_the_remove_before_the_provider_is_ (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); } + [Theory] + [InlineData("remove", FederationOperatorOutcome.Applied)] + [InlineData("remove", FederationOperatorOutcome.Uncertain)] + [InlineData("disable", FederationOperatorOutcome.Applied)] + public async Task A_completion_that_cannot_be_written_after_a_change_is_answered_as_the_unknown_outcome_and_leaves_the_intent_standing( + string act, FederationOperatorOutcome provider) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = provider, DisableOutcome = provider }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations, failResult: true); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain, "the change was sent and its record was not written"); + (remove ? operations.Removed : operations.Disabled).Should().ContainSingle("the provider call had been made"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, remove ? "platform.federation.remove_attempt" : "platform.federation.disable_attempt"); + } + [Fact] - public async Task A_failed_completion_write_leaves_the_intent_row_standing_after_the_effect() + public async Task A_completion_that_cannot_be_written_when_nothing_changed_is_still_the_audit_failure() { var owner = OwnerOf(Guid.CreateVersion7()); - var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = FederationOperatorOutcome.Refused }; var admission = Admission(PlatformOperations.FederationRemove); var act = async () => await Service(operations, failResult: true).RemoveAsync(admission, owner.Alias); - await act.Should().ThrowAsync(); - operations.Removed.Should().ContainSingle("the provider call had been made"); - (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( - PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + await act.Should().ThrowAsync("a refused change recorded nowhere is safe to repeat"); + } + + [Fact] + public async Task A_caller_that_leaves_while_the_provider_changes_the_broker_is_recorded_as_uncertain_on_a_detached_budget() + { + var owner = OwnerOf(Guid.CreateVersion7()); + using var caller = new CancellationTokenSource(); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeRemove = () => + { + // The request is aborted after the change may have been sent: the adapter rethrows the caller's cancellation. + caller.Cancel(); + throw new OperationCanceledException(caller.Token); + }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias, caller.Token); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("uncertain"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeTrue("the change may have deleted the links"); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_marker_that_names_another_tenant_than_its_row_is_not_owned_and_writes_no_tenant_row(string act) + { + // The tombstone is tenant A's, and the instance's marker names tenant B: never touched, and no row names B. + var owner = OwnerOf(TombstoneA, SchemaFixture.TenantB); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.NotOwned); + operations.Removed.Should().BeEmpty(); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_live_row_that_appears_after_the_intent_refuses_the_delete_and_is_recorded_without_calling_the_provider() + { + // Amendment 10 item 3: the row is read again immediately before the delete. A tenant commits its row at that moment. + var connection = Guid.CreateVersion7(); + var owner = OwnerOf(connection, FederationDatabase.TenantC); + var operations = new Scripted { Inspected = Facts(owner, readable: true, conforms: false), InspectedMappers = 1 }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations(Scope(false, false, afterIntent: async () => + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, FederationDatabase.TenantC); + await InsertAsync(app, transaction, connection, FederationDatabase.TenantC, IdentityMembershipFixture.AdminA, + DateTimeOffset.UtcNow.AddMinutes(-5)); + await transaction.CommitAsync(); + }), operations); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.LiveConnection, FederationDatabase.TenantC, connection)); + operations.Removed.Should().BeEmpty("the provider is not called once the row is live"); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("rowState").GetString().Should().Be("absent", "the first read found no row"); + using var after = JsonDocument.Parse(rows[2].After); + (after.RootElement.GetProperty("outcome").GetString(), after.RootElement.GetProperty("cause").GetString()) + .Should().Be(("refused", "live_connection")); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeFalse("nothing was changed"); + } + + [Theory] + [InlineData(FederationOperatorOutcome.Uncertain, "uncertain", FederationActOutcome.Uncertain)] + [InlineData(FederationOperatorOutcome.Unavailable, "unavailable", FederationActOutcome.Unavailable)] + [InlineData(FederationOperatorOutcome.Refused, "refused", FederationActOutcome.Refused)] + [InlineData(FederationOperatorOutcome.NotOwned, "not_owned", FederationActOutcome.NotOwned)] + public async Task A_provider_that_does_not_apply_a_disable_is_recorded_in_the_completion_row( + FederationOperatorOutcome provider, string recorded, FederationActOutcome expected) + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false), DisableOutcome = provider }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be(recorded); + } + + [Theory] + [InlineData(FederationInspectionStatus.Unavailable, FederationActOutcome.Unavailable)] + [InlineData(FederationInspectionStatus.Absent, FederationActOutcome.NotFound)] + [InlineData(FederationInspectionStatus.NotOwned, FederationActOutcome.NotOwned)] + public async Task A_disable_the_provider_cannot_inspect_or_that_names_nothing_it_owns_sends_nothing_and_writes_no_tenant_row( + FederationInspectionStatus status, FederationActOutcome expected) + { + var operations = new Scripted { InspectedStatus = status }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, Alias(Guid.CreateVersion7())); + + result.Outcome.Should().Be(expected); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_provider_that_cannot_inspect_a_remove_sends_nothing_and_writes_no_tenant_row() + { + var operations = new Scripted { InspectedStatus = FederationInspectionStatus.Unavailable }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, Alias(Guid.CreateVersion7())); + + result.Outcome.Should().Be(FederationActOutcome.Unavailable); + operations.Removed.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_report_counts_the_mappers_of_a_healthy_broker_and_names_one_that_carries_drift() + { + var healthy = OwnerOf(LiveA); + var operations = new Scripted { Listed = [Facts(healthy)] }; + operations.MapperCounts[healthy.Alias] = 2; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + var item = result.Items.Should().ContainSingle().Which; + (string.Join('+', item.Classes), item.Mappers, item.RowState).Should().Be(("nonconforming", 2, "Draft")); + result.Unread.Should().Be(0); + } + + [Fact] + public async Task A_broker_whose_mappers_could_not_be_read_is_counted_as_unread_and_never_reported_as_clean() + { + var first = OwnerOf(LiveA); + var second = OwnerOf(LiveB, SchemaFixture.TenantB); + var operations = new Scripted { Listed = [Facts(first), Facts(second)] }; + operations.MapperCounts[first.Alias] = null; + operations.MapperDeadlines.Add(second.Alias); + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Ok); + result.Items.Should().BeEmpty("a broker with no mapper count is unknown, and an unknown broker is not a finding"); + result.Unread.Should().Be(2, "the page says how many healthy-looking brokers it could not clear"); + } + + [Theory] + [InlineData("report")] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_transient_database_fault_is_the_unavailable_owner_with_its_cause_and_never_a_raw_failure(string act) + { + var fault = new NpgsqlException("the database is not reachable", new IOException("reset")); + var owner = OwnerOf(Guid.CreateVersion7()); + var service = new FederationBrokerOperations(new ThrowingScope(fault), new Scripted { Inspected = Facts(owner, readable: false) }); + + var call = act switch + { + "report" => (Func)(async () => await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 5)), + "remove" => async () => await service.RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias), + _ => async () => await service.DisableAsync(Admission(PlatformOperations.FederationDisable), owner.Alias), + }; + + (await call.Should().ThrowAsync()).Which.InnerException.Should().BeSameAs(fault); + } + + [Fact] + public async Task A_database_fault_that_is_not_transient_surfaces_as_the_defect_it_is() + { + var defect = new InvalidOperationException("a defect"); + var service = new FederationBrokerOperations(new ThrowingScope(defect), new Scripted()); + + var report = async () => await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 5); + + (await report.Should().ThrowAsync()).Which.Should().BeSameAs(defect); } [Theory] @@ -377,19 +617,27 @@ await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sq private FederationBrokerOperations Service(Scripted operations, bool failIntent = false, bool failResult = false) => new(Scope(failIntent, failResult), operations); - private PlatformAdminScope Scope(bool failIntent, bool failResult) + private PlatformAdminScope Scope(bool failIntent, bool failResult, Func? afterIntent = null) { var platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); var store = AuditStore(); return new PlatformAdminScope( new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), - failIntent || failResult ? new FailingStore(store, failIntent, failResult) : store, + failIntent || failResult || afterIntent is not null ? new FailingStore(store, failIntent, failResult, afterIntent) : store, new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); } private static PlatformAdmission Admission(PlatformOperation operation, string? ticket = null) => TestPlatformAdmissions.Admission( operation, ticket, correlationId: "00-federation-" + Guid.NewGuid().ToString("N")); + private async Task ScalarAsync(string sql, Guid id) + { + await using var connection = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)connection); + command.Parameters.AddWithValue("id", id); + return (long)(await command.ExecuteScalarAsync())!; + } + private async Task> RowsAsync(string correlation) { await using var connection = await PostgresFixture.OpenAsync(database.PlatformConnectionString); @@ -460,36 +708,50 @@ public Task WriteResultAsync(PlatformResult result, CancellationToken cancellati } } + /// A scope whose database cannot be reached: entering it fails with the fault it was given. + private sealed class ThrowingScope(Exception fault) : IPlatformAdminScope + { + public Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => throw fault; + } + private sealed record AuditRow(string Operation, string Outcome, Guid Tenant, string Metadata, string Before, string After, string EntityId); /// Fails the intent or the completion row of the operator, as an outage at that moment would. - private sealed class FailingStore(IServiceScopeFactory inner, bool failIntent, bool failResult) : IServiceScopeFactory + private sealed class FailingStore(IServiceScopeFactory inner, bool failIntent, bool failResult, Func? afterIntent = null) + : IServiceScopeFactory { - public IServiceScope CreateScope() => new Scope(inner.CreateScope(), failIntent, failResult); + public IServiceScope CreateScope() => new Scope(inner.CreateScope(), failIntent, failResult, afterIntent); - private sealed class Scope(IServiceScope inner, bool failIntent, bool failResult) : IServiceScope, IServiceProvider + private sealed class Scope(IServiceScope inner, bool failIntent, bool failResult, Func? afterIntent) : IServiceScope, IServiceProvider { public IServiceProvider ServiceProvider => this; public object? GetService(Type type) => type == typeof(IAuditStore) - ? new Decorator(inner.ServiceProvider.GetRequiredService(), failIntent, failResult) + ? new Decorator(inner.ServiceProvider.GetRequiredService(), failIntent, failResult, afterIntent) : inner.ServiceProvider.GetService(type); public void Dispose() => inner.Dispose(); } - private sealed class Decorator(IAuditStore store, bool failIntent, bool failResult) : IAuditStore + private sealed class Decorator(IAuditStore store, bool failIntent, bool failResult, Func? afterIntent) : IAuditStore { public Task WritePlatformScopeAsync(AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => store.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); - public Task WritePlatformOperatorIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, + public async Task WritePlatformOperatorIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, - CancellationToken cancellationToken = default) => - failIntent - ? throw new AuditWriteFailedException("forced intent failure") - : store.WritePlatformOperatorIntentAsync(entry, admission, connection, transaction, cancellationToken); + CancellationToken cancellationToken = default) + { + if (failIntent) throw new AuditWriteFailedException("forced intent failure"); + await store.WritePlatformOperatorIntentAsync(entry, admission, connection, transaction, cancellationToken); + // Between the intent and the provider call, as a tenant that commits a row at that moment would. + if (afterIntent is not null) await afterIntent(); + } public Task WritePlatformOperatorResultAsync(AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, @@ -533,6 +795,8 @@ private sealed class Scripted : IFederationOperator public FederationOperatorOutcome RemoveOutcome { get; set; } = FederationOperatorOutcome.Applied; public FederationOperatorOutcome DisableOutcome { get; set; } = FederationOperatorOutcome.Applied; public Func? BeforeRemove { get; set; } + public Dictionary MapperCounts { get; } = new(StringComparer.Ordinal); + public HashSet MapperDeadlines { get; } = new(StringComparer.Ordinal); public List Calls { get; } = []; public List Offsets { get; } = []; public List MapperCalls { get; } = []; @@ -549,7 +813,7 @@ public Task ListAsync(int offset, int limit, CancellationT return Task.FromResult(new FederationBrokerPage(FederationOperatorStatus.Ok, page, 0, page.Count)); } - public Task InspectAsync(string alias, CancellationToken cancellationToken = default) + public Task InspectAsync(string brokerAlias, CancellationToken cancellationToken = default) { Calls.Add("inspect"); return Task.FromResult(InspectedStatus switch @@ -566,7 +830,8 @@ public Task InspectAsync(string alias, CancellationT Calls.Add("mappers"); Events?.Add("mappers"); MapperCalls.Add(owner.Alias); - return Task.FromResult(0); + if (MapperDeadlines.Contains(owner.Alias)) throw new OperationCanceledException("the page's time ran out"); + return Task.FromResult(MapperCounts.TryGetValue(owner.Alias, out var count) ? count : 0); } public async Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index cc1d0546..ccb868d7 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -670,7 +670,8 @@ public async Task A_Federation_Report_Passes_Its_Page_On_Clamps_The_Limit_And_An call.Admission.Operation.Should().BeSameAs(PlatformOperations.FederationReport); call.Admission.Ticket.Should().Be("CHG-5"); var text = await response.Content.ReadAsStringAsync(); - text.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next\"").And.Contain("\"scanned\":3").And.Contain("\"ignored\":1"); + text.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next\"").And.Contain("\"scanned\":3").And.Contain("\"ignored\":1") + .And.Contain("\"mappersUnread\":4"); } [Theory] @@ -738,21 +739,39 @@ public async Task A_Federation_Act_Names_Only_A_Derived_Alias_And_Calls_Nothing_ } [Theory] - [InlineData(FederationActOutcome.AlreadyApplied, HttpStatusCode.OK, "already_applied")] - [InlineData(FederationActOutcome.NotFound, HttpStatusCode.NotFound, "not_found")] - [InlineData(FederationActOutcome.NotOwned, HttpStatusCode.Conflict, "lockey_not_owned")] - [InlineData(FederationActOutcome.LiveConnection, HttpStatusCode.Conflict, "lockey_live_connection")] - [InlineData(FederationActOutcome.NotApplicable, HttpStatusCode.Conflict, "lockey_not_applicable")] - [InlineData(FederationActOutcome.Refused, HttpStatusCode.Conflict, "lockey_provider_refused")] - public async Task A_Federation_Act_Answers_Each_Outcome_With_Its_Status_And_The_Reason_On_The_Field_It_Concerns( - FederationActOutcome outcome, HttpStatusCode status, string expected) + [InlineData(FederationActOutcome.NotOwned, "owner", "lockey_not_owned")] + [InlineData(FederationActOutcome.LiveConnection, "connection", "lockey_live_connection")] + [InlineData(FederationActOutcome.NotApplicable, "class", "lockey_not_applicable")] + [InlineData(FederationActOutcome.Refused, "provider", "lockey_provider_refused")] + public async Task A_Federation_Act_Refusal_Is_A_409_With_Its_Reason_On_The_Field_It_Concerns( + FederationActOutcome outcome, string field, string reason) { _brokers.Act = new FederationActResult(outcome); var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var reasons = body.RootElement.GetProperty("errors").EnumerateObject().ToDictionary( + property => property.Name, property => property.Value[0].GetProperty("key").GetString()); + reasons.Should().Equal(new Dictionary { [field] = reason }, "the reason is on the field it concerns, and only there"); + } + + [Theory] + [InlineData(FederationActOutcome.AlreadyApplied, HttpStatusCode.OK, "already_applied", false)] + [InlineData(FederationActOutcome.NotFound, HttpStatusCode.NotFound, null, false)] + public async Task A_Federation_Act_Answers_A_Repeat_Or_A_Missing_Alias_Without_Owing_An_Account_Review( + FederationActOutcome outcome, HttpStatusCode status, string? token, bool owed) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}"); + response.StatusCode.Should().Be(status); - (await response.Content.ReadAsStringAsync()).Should().Contain(expected); + if (token is null) return; + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + (body.RootElement.GetProperty("outcome").GetString(), body.RootElement.GetProperty("accountReviewOwed").GetBoolean()).Should().Be((token, owed)); } [Fact] @@ -776,12 +795,54 @@ public async Task An_Unknown_Or_Unavailable_Federation_Outcome_Is_A_Retryable_50 [Fact] public async Task A_Failed_Federation_Audit_Write_Is_The_Retryable_Audit_503_And_Is_Counted() { + using var counted = Counted(); _brokers.Failure = new AuditWriteFailedException("forced"); - var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + var act = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + var report = await Call(HttpMethod.Get, Fed, Valid()); + + foreach (var response in new[] { act, report }) + { + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + await AssertProblem(response, "audit_unavailable"); + } + + counted.AuditFailures.Should().Be(2); + } + + [Theory] + [InlineData("report")] + [InlineData("remove")] + public async Task A_Database_Fault_The_Federation_Owner_Translates_Is_A_Retryable_503_Without_An_Unknown_Outcome(string act) + { + using var federation = new FederationListener(); + _brokers.Failure = new OperatorRecoveryUnavailableException(cause: new InvalidOperationException("the database is not reachable")); + + var response = act == "report" + ? await Call(HttpMethod.Get, Fed, Valid()) + : await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); - await AssertProblem(response, "audit_unavailable"); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + body.RootElement.TryGetProperty("errors", out _).Should().BeFalse("nothing was changed, so no unknown outcome is named"); + federation.Calls.Should().Equal([(act == "report" ? "platform.federation.report" : "platform.federation.remove", "unavailable")]); + } + + [Fact] + public async Task The_Federation_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() + { + using var federation = new FederationListener(); + + (await Call(HttpMethod.Get, Fed, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + _brokers.Act = new FederationActResult(FederationActOutcome.AlreadyApplied); + (await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Get, Fed + "?limit=0", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + federation.Calls.Should().Equal( + ("platform.federation.report", "ok"), ("platform.federation.remove", "applied"), ("platform.federation.disable", "already_applied")); } [Theory] @@ -1356,10 +1417,44 @@ public Task ToggleAsync( } } + /// Captures the operation and outcome labels of every federation call counted while it is alive. + private sealed class FederationListener : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly ConcurrentQueue<(string Operation, string Outcome)> _calls = new(); + + public FederationListener() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == PlatformOperatorMetrics.FederationCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value as string; + if (tag.Key == "outcome") outcome = tag.Value as string; + } + + _calls.Enqueue((operation ?? string.Empty, outcome ?? string.Empty)); + }); + _listener.Start(); + } + + public IReadOnlyList<(string Operation, string Outcome)> Calls => [.. _calls]; + + public void Dispose() => _listener.Dispose(); + } + private sealed class RecordingBrokers : IFederationBrokerOperations { public List<(string Operation, PlatformAdmission Admission, string? Argument, int Limit)> Calls { get; } = []; - public FederationReportResult Report { get; set; } = new(FederationReportOutcome.Ok, [], "next", 3, 1); + public FederationReportResult Report { get; set; } = new(FederationReportOutcome.Ok, [], "next", 3, 1, 4); public FederationActResult Act { get; set; } = new(FederationActOutcome.Applied, Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501"), Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502")); public Exception? Failure { get; set; } @@ -1371,11 +1466,11 @@ public Task ReportAsync( return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Report); } - public Task RemoveAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) => - Record("remove", admission, alias); + public Task RemoveAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + Record("remove", admission, brokerAlias); - public Task DisableAsync(PlatformAdmission admission, string alias, CancellationToken cancellationToken = default) => - Record("disable", admission, alias); + public Task DisableAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + Record("disable", admission, brokerAlias); private Task Record(string operation, PlatformAdmission admission, string alias) { diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs index 01369afe..5cda2bda 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs @@ -58,17 +58,29 @@ public async Task The_operator_lists_the_realm_in_bounded_pages_and_classifies_o try { var owned = new Dictionary(StringComparer.Ordinal); + var seen = new List(); var ignored = 0; + var scanned = 0; for (var offset = 0; ; offset += 2) { var page = await op.ListAsync(offset, 2); page.Status.Should().Be(FederationOperatorStatus.Ok, "the federation client's one role is enough to list"); page.Scanned.Should().BeLessThanOrEqualTo(2); - foreach (var facts in page.Owned) owned[facts.Owner.Alias] = facts; + foreach (var facts in page.Owned) + { + owned[facts.Owner.Alias] = facts; + seen.Add(facts.Owner.Alias); + } + ignored += page.Ignored; + scanned += page.Scanned; if (page.Scanned < 2) break; } + // The pages are disjoint and complete: nothing is listed twice, and every instance the realm holds is scanned once. + seen.Should().OnlyHaveUniqueItems("offset paging must not repeat an instance across pages"); + scanned.Should().Be((await admin.GetAsync("identity-provider/instances")).GetArrayLength()); + owned[healthy.Alias].Should().Match(facts => facts.Readable && facts.Conforms && facts.Enabled, "the pinned provider masks the secret in the listing, so a healthy broker reads as conforming"); owned[broken.Alias].Should().Match(facts => !facts.Readable && !facts.Conforms); @@ -147,8 +159,9 @@ public async Task The_operator_disables_an_unreadable_broker_by_sending_back_wha var after = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetRawText())!.AsObject(); after["enabled"]!.GetValue().Should().BeFalse(); - after["config"]!["clientSecret"]!.GetValue().Should().Be(FederationClientSecret.MaskLiteral, - "the provider kept the stored secret when it read its own mask back"); + // The administrative read masks the secret whether or not it was kept, so this asserts the shape only; the next + // test proves the secret was kept, by signing a person in through the broker afterwards. + after["config"]!["clientSecret"]!.GetValue().Should().Be(FederationClientSecret.MaskLiteral); // Nothing else moved: compare everything the provider computes on each read away. foreach (var key in new[] { "internalId", "types" }) { @@ -165,4 +178,33 @@ public async Task The_operator_disables_an_unreadable_broker_by_sending_back_wha await admin.DeleteAsync("identity-provider/instances/" + broken.Alias); } } + + [Fact] + public async Task The_operator_disable_keeps_the_stored_secret_so_a_person_can_sign_in_through_the_broker_once_it_is_enabled_again() + { + var owner = federation.OwnerA; + await EnableAsync(owner, "federation-idp-a", FederationKeycloakFixture.IdpSecretA); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + const string person = "demo-admin@tenant-a.test"; + + // Control: the broker reaches the link confirmation, which needs its client secret at the identity provider. + using (var before = Keycloak.Browser()) + (await before.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().Be(BrokeredStop.ConfirmationAbandoned); + + (await op.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Applied); + using (var disabled = Keycloak.Browser()) + (await disabled.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().NotBe(BrokeredStop.ConfirmationAbandoned, "a disabled broker signs nobody in"); + + // Enabled again out of band, with the representation the provider returns and its mask. If the operator's write had + // stored the mask literal as the secret, this write would keep it so, and the sign-in below could not succeed. + var returned = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + owner.Alias)).GetRawText())!.AsObject(); + returned["enabled"] = true; + (await admin.PutAsync("identity-provider/instances/" + owner.Alias, returned)).Should().Be(HttpStatusCode.NoContent); + using var after = Keycloak.Browser(); + (await after.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().Be(BrokeredStop.ConfirmationAbandoned, "the stored secret survived the disable"); + } } diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs index 95fb698b..0528ce5f 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Collections.Immutable; using System.Net; +using System.Reflection; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; @@ -616,6 +617,22 @@ await adapter.DisableAsync(owner), await adapter.RemoveAsync(owner), .NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme").And.NotContain("idp.example.com"); } + [Fact] + public void The_operator_ports_result_types_can_carry_no_secret_or_provider_text_because_they_declare_no_member_that_could() + { + // ToString is a constant on these records, so a text check cannot see a new member. The members can be seen: each is an + // owner, a flag, a count, a closed status or a protocol, and there is no string for a display name, issuer or secret. + var closed = new HashSet + { + typeof(FederationBrokerOwner), typeof(bool), typeof(int), typeof(FederationBrokerProtocol?), typeof(FederationOperatorStatus), + typeof(FederationInspectionStatus), typeof(FederationBrokerFacts), typeof(IReadOnlyList), + }; + const BindingFlags declared = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; + + foreach (var type in new[] { typeof(FederationBrokerFacts), typeof(FederationBrokerPage), typeof(FederationBrokerInspection) }) + type.GetProperties(declared).Select(property => property.PropertyType).Should().BeSubsetOf(closed, type.Name); + } + private static FederationClientSecret Fresh() => FederationClientSecret.TryCreate(TenantSecret, out var secret) ? secret! : throw new InvalidOperationException(); @@ -689,8 +706,8 @@ protected override async Task SendAsync(HttpRequestMessage if (ListDefect == "object") return Json(HttpStatusCode.OK, new JsonObject()); var query = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query); var page = Brokers.Values.OrderBy(broker => broker["alias"]!.GetValue(), StringComparer.Ordinal) - .Skip(int.Parse(query["first"]!)); - if (!ListIgnoresPaging) page = page.Take(int.Parse(query["max"]!)); + .Skip(int.Parse(query["first"]!, System.Globalization.CultureInfo.InvariantCulture)); + if (!ListIgnoresPaging) page = page.Take(int.Parse(query["max"]!, System.Globalization.CultureInfo.InvariantCulture)); return Json(HttpStatusCode.OK, new JsonArray([.. page.Select(View)])); } var rest = path[(prefix.Length + 1)..]; diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index d7d4f510..ab3680f7 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -271,6 +271,11 @@ dead-lettered row is a sibling seam, `WriteOperatorRecoveryAsync` carries the admitted operator and the fence before and after, the row names the real event tenant with no actor and no ticket, and the outbox role needs no new policy arm because it bypasses row security and already holds `INSERT`. +Absent optional causal IDs are valid and do not alone invalidate the stored trace. +Closed terminal values use bounded metadata; `Reason` stays for platform entry. +Audit failure retains terminal work for retry without delivery; uncertain COMMIT +is reconciled before retry and cannot duplicate a completed terminal audit. + The platform scope's intent seam, `WritePlatformOperatorIntentAsync` ([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), is the sibling for an operator act whose effect is outside the database: the scope handle's checkpoint writes @@ -278,10 +283,6 @@ the intent row on the operation's attempt slug with the outcome `indeterminate`, it, and only then lets the provider be called; the result row follows on a fresh transaction. An effect that fails afterwards leaves the intent row standing, and the result row is refused before an intent that its operation declares. -Absent optional causal IDs are valid and do not alone invalidate the stored trace. -Closed terminal values use bounded metadata; `Reason` stays for platform entry. -Audit failure retains terminal work for retry without delivery; uncertain COMMIT -is reconciled before retry and cannot duplicate a completed terminal audit. The existing outbox role gains audit INSERT-only in the Audit chain, with exact grants owned by [Database Standards](../standards/05-database.md#grant-matrix). diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index df2ac851..256efc2c 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1339,22 +1339,24 @@ platform scope of Amendment 17 writes one result row and closes at commit, which nothing durable before such an effect. [ADR-0099](0099-confined-tenant-federation.md) Amendment 11 records the implementation. -- **One new witness-bound write, the fifteenth.** `IAuditStore.WritePlatformOperatorIntentAsync` - writes the intent row of a platform-scope act on its `PlatformOperation.AttemptAuditSlug`, - with the outcome `indeterminate`, the same closed reason, correlation id and - `metadata.operator` as the result row, the actor NULL and the class MUST. Like the - result method it is bound to the admission, takes the real target tenant, refuses a - ticket on a tenant-readable row and refuses the identity module's own rows. An - operation with no attempt slug, or one that does not enter the platform scope (the - offline rebind, whose intent has its own method), presents none. +- **One new witness-bound write, the fifteenth.** + `IAuditStore.WritePlatformOperatorIntentAsync` writes the intent row of a + platform-scope act on its `PlatformOperation.AttemptAuditSlug`, with the outcome + `indeterminate`, the same closed reason, correlation id and `metadata.operator` as + the result row, the actor NULL and the class MUST. Like the result method it is bound + to the admission, takes the real target tenant, refuses a ticket on a tenant-readable + row and refuses the identity module's own rows. An operation with no attempt slug, or + one that does not enter the platform scope (the offline rebind, whose intent has its + own method), presents none. - **A checkpoint on the scope handle.** `IPlatformAdminScopeHandle.WriteIntentAsync` - writes that row on the work transaction, commits it, and continues the scope in a fresh - transaction on the same connection. It is allowed once, only for an operation that - declares an attempt slug, and the result row of such an operation is refused before it. - A failure to write or to commit the intent row throws `AuditWriteFailedException` and - the effect must not start; an effect that fails afterwards leaves the intent row - standing, as § 10 requires of the entry row. The scope still ends at the result row and - the commit, or by disposal, which rolls back whatever followed the checkpoint. + writes that row on the work transaction, commits it, and continues the scope in a + fresh transaction on the same connection. It is allowed once, only for an operation + that declares an attempt slug, and the result row of such an operation is refused + before it. A failure to write or to commit the intent row throws + `AuditWriteFailedException` and the effect must not start; an effect that fails + afterwards leaves the intent row standing, as § 10 requires of the entry row. The + scope still ends at the result row and the commit, or by disposal, which rolls back + whatever followed the checkpoint. - **Declared like every off-path slug.** The attempt slugs are declared off-path MUST/SecurityEvent in the Tenancy catalogue source beside the entry and result slugs, and the scope refuses entry when any of them is undeclared. diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index d6864155..be69ce37 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1136,12 +1136,13 @@ realm users. 1. **Where the code lives.** `IFederationOperator` sits beside the tenant provider port and is held by the operator's owner, `FederationBrokerOperations` (Identity Infrastructure), and by the adapter that implements it, the operator half of the - same Keycloak class. A second instance of that class is built with its own resilience - pipeline of the fixed shape, so a sweep cannot starve a tenant's calls. The routes are - `GET /api/platform/v1/federation/brokers`, `POST .../{alias}/remove` and - `POST .../{alias}/disable`, behind the keys [ADR-0101](0101-platform-operator-authority.md) - § 5 fixed, `platform.federation.read` and `platform.federation.admin`, and each runs - the gate first. + same Keycloak class. A second instance of that class is built with its own + resilience pipeline of the fixed shape, so a sweep cannot starve a tenant's calls. + The routes are `GET /api/platform/v1/federation/brokers`, + `POST .../{alias}/remove` and `POST .../{alias}/disable`, behind the keys + [ADR-0101](0101-platform-operator-authority.md) § 5 fixed, + `platform.federation.read` and `platform.federation.admin`, and each runs the gate + first. 2. **The grant is an Identity-chain migration.** `federation_connections` is created in the Identity chain, which runs after the Platform chain, so the column grant of item 5 is a hand-written forward-only Identity migration. The raw-reader census of @@ -1149,9 +1150,9 @@ realm users. pinned whole: it reads by primary key through the four granted columns and sees tombstones, which the shared live predicate would hide. 3. **Two rows around the provider call.** The tenant path's pattern is the Decision's - § Intent-first operations, not Amendment 2. The platform scope could write one result - row and no row before a provider call, so the seam is the scope handle's checkpoint - and a fifteenth `IAuditStore` write + § Intent-first operations, not Amendment 2. The platform scope could write one + result row and no row before a provider call, so the seam is the scope handle's + checkpoint and a fifteenth `IAuditStore` write ([ADR-0044 Amendment 18](0044-audit-write-path.md)): one admission, an intent row with the outcome `indeterminate` on `platform.federation.remove_attempt` or `platform.federation.disable_attempt`, committed before the provider call, and a @@ -1181,6 +1182,12 @@ realm users. broker, for an unreadable owned broker as well. Such a broker is disabled by the operator and removed by the tenant's own Delete, which this step leaves as the residual Amendment 10 item 3 implies. + + > **Erratum (2026-11-20, Amendment 12 item 1).** The tenant's own Delete does not + > remove an unreadable owned broker: the tenant adapter reports it foreign + > (Amendment 9 item 5), the runner fails the Delete with an owner mismatch, and the + > row stays live. An unreadable owned broker with a live row therefore had no + > removal path at all. 6. **Disable sends back what the provider returned.** An unreadable owned broker cannot be rebuilt from the fixed profile, so the operator disable is the one provider write that does not build its body from the allow-list: it reads the instance, proves the @@ -1199,9 +1206,56 @@ realm users. the one paged listing of Amendment 10, and "adds no realm authority" holds. The route census admits the listing's collection route with its one exact query. 8. **Residual.** There is still no provider-side fence, so a tenant create that lands - after a sweep produces a new orphan, which the next report finds, and the disable is a - read and a write the tenant's own write can interleave with; the tenant's next readback - detects the drift. The account review stays a runbook step. + after a sweep produces a new orphan, which the next report finds, and the disable is + a read and a write the tenant's own write can interleave with; the tenant's next + readback detects the drift. The account review stays a runbook step. The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 12 — Federation operator steps: review round 1 corrections (2026-11-20) + +The first review round of Step 5 found one dead end and five places where the record +or the code said less than the behaviour. The maintainer chose item 1; items 2 to 6 +state, without changing Amendment 10's choice of option, what the implementation does. + +1. **An unreadable owned broker is removed even with a live row.** Amendment 10 item 3 + and Amendment 11 item 5 refuse a remove while a live row names the broker, for both + classes. The refusal applies to a broker that reads, whose tenant Delete works and + retires the pair. An unreadable owned broker is removed by the operator on its + marker proof, with a live row or without one: the tenant's Delete cannot reach it + (Amendment 9 item 5), it already fails closed, and the tenant's next readback finds + it absent, after which the tenant's own Delete tombstones the row. The operator + never writes the tenant's row. The rows record the live state found, and the account + review is owed as for any remove. Amendment 10 item 3 and Amendment 11 item 5 are + read accordingly, and a readable nonconforming broker is still disabled, not removed. +2. **An unread mapper count is a page counter.** Amendment 11 item 4 reports an unread + count "unknown, never zero". A broker whose only possible class is an extra mapper + has no other class to carry the unknown, so the page carries it: `mappersUnread` + counts the healthy-looking live brokers whose mappers were not read (the provider + failed, its circuit was open or the page's ten seconds ran out). No item names them. +3. **The completion has its own budget.** After the intent row, the completion row is + written and committed on a bounded token of three seconds, detached from the + request, as the tenant runner completes on a detached token. A caller that leaves + while the provider works is recorded `uncertain`. A completion that cannot be + written after a change that landed or may have answers the unknown outcome (`503` + `dependency_unavailable` with the reason `outcome_unknown`) and leaves the intent + row standing; the account review is then owed if the broker is gone. When nothing + changed, a failed completion is the audit failure and is safe to repeat. A transient + database fault is a `503` with its cause in the log, and any failure to commit the + intent row stops the act. +4. **The ticket is recorded on the entry row.** Amendment 11 item 3 says the rows carry + no ticket. That holds for the intent and completion rows, which the tenant can read. + The platform scope's entry row, a row of the platform sentinel, carries the checked + ticket, as it does for every scope act. +5. **The completion row's audit outcome is `success`.** The scope's result row records + that the act ran to its end and is written only with that outcome. How the provider + call ended is the closed `outcome` of `after_state`, and an alert keys on it. +6. **An applied disable also owes the review.** Amendment 10 item 6 asks for the + follow-up note on both acts: `accountReviewOwed` is true for an applied remove, which + deleted the federated links, and for an applied disable, which closed the broker as + a sign-in option. An absent or already disabled broker owes none. + +The Decision, Status, Date and prior amendments of this record are unchanged, except +for the inline erratum beside Amendment 11 item 5 that item 1 records. Acceptance of +the linked records is not proof that anything they decide is implemented. diff --git a/docs/glossary.md b/docs/glossary.md index 65984e96..19dfb84a 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -13,8 +13,8 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | | **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | -| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act and an inspection run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | -| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, and cannot list or remove a realm user, so the account review a remove owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), [runbook](runbooks/federation-operator.md)). | +| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, the federation report, remove or disable ([Federation operator](#federation-operator)), or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act, an inspection and the federation acts run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | +| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, removes an unreadable owned broker even when a live row names it (the tenant's own Delete cannot reach one) and refuses to remove a broker that reads while a live row names it, and cannot list or remove a realm user, so the account review a remove owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), [runbook](runbooks/federation-operator.md)). | | **Operator recovery** | The operator's inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and its two fenced transitions: a **replay** resets one dead-lettered subscriber delivery and a **producer reset** resets one retry-exhausted outbox row, which renews its six-attempt budget. Each transition carries a **fence**, the state the operator read at inspection (for a replay the replay count, the dead-letter instant to the microsecond and the terminal reason; for a reset the attempts and the instant), and is refused with a stale-fence conflict when the row no longer shows it. It writes a MUST audit row on the same transaction. Job recovery and a dashboard do not exist ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md), [runbook](runbooks/operator-recovery.md)). | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | diff --git a/docs/modules/identity/providers.md b/docs/modules/identity/providers.md index 9924cd8e..c761da53 100644 --- a/docs/modules/identity/providers.md +++ b/docs/modules/identity/providers.md @@ -57,12 +57,12 @@ specification. | Boundary | Contract | |---|---| -| Ports | SharedKernel `IFederationProvider` and `IFederationEgressFetcher`; held only by `FederationOperationRunner` | +| Ports | SharedKernel `IFederationProvider` and `IFederationEgressFetcher`, held only by `FederationOperationRunner`; and `IFederationOperator`, the platform operator's port ([Operator access](#operator-access)), held only by its owner and the adapter | | Adapter | Internal sealed `KeycloakFederationProvider` in `LearnStack.Infrastructure.Identity.Federation`; direct HTTP, no SDK | | Fetcher | Internal sealed `FederationEgressFetcher` in the same namespace; the only fetcher of a tenant-supplied URL | | Selection | API `FederationComposition` replaces the fail-closed defaults only when `Federation:ClientSecret` is configured; `FederationAdapterFactory` is the only entry. The choice is made when the port is first resolved (it follows `ISecretProvider`), so an empty or invalid `Authentication:Tenant:Issuer` with the secret present refuses at that first resolution, not at host startup | | Credentials | Client `learnstack-federation-admin`; secret through `ISecretProvider` key `Federation:ClientSecret`; a fresh client-credentials token per port call | -| Resilience | `IProviderResilience`, configuration `Resilience:federation`: retry disabled, a 2.5 s timeout, circuit breaker on, a bulkhead of exactly 4 with no queue; these are fixed values, and composition refuses any other value at startup. The enabled breaker's parameters are bounded: failure ratio in (0, 1], minimum throughput 2 to 100, sampling duration 1 to 60 s, break duration 1 to 300 s (defaults 0.5, 10, 30 s, 30 s); a value outside a range refuses at startup | +| Resilience | `IProviderResilience` for the tenant calls and a second instance of the fixed shape, `IProviderResilience`, for the operator's, so a sweep cannot starve a tenant; configuration `Resilience:federation`: retry disabled, a 2.5 s timeout, circuit breaker on, a bulkhead of exactly 4 with no queue; these are fixed values, and composition refuses any other value at startup. The enabled breaker's parameters are bounded: failure ratio in (0, 1], minimum throughput 2 to 100, sampling duration 1 to 60 s, break duration 1 to 300 s (defaults 0.5, 10, 30 s, 30 s); a value outside a range refuses at startup | | Failures | Transport faults, 5xx and 429 are `FederationProviderException` (a `ProviderException`) inside the pipeline and leave as `Unavailable`; no provider text crosses the port | ### Admitted calls @@ -93,11 +93,12 @@ adapter never forwards its output either way. ### Operator access [ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md) and -Amendment 11 give the platform operator four acts on this realm through the same -confined client, `manage-identity-providers`, and no wider role: a **report** (the +Amendment 11 and 12 give the platform operator four calls on this realm through the +same confined client, `manage-identity-providers`, and no wider role: a **report** (the listing joined to the registry), an **inspection** of one alias, a **remove** of an -owner-marked broker that the registry no longer holds live, and a **disable** of an -owner-marked broker at the provider only. +owner-marked broker that the registry no longer holds live or that does not read +(Amendment 12 item 1), and a **disable** of an owner-marked broker at the provider +only. - The operator holds `IFederationOperator`, a port beside `IFederationProvider` that the tenant runner never holds; its adapter is the same internal sealed class with its @@ -108,7 +109,8 @@ owner-marked broker at the provider only. LearnStack's are counted and never named. - A remove deletes by alias and confirms the alias is gone. The provider deletes the federated links of that broker with it and keeps the accounts; the runbook owes an - account review. + account review. A live row refuses it for a broker that reads and not for one that + does not, because the tenant's own Delete cannot reach an unreadable broker. - A disable is the one provider write that is not the fixed profile: the broker can be unreadable (that is why it is disabled rather than rewritten), so the adapter reads the raw representation, sets `enabled=false` and puts it back with the secret mask @@ -116,7 +118,8 @@ owner-marked broker at the provider only. provider keeps the stored secret when it reads its own mask back. - A report is one page, no larger than the API's cursor limit, and its cursor is the provider offset the next page starts at. A listing the provider cannot answer reports - `unavailable`, never an empty realm. + `unavailable`, never an empty realm, and a mapper count that could not be read is + counted as unread, never as zero. - Federation destinations, secrets, display names, issuers and configuration values never cross the operator port: facts are an alias, an owner, readable, conforming, enabled, protocol and a mapper count. diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 5ce0ba89..8df020b5 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -151,7 +151,7 @@ unmarked row is one a shipped command already raises. | `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `federation_connections` and the realm's identity-provider instances | `platform.federation.report` `(off-path)` | **MUST** (`security-event`) | An operator's report of the brokers that are orphaned, unreadable or nonconforming ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `federation_report` is this slug's, with the operator attribution and ticket in `metadata.operator`; the scope reads and changes nothing, so it writes no result row, and it does not say which page was read | | `federation_connections` | `platform.federation.remove_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's removal of an orphaned or unreadable owned broker, written at the platform scope handle's checkpoint and committed before the provider call ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 11). Outcome `indeterminate`, under the tenant the owner marker names (never the platform sentinel, even when no `tenants` row exists), no actor, the closed reason `federation_remove`, the operator attribution in `metadata.operator`, no ticket because a tenant can read the row, and `before_state` holding the broker's classes and the connection row's state; the entity is the connection | -| `federation_connections` | `platform.federation.remove` `(off-path)` | **MUST** (`security-event`) | The completion row of that removal, written through the witness-bound result method on the work transaction that follows the checkpoint, in the same shape with the outcome `success` and `after_state` holding the closed outcome (`applied`, `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`) and whether an account review is owed, because the provider deletes the federated links with a broker. A lost completion leaves the intent row alone, which the next report resolves | +| `federation_connections` | `platform.federation.remove` `(off-path)` | **MUST** (`security-event`) | The completion row of that removal, written through the witness-bound result method on the work transaction that follows the checkpoint, in the same shape with the audit outcome `success`, which says the act ran to its end, and `after_state` holding the closed `outcome` that says how the provider call ended (`applied`, `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`), a `cause` of `live_connection` when a live row refused the delete after the intent, and `accountReviewOwed`, because the provider deletes the federated links with a broker. It is written on a bounded budget detached from the request ([ADR-0099 Amendment 12](../../decisions/0099-confined-tenant-federation.md) item 3). A lost completion leaves the intent row alone, which the next report resolves | | `federation_connections` | `platform.federation.disable_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's disable of a nonconforming or unreadable owned broker, in the shape of the removal's intent under the closed reason `federation_disable` | | `federation_connections` | `platform.federation.disable` `(off-path)` | **MUST** (`security-event`) | The completion row of that disable, in the shape of the removal's completion; the provider is changed and the tenant's row is left to its next readback ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10 item 4) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 2d527808..46d6f8f8 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,008 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,075 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -523,6 +523,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 4 — review round 1 and its fixes (2026-11-20)](#p03-9-step-4--review-round-1-and-its-fixes-2026-11-20) — 49 lines - [P03-9 Step 4 — review round 2 and its fixes (2026-11-20)](#p03-9-step-4--review-round-2-and-its-fixes-2026-11-20) — 39 lines - [P03-9 Step 5 — federation operator steps (2026-11-20)](#p03-9-step-5--federation-operator-steps-2026-11-20) — 71 lines + - [P03-9 Step 5 — review round 1 and its fixes (2026-11-20)](#p03-9-step-5--review-round-1-and-its-fixes-2026-11-20) — 67 lines @@ -25188,3 +25189,70 @@ and the refused columns; each route's statuses, bodies and permission held alone the route, port-holder and raw-reader censuses with their planted violations. A mutation sweep over the new guards killed every mutant but one equivalent: a marker length check that the marker's round trip makes redundant. + +### P03-9 Step 5 — review round 1 and its fixes (2026-11-20) + +Three read-only reviews ran over the Step 5 commit, one per lens: goal conformance, +authority and security; correctness, the audit checkpoint and robustness; tests, +censuses, documentation and standards fidelity. Each finding was verified against the +code before it was acted on. The first full run of the heavy architecture suite had +already failed three lifecycle-census tests, and the full integration run one +isolation test, for two causes recorded below. + +Fixed, with the proof that now catches each: + +- **A completion lost after a change read as "nothing changed".** The completion row + is written on a bounded three-second token detached from the request. A caller that + leaves while the provider works is recorded `uncertain`, and a completion that cannot + be written after a change that landed or may have answers the unknown outcome with + the intent row standing. Owner tests fail the completion after an applied remove, an + uncertain remove and an applied disable, fail it when nothing changed (still the audit + failure), and abort the caller inside the provider call. +- **An unread mapper count made a drifted broker vanish.** The report carries + `mappersUnread`, the healthy-looking live brokers it could not clear. Owner tests + return a count, `null` and a deadline from the scripted provider. +- **A database fault was a raw 500.** The owner translates a transient fault to the + unavailable owner with its cause for the log, the route answers `503`, and any + failure to commit the intent row now stops the act. The fault classifier became + public for it. Owner and route tests cover each act. +- **An unreadable owned broker with a live row could be removed by nobody.** The + tenant's Delete reports it foreign and fails, and the operator remove refused the + live row. The maintainer chose to admit the operator remove for exactly that class; + ADR-0099 Amendment 12 records it with an erratum beside Amendment 11 item 5. Owner + tests refuse a readable pair, remove an unreadable one with its row untouched, and + refuse a delete whose row turned live after the intent. +- **Record against behaviour.** The ticket is recorded on the entry row, never on a + tenant row; the grant sat in the wrong column of the Standard 05 matrix; the runbook's + metric labels, step order, class count and `accountReviewOwed` were wrong; the served + contract named too few reasons and fields; Standard 21 still counted three raw + readers and two scope holders; the glossary, the provider specification and the + audit documents lagged. Each is corrected, and Amendment 12 records the decisions + that were implicit (the audit outcome of a completion row is `success`, and an + applied disable owes the review too). +- **Test gaps.** Marker and row disagreeing on remove and disable, every non-applied + disable outcome, an uninspectable alias, the route's field-level reasons, the + counter's labels, a report's audit failure, the real-provider paging being disjoint + and complete, and a real brokered sign-in after a disable that proves the provider + kept the stored secret. The port-holder census now also finds a holder of the + concrete owner, with planted controls, and the listing's one exact query is pinned. + +Two causes outside the findings: the new checkpoint is a `CommitAsync` owner the +delivery-lifecycle census had to name, and the new audit-writing service tests moved to +an isolated database because `audit_log` is append-only and the shared schema's +isolation census counts the rows each seeded tenant sees. + +Decided and not changed: + +- **The audit outcome of a completion row.** It stays `success`; the provider outcome + is `after_state.outcome` (Amendment 12 item 5). A query for non-success rows misses a + refused or uncertain provider call, which is the open question for the maintainer. +- **An applied disable owes the review** (Amendment 12 item 6), as Amendment 10 item 6 + says. +- **The marker's tenant is not checked against `tenants`.** Amendment 11 item 3 decides + it, and planting a marker needs realm-console rights, which exceed a tenant + administrator's. +- **No batched mapper read.** The operator pipeline's per-call timeout bounds one call, + so one token over a batch would not be sound; the page's ten seconds and + `mappersUnread` bound the cost, and the runbook says so. +- **The disable reads the row once.** Amendment 11 item 8 accepts the read-and-write + interleave; the effect fails closed. diff --git a/docs/runbooks/federation-operator.md b/docs/runbooks/federation-operator.md index 44b1ec39..ed42b5c1 100644 --- a/docs/runbooks/federation-operator.md +++ b/docs/runbooks/federation-operator.md @@ -39,7 +39,8 @@ Everything else in the realm (an unmarked instance, a marker naming another conn an alias that is not LearnStack's) is **counted and never named**: the report's `ignored` says how many, and no act accepts such an alias. -A broker the platform may touch is reported in at most three classes: +A broker the platform may touch is reported in one or two classes (`orphan` combines +with either of the others): | Class | Meaning | |---|---| @@ -54,11 +55,13 @@ A broker that conforms and has a live row is not reported. - **Listing or removing realm users.** No LearnStack credential may enumerate or remove them ([ADR-0099 Decision Q1](../decisions/0099-confined-tenant-federation.md)). The account review below is yours, with your own realm authority. -- **Removing a broker a live row still names.** Disable it here and let the tenant's - own *Delete* retire the connection; a removal is refused while a live row exists. +- **Removing a broker that reads while a live row names it.** Disable it here if it + must stop now, and let the tenant's own *Delete* retire the connection with its + broker; a remove is refused (`errors.connection`) while a live row names a broker + that reads. A broker that does *not* read is the exception, below. - **Repairing a broker.** There is no rewrite from the fixed profile on this surface. - The tenant's next readback corrects its own broker; an unreadable one is disabled - here and deleted by the tenant. + The tenant's next readback corrects its own broker; an unreadable one is removed + here, because the tenant's own Delete treats it as foreign and cannot. - **A broker whose tenant is archived or deleted with a live row.** That is [P03-10](../roadmap/phase-03-identity-admin.md)'s. - **A provider-side fence.** A tenant's create that lands after a sweep produces a new @@ -92,12 +95,19 @@ curl -s -H "Authorization: Bearer $TOKEN" \ other parameter is refused with `errors.query` and nothing is read. - A page is one slice of the provider's own listing, `scanned` instances long, and the answer holds `items` (the brokers on that slice that need attention), `scanned`, - `ignored` and a `pageInfo` whose `nextCursor` you send back as `cursor`. **An empty - `items` with a `nextCursor` is not the end**: the slice held nothing to report. Read - until `hasNext` is false. A cursor belongs to this route. + `ignored`, `mappersUnread` and a `pageInfo` whose `nextCursor` you send back as + `cursor`. **An empty `items` with a `nextCursor` is not the end**: the slice held + nothing to report. Read until `hasNext` is false. A cursor belongs to this route. - Each item carries `alias`, `tenantId`, `connectionId`, `classes`, `rowState`, - `protocol`, `enabled` and `mappers`. `mappers` is the count on a readable broker with - a live row; `null` means it was not read or could not be, **never zero**. + `protocol`, `enabled` and `mappers`. `mappers` is the count read on a live broker that + reads and conforms, where only a mapper can make it drift; `null` means it was not + asked (an orphan, an unreadable or a drifted broker already has its class). +- **`mappersUnread` is not clean.** An extra mapper is drift only a mapper read shows, + so the page reads the mappers of its healthy-looking live brokers one call at a time + within ten seconds. `mappersUnread` counts those it could not read (the provider + failed, its circuit was open or the time ran out): they are unknown, not cleared, and + no item names them. When it is not zero, read the page again, with a smaller `limit` + if it keeps running out of time. - The realm is read **first** and the connection rows second, because a tenant writes its row before it creates its broker. A tenant that creates a broker while your page is being read cannot be taken for an orphan. A broker whose class is `orphan` on one @@ -109,18 +119,21 @@ curl -s -H "Authorization: Bearer $TOKEN" \ | The broker is | Do | |---|---| | `orphan`, readable or not | **Remove** it | -| `unreadable_owned` with a live row | **Disable** it, and ask the tenant to delete the connection; a remove is refused | -| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback corrects it, and until then the sign-in option fails closed | +| `unreadable_owned`, with or without a live row | **Remove** it: the tenant's own Delete cannot reach a broker that does not read, so nothing else can. The tenant's row stays as it was and its next readback finds the broker absent, after which the tenant's own Delete completes. Disable it instead only if the loss of its federated links must wait | +| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback corrects it, and until then the sign-in option fails closed. The tenant's own Delete can remove it, because it reads; a remove here is refused | | healthy with a live row | Neither: a disable is refused with `not_applicable` | A **remove** also deletes the broker's federated links, which is why [an account review](#account-review-after-a-remove) is owed. A **disable** changes only `enabled` -at the provider and the tenant's own row is left to its next readback. +at the provider and the tenant's own row is left to its next readback. Neither writes +the tenant's connection row. ## Act -A ticket is optional and is **checked, not stored**: the audit rows are readable by -the tenant, so they never carry one. The body is `{}` or `{"ticket":"CHG-123"}`. +A ticket is optional and is checked, and **recorded only on the platform scope's entry +row** (a row of the platform sentinel, like the report's): the intent and completion +rows are readable by the tenant, so they never carry one. The body is `{}` or +`{"ticket":"CHG-123"}`. ```sh curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ @@ -129,24 +142,27 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ Use `.../disable` the same way. -Each act proves the owner marker at the provider, re-reads the connection row -immediately before the change, writes an **intent** row, changes the provider, reads -it back, and writes a **completion** row. +Each act proves the owner marker at the provider and reads the connection row (a live +row refuses a remove at once and writes no tenant row). It then writes an **intent** +row; a remove reads the row again, as the last check before the delete. It changes the +provider, reads it back, and writes a **completion** row on a bounded budget of its own, +so a client that leaves while the provider works does not lose the record. | Answer | Meaning | |---|---| -| `200`, `outcome: applied` | The provider's change was made and confirmed. `accountReviewOwed` is `true` for a remove, which deleted federated links | -| `200`, `outcome: already_applied` | The broker was already absent (remove) or already disabled (disable). Nothing was sent and **no tenant row was written** | +| `200`, `outcome: applied` | The provider's change was made and confirmed. `accountReviewOwed` is `true`: a remove deleted the broker's federated links, and a disable closed it as a sign-in option, so people who signed in only through it need another way in | +| `200`, `outcome: already_applied` | The broker was already absent (remove) or already disabled (disable). Nothing was sent, and when it was so at the first read **no tenant row was written**; if it changed between that read and the provider call, the intent and completion rows exist and the completion says `already_applied` | | `404` | A disable named an alias no instance has | | `409`, `errors.owner` = `lockey_not_owned` | The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. Nothing was touched | -| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names the broker, so a remove is refused. Disable it, and the tenant deletes the connection | +| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names a broker that reads, so a remove is refused. Disable it if it must stop now, and the tenant deletes the connection | | `409`, `errors.class` = `lockey_not_applicable` | A disable found a healthy owned broker with a live row | | `409`, `errors.provider` = `lockey_provider_refused` | The provider definitively refused the change. Nothing changed | | `400` | The alias is not a derived one, or the body or the ticket is malformed. A refusal at the gate carries no per-field errors | | `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.federation.admin` for an act), the body size or type, or the request budget | -| `503`, `audit_unavailable` | A MUST row could not be written, so nothing changed (or only the intent row is recorded). Retry after the delay; error line 7105 is in the API's log | +| `503`, `audit_unavailable` | The intent row could not be written or committed, or the completion of a change that did not happen could not be: nothing changed, though the intent row may stand alone. Retry after the delay; error line 7105 is in the API's log | | `503`, `dependency_unavailable` | The provider or the database could not be reached before any change was sent. Nothing changed. Retry after the delay | -| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, or a fault followed it. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, the request was aborted while it ran, or the completion that records it could not be written. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | +| `500` | An unexpected failure or a deployment defect (a refused credential, a missing grant): the API's log names it | A client that never received an answer (a timeout, a gateway error) is in the same position as an unknown outcome. @@ -161,8 +177,11 @@ There is no provider-side fence, so reconcile by reading, in this order: 3. To tell your act from another operator's, read the tenant's audit rows by the `correlationId` of the failed response, as in [Check it worked](#check-it-worked). -A repeat of an act that had landed answers `already_applied` and writes no row; that -alone cannot say whose act it was. +A repeat of an act that had landed answers `already_applied` with `accountReviewOwed` +false, and writes no row; that alone cannot say whose act it was, and it does not say a +review is owed. **After an unknown remove that shows the broker gone, treat the account +review as owed.** The record is the `remove_attempt` row, with no completion row or +with an `uncertain` one. ## Account review after a remove @@ -203,30 +222,34 @@ row's `after_state`, are the reminder. Nothing in LearnStack closes the review. 3. An **intent row with no completion row** is a completion that was lost: the provider may have been changed. The next report resolves it, as step 1 does. -A refusal before the intent (an absent broker, an unowned alias, a live row, an -unavailable provider) writes **no tenant row**: the scope's entry row, -`platform.admin_scope.enter` with the reason `federation_remove` or +A refusal before the intent (an absent broker, an unowned alias, a live row seen at +the first read, an unavailable provider) writes **no tenant row**: the scope's entry +row, `platform.admin_scope.enter` with the reason `federation_remove` or `federation_disable`, records that an act was attempted and nothing is known to name a -tenant. +tenant. A live row found only at the re-read after the intent writes both tenant rows, +and the completion says `refused` with the cause `live_connection`. ## A 503 that does not clear -Find the cause in the API's host log by the response's `correlationId` (warning 7110; -it carries the operation and whether the outcome is unknown, and the exception holds the -cause): +Find the line in the API's host log by the response's `correlationId` (warning 7110; +it carries the operation and whether the outcome is unknown): - **The provider.** The federation admin client's token or an admin call failed. The - adapter's circuit may be open after repeated failures; it closes by itself. A - `Federation:ClientSecret` that is not configured, or one the realm refuses, never - clears until it is fixed. -- **The database or the credential.** `ConnectionStrings:PlatformAdmin` cannot connect. - A refused credential or a missing grant is a `500` and the log names it. + adapter never logs provider text, so the line names no cause: read the provider's own + server log, and the counter below (`outcome` `unavailable`). The adapter's circuit may + be open after repeated failures; it closes by itself. A `Federation:ClientSecret` that + is not configured, or one the realm refuses, never clears until it is fixed. +- **The database.** A transient fault of `ConnectionStrings:PlatformAdmin` (it cannot + connect, a timeout) is a `503`, and the line's exception holds the cause. A refused + credential or a missing grant is not transient: it is a `500` and the log names it. ## Signals -`learnstack_platform_operator_federation_total{operation,outcome}` counts every call. -`operation` is `platform.federation.report`, `platform.federation.remove_attempt` or -`platform.federation.disable_attempt`; `outcome` is `ok`, `invalid_cursor`, +`learnstack_platform_operator_federation_total{operation,outcome}` counts every call +that reached the owner: a refused parameter, alias or body (a `400`) and a refused +credential are not counted, and an audit failure is counted by the audit-failure +counter. `operation` is `platform.federation.report`, `platform.federation.remove` or +`platform.federation.disable`; `outcome` is `ok`, `invalid_cursor`, `applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, `not_applicable`, `refused`, `unavailable` or `uncertain`. A rising `uncertain` means completions are being lost or the provider is failing mid-change; a rising @@ -238,7 +261,10 @@ a killswitch act does. ## Limits - **Pages are slices of the realm.** A realm with many instances takes many pages; - there is no filter by tenant, class or alias. + there is no filter by tenant, class or alias. A page whose instances are unusually + large (over 1 MiB together) is refused as unavailable: lower `limit`. +- **The mapper reads are sequential.** Each costs a token and a call, so a page of many + healthy brokers can run out of its ten seconds; `mappersUnread` says so. - **Disable is a read and a write.** The tenant's own write can interleave with it, and the tenant's next readback detects the drift ([ADR-0099 Amendment 11](../decisions/0099-confined-tenant-federation.md)). diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index da6bf86a..584423d8 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -200,8 +200,8 @@ federation report, remove or disable logs a Warning with event 7001 and the text match the text too); the onboarding acts and the two recovery acts do not enter the platform scope and log no 7001. Event 7109 (Warning) is an onboarding act the request pipeline itself refused as forbidden, which is a -defect. Event 7110 (Warning) is a recovery or an inspection the owner could not finish, -with whether its commit's outcome is unknown; see the [recovery +defect. Event 7110 (Warning) is a recovery, an inspection or a federation call the owner +could not finish, with whether its commit's outcome is unknown; see the [recovery runbook](operator-recovery.md#a-503-that-does-not-clear). A refused operator leaves no database row; the one exception is an onboarding act an admitted operator had refused for a business reason, which writes a `failed` row in the tenant. diff --git a/docs/standards/04-api-design.md b/docs/standards/04-api-design.md index 1370543f..3ef1ae07 100644 --- a/docs/standards/04-api-design.md +++ b/docs/standards/04-api-design.md @@ -55,9 +55,10 @@ Platform operator endpoints live under `/api/platform/v1/...`, outside the tenan ([ADR-0101](../decisions/0101-platform-operator-authority.md)). The federation routes (`GET /api/platform/v1/federation/brokers` and the `remove` and `disable` acts under it, [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)) take an -optional checked, never stored `ticket`, answer a refusal on the field it concerns and -answer an act whose outcome is unknown `503` `dependency_unavailable` with -`errors.outcome`. +optional `ticket`, checked and recorded only on the platform scope's entry row and +never on a tenant-readable row, answer a refusal on the field it concerns, and answer +an act whose outcome is unknown, or whose completion could not be recorded after the +provider changed, `503` `dependency_unavailable` with `errors.outcome`. **P02d-4 Accepted contract — 2026-10-03.** Steps 2–3 deliver all four GET/HEAD read pairs; Step 4 delivers the contract/SDK controls. Institution diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 22ce546e..2f4bedbe 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -1100,7 +1100,7 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | `membership_role_assignments` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | | `roles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | | `role_permission_grants` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | -| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | — | `SELECT` of `id`, `tenant_id`, `state` and `deleted_at` only ([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 11); exact [projection grant](#federation-operator-projection) | +| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | `SELECT` of `id`, `tenant_id`, `state` and `deleted_at` only ([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 11); exact [projection grant](#federation-operator-projection) | — | | `tenants` | `SELECT, INSERT, UPDATE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `organizations` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `tenant_domains` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT` | — | diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index b45b0569..f42b9b1a 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,7 +177,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**390 test methods run in +**393 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, @@ -6044,8 +6044,9 @@ structural test proves — and what it does not. #### `Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Operator_Ports` - **Asserts:** the files, by their path under `backend/src`, that name - `IFederationBrokerOperations` are exactly the port, its one owner, the persistence - composition and the federation routes, and the files that name `IFederationOperator` + `FederationBrokerOperations` (the port's name contains it, so the owner's class is + found too) are exactly the port, its one owner, the persistence composition and the + federation routes, and the files that name `IFederationOperator` are exactly the port, the owner, the adapter that implements it, its factory, the federation composition and the Identity foundation registration that gives it a fail-closed default. The tenant runner is in neither list. Adding a caller is a @@ -6055,7 +6056,9 @@ structural test proves — and what it does not. holder of the operator port, or a handler that reached the owner, would make a cross-tenant provider change from a path the operator gate does not guard. - **Source:** [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10. -- **Type:** xUnit + source scan. **Kind:** structural. +- **Type:** xUnit + source scan, with a planted holder of each port and of the + concrete owner (`The_Federation_Port_Census_Finds_A_Planted_Holder_Of_Either_Port_Or_The_Concrete_Owner`). + **Kind:** structural. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 5). - **Phase:** P03-9. @@ -6064,8 +6067,8 @@ structural test proves — and what it does not. - **Asserts:** the files, by their path under `backend/src`, that name `IPlatformAdminScope` are exactly the interface, the scope, the persistence composition and the operator services that perform an admitted act (today the - killswitch toggle and the delivery inspection). Adding a service is a deliberate - edit here, with its denied proof. + killswitch toggle, the delivery inspection and the federation owner). Adding a + service is a deliberate edit here, with its denied proof. - **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a tenant request path. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. @@ -7785,15 +7788,20 @@ sign-in read). The `state <> 'Deleted' AND deleted_at IS NULL`; every production source, both Identity projects included, that reads `federation_connections` (`FROM` or `JOIN`, any case or whitespace, with or without the schema, quoted or through the mapped table-name - constant) is exactly `FederationConnectionStore`, `FederationHostAliasReader` or - `PublicSignInReader`; and each such statement, not merely its file, interpolates that - constant and spells no tombstone predicate of its own, so the three raw reads cannot - drift from each other or from the EF `Live` filter silently. + constant) is exactly `FederationConnectionStore`, `FederationHostAliasReader`, + `PublicSignInReader` or the operator's `FederationBrokerOperations`; each of the + three tenant statements, not merely its file, interpolates that constant and spells + no tombstone predicate of its own, so the three tenant reads cannot drift from each + other or from the EF `Live` filter silently. The operator's read is the one + exception: it must see tombstones, so it is pinned whole instead, by primary key + through the four columns the platform role may read + ([ADR-0099 Amendment 11](../decisions/0099-confined-tenant-federation.md) item 2). - **Source:** [ADR-0099 Amendment 1](../decisions/0099-confined-tenant-federation.md#amendment-1--step-1-storage-deviations-2026-11-13) (the tombstone) and the P03-8 Step 2 review round 1 (S-D). - **Type:** source scan with planted controls: an own predicate, a second statement without the constant, an unlisted reader by `JOIN`, without the schema, with other - spacing, quoted or through the table-name constant, and a dropped reader. + spacing, quoted or through the table-name constant, a dropped reader, and a + widened operator statement (a fifth column, another predicate, a second statement). **Kind:** structural. - **Status:** **Implemented** (`FederationApplicationConventionTests`). - **Test owner:** [FederationApplicationConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs). @@ -7850,7 +7858,11 @@ sign-in read). The string literal in the adapter namespace names another Admin, identity-provider, authentication, user, client or role path. The unit test `KeycloakFederationProviderTests.Every_admitted_request_targets_the_enumerated_routes_only` - checks the same set behaviourally against a scripted provider. + checks the same set behaviourally against a scripted provider. The listing's one + exact query is pinned too: the route builder names the fragments `?first=`, `&max=` + and `&briefRepresentation=false`, in that order, and no other file of the adapter + builds a query string (`The_one_admitted_query_is_the_listing_page_and_no_provider_file_builds_another`, + with a planted fragment). - **Source:** [ADR-0099 § Ownership and the confined adapter](../decisions/0099-confined-tenant-federation.md#ownership-and-the-confined-adapter) ("the adapter admits only the enumerated calls and aliases"). - **Type:** reflection plus source scan, with planted routes. **Kind:** structural. From b8d74c58f342d20e79852b7fb3629d0cfb9ffaa2 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Fri, 20 Nov 2026 23:57:45 +0300 Subject: [PATCH 22/28] fix(platform): close P03-9 step 5 review round 2 findings Removing an unreadable owned broker that a live connection row names now needs it to be disabled as well, proved again by the adapter at the delete: "unreadable" is a shape check, and such a broker can still serve sign-ins (ADR-0099 Amendment 13, with errata beside the false premise and a wrong pointer). The owner tracks whether a provider change may have landed. Any non-fatal failure after that point answers the unknown outcome and keeps its cause for the log, instead of "nothing changed" or a silent swallow. The completion budget is injectable. The runbook, the served contract, the standards and the glossary are corrected, and the new guards have tests that fail when they are mutated. ADR: 0099 Module: Identity, Platform Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorDocumentTransformer.cs | 9 +- .../PlatformOperatorEndpoints.Federation.cs | 15 +- .../PlatformOperatorEndpoints.Recovery.cs | 2 +- .../KeycloakFederationProvider.Operator.cs | 6 +- .../Messaging/OperatorRecoveryFaults.cs | 2 +- .../MultiTenancy/PlatformAdminScope.cs | 2 +- .../Identity/IFederationOperator.cs | 11 +- .../Platform/IFederationBrokerOperations.cs | 17 +- .../Federation/FederationBrokerOperations.cs | 121 +++++--- .../FederationAdapterConventionTests.cs | 10 + .../FederationBrokerOperationsTests.cs | 291 ++++++++++++++++-- .../PlatformOperatorHttpTests.cs | 27 +- .../FederationProviderTests.Operator.cs | 8 +- .../Composition/FederationCompositionTests.cs | 38 +++ .../KeycloakFederationProviderTests.cs | 34 ++ .../0099-confined-tenant-federation.md | 45 +++ docs/glossary.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 66 +++- docs/roadmap/phase-03-identity-admin.md | 2 +- docs/runbooks/federation-operator.md | 78 +++-- docs/runbooks/operator-access.md | 8 +- docs/standards/05-database.md | 8 +- docs/standards/11-security.md | 8 +- docs/standards/20-infrastructure-stack.md | 8 +- 24 files changed, 682 insertions(+), 136 deletions(-) diff --git a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index ca15ecfb..ad63f706 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -20,7 +20,8 @@ internal sealed class PlatformOperatorDocumentTransformer(string documentName) : "Operator-only platform operations. Authenticate with a short-lived access token issued by the " + "deployment's operator issuer to the client learnstack-operator after a second factor; the token " + "profile and the runbooks are in docs/runbooks/operator-access.md, and the recovery of dead-lettered " - + "work is explained in docs/runbooks/operator-recovery.md. Authentication grants no " + + "work is explained in docs/runbooks/operator-recovery.md and the federation operator steps in " + + "docs/runbooks/federation-operator.md. Authentication grants no " + "permission: each operation needs a Platform grant held by LearnStack and evaluated on every act."; public async Task TransformAsync( @@ -141,7 +142,7 @@ private static void DescribeInspectionParameters(OpenApiOperation operation) }; break; case "cursor": - concrete.Description = "The nextCursor of the previous page; it belongs to the route and state that issued it."; + concrete.Description = "The nextCursor of the previous page; it belongs to the route and state that issued it. A federation cursor is at most 64 characters."; concrete.Schema = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 512 }; break; case "ticket": @@ -218,11 +219,11 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation private static readonly (string Status, string Description)[] Statuses = [ - ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit, errors.cursor or, for the federation report, errors.query (a parameter it does not take). A federation act names only an alias of the form lsf- and 32 lowercase hexadecimal characters."), + ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit, errors.cursor or errors.query (a parameter the route does not take). A federation act names only an alias of the form lsf- and 32 lowercase hexadecimal characters."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, a recovery names no such row, or a federation disable names an alias no identity-provider instance has."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200. A federation act answers 409 with the reason on errors.owner (the instance's owner marker is not LearnStack's, or names another tenant than its row), errors.connection (a live connection row still names a broker that reads: a remove is refused; an unreadable owned broker is removed even so), errors.class (a disable found a healthy broker with a live row) or errors.provider (the provider definitively refused the change; nothing changed). A repeat of a federation act that had landed answers 200 already_applied and writes no row of its own."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200. A federation act answers 409 with the reason on errors.owner (the instance's owner marker is not LearnStack's, or names another tenant than its row), errors.connection (a live connection row still names the broker and it reads or is still enabled: a remove is refused; disable an unreadable one first, and it is then removed even with the live row), errors.class (a disable found a healthy broker with a live row) or errors.provider (the provider definitively refused the change; nothing changed). A repeat of a federation act that had landed answers 200 already_applied and writes no row of its own, and does not say that a remove owes the account review."), ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs index eba96bb2..bc5abe5a 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs @@ -43,15 +43,22 @@ private static void MapFederation(RouteGroupBuilder group) DescribeInspection( group.MapGet(FederationPrefix, ReportFederationAsync) .WithName("PlatformFederationReport") - .WithSummary("Report identity-provider brokers that are orphaned, unreadable or nonconforming; the realm is read first, then the rows."), + .WithSummary("Report identity-provider brokers that are orphaned, unreadable or nonconforming; the realm is read first, then the rows.") + .WithDescription( + "One page of the provider's own listing, in the provider's order: items holds the brokers on that slice that need " + + "an operator, so an empty items with a nextCursor is not the end. mappersUnread counts the healthy-looking live " + + "brokers whose mappers could not be read (the provider failed or the page's time ran out): they are unknown, not " + + "clean, and no item names them. scanned and ignored count the instances the provider returned and the ones that " + + "are not LearnStack's. A ticket is checked and recorded only on the platform scope's entry row."), typeof(FederationReportResponse)); Describe( group.MapPost(FederationPrefix + "/{alias}/remove", RemoveFederationAsync) .WithName("PlatformFederationRemove") .WithSummary("Remove an orphaned or unreadable owned broker at the provider; the provider deletes its federated links.") .WithDescription( - "Refused while a live connection row names a broker that reads; an unreadable owned broker is removed even " - + "with a live row, because nothing else can. An absent broker is already removed. The tenant's " + "Refused while a live connection row names the broker and it reads or is still enabled; an unreadable owned " + + "broker that is disabled is removed even with a live row, because nothing else can. An absent broker is " + + "already removed. The tenant's " + "intent and completion rows are written around the provider call; the delegated-account review is the " + "operator's, by runbook. A ticket is checked and recorded only on the platform scope's entry row, never " + "on a tenant's row."), @@ -169,7 +176,7 @@ private static async Task FederationActAsync( FederationActOutcome.Refused => ResultProblem(http, Rule("provider", "lockey_provider_refused")), FederationActOutcome.Unavailable => UnavailableProblem(http, loggers, operation, new OperatorRecoveryUnavailableException()), FederationActOutcome.Uncertain => UnavailableProblem( - http, loggers, operation, new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true)), + http, loggers, operation, new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: result.Cause)), _ => throw new InvalidOperationException("A federation outcome the route does not answer."), }; } diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs index 1465bbd7..a4c2721f 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs @@ -276,7 +276,7 @@ private static async Task RecoverAsync( LoggerMessage.Define( LogLevel.Warning, new EventId(7110, nameof(LogRecoveryUnavailable)), - "An operator recovery owner was unavailable for {Operation}; the commit's outcome unknown: {CommitOutcomeUnknown}."); + "An operator owner (recovery, inspection or federation) was unavailable for {Operation}; the outcome unknown: {CommitOutcomeUnknown}."); /// /// A 503 whose cause the operator can find: the fault is logged, and the response names only whether the commit's diff --git a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs index e3c85cd9..7765902e 100644 --- a/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs +++ b/backend/src/LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.Operator.cs @@ -89,7 +89,8 @@ public async Task InspectAsync(string brokerAlias, C } /// - public async Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + public async Task RemoveAsync( + FederationBrokerOwner owner, bool requireDisabledUnreadable = false, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var sent = false; @@ -100,6 +101,9 @@ public async Task RemoveAsync(FederationBrokerOwner o { if (probe.Kind == Probe.Absent) return FederationOperatorOutcome.AlreadyApplied; if (probe.Kind == Probe.NotOwned || !Names(probe.Facts!.Owner, owner)) return FederationOperatorOutcome.NotOwned; + // The owner removes a broker a live row still names only while it does not read and is disabled: proved + // again here, at the delete, and not trusted from an inspection that may be seconds old. + if (requireDisabledUnreadable && (probe.Facts.Readable || probe.Facts.Enabled)) return FederationOperatorOutcome.Refused; } finally { probe.Zero(); } diff --git a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs index 92d99566..2d350edf 100644 --- a/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs +++ b/backend/src/LearnStack.Infrastructure/Messaging/OperatorRecoveryFaults.cs @@ -26,6 +26,6 @@ public static class OperatorRecoveryFaults /// A transient database fault, or one of the owner's own refusals: the lane is busy, the pool is exhausted or the /// store is sealed by an unconfirmed cleanup, each of which is an . /// - public static bool IsUnavailable(Exception failure, CancellationToken caller) => + internal static bool IsUnavailable(Exception failure, CancellationToken caller) => failure is InvalidOperationException || IsTransientDatabaseFault(failure, caller); } diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index 4ba422c0..28773e88 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -565,7 +565,7 @@ public async Task WriteIntentAsync(PlatformResult intent, CancellationToken canc // effect must not start on an intent nobody can prove was recorded. await _transaction.CommitAsync(cancellationToken); } - catch (Exception failure) + catch (Exception failure) when (failure is not (OutOfMemoryException or AccessViolationException)) { // Any failure of the commit, a connection already broken included, stops the effect: it must not start on // an intent nobody can prove was recorded (ADR-0044 Amendment 18). diff --git a/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs index 6babc2f2..37ff4c88 100644 --- a/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs +++ b/backend/src/LearnStack.SharedKernel/Identity/IFederationOperator.cs @@ -113,9 +113,13 @@ public interface IFederationOperator /// /// Deletes the instance after proving its marker names this owner, whether or not it can be read, and confirms - /// that it is gone. The provider deletes the federated links with it. + /// that it is gone. The provider deletes the federated links with it. When + /// is set, the instance must still read as unreadable and be disabled when the delete is about to be sent, proved again + /// at that moment, or the call is and nothing is sent: that is the + /// condition under which the owner removes a broker a live connection row still names (ADR-0099 Amendment 12). /// - Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default); + Task RemoveAsync( + FederationBrokerOwner owner, bool requireDisabledUnreadable = false, CancellationToken cancellationToken = default); /// /// Sets enabled to false at the provider only, after proving the marker: the one provider write that sends @@ -136,7 +140,8 @@ public Task InspectAsync(string brokerAlias, Cancell public Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => Task.FromResult(null); - public Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => + public Task RemoveAsync( + FederationBrokerOwner owner, bool requireDisabledUnreadable = false, CancellationToken cancellationToken = default) => Task.FromResult(FederationOperatorOutcome.Unavailable); public Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) => diff --git a/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs index db50eb16..6a40a4ab 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs @@ -52,7 +52,10 @@ public enum FederationActOutcome /// The provider's change was made and confirmed; the account review is owed. Applied = 1, - /// The broker was already absent (remove) or already disabled (disable); nothing was sent and no tenant row was written. + /// + /// The broker was already absent (remove) or already disabled (disable); nothing was sent. No tenant row is written when + /// it was so at the first read, and both rows are when it changed between that read and the provider call. + /// AlreadyApplied, /// A disable named an alias no instance has. @@ -62,8 +65,9 @@ public enum FederationActOutcome NotOwned, /// - /// A live connection row names a broker that reads, so a remove refuses; the tenant's own Delete retires the pair. An - /// unreadable owned broker is removed even with a live row (ADR-0099 Amendment 12). + /// A live connection row names the broker and it still reads or is still enabled, so a remove refuses: the tenant's own + /// Delete retires a pair that reads, and an enabled one may still be serving. An unreadable owned broker that is + /// disabled is removed even with a live row (ADR-0099 Amendment 12). /// LiveConnection, @@ -84,7 +88,12 @@ public enum FederationActOutcome /// How it ended. /// The tenant the marker names, when an owned broker was found. /// The connection the marker names, when an owned broker was found. -public sealed record FederationActResult(FederationActOutcome Outcome, Guid? TenantId = null, Guid? ConnectionId = null); +/// +/// The failure behind an unknown outcome, for the route's log and never for a response: a provider fault after the change +/// was sent, or a completion that could not be written. +/// +public sealed record FederationActResult( + FederationActOutcome Outcome, Guid? TenantId = null, Guid? ConnectionId = null, Exception? Cause = null); /// /// The confined owner of the operator's federation report, remove and disable (ADR-0099 Amendment 10 and 11): it diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs index a7b9c523..9d55c16e 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs @@ -1,9 +1,7 @@ -using System.Data.Common; using System.Globalization; using System.Text; using System.Text.Json; using LearnStack.Infrastructure.Messaging; -using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Pagination; using LearnStack.SharedKernel.Platform; @@ -42,47 +40,65 @@ namespace LearnStack.Modules.Identity.Infrastructure.Federation; /// read them. /// /// -public sealed class FederationBrokerOperations(IPlatformAdminScope scope, IFederationOperator provider) : IFederationBrokerOperations +public sealed class FederationBrokerOperations( + IPlatformAdminScope scope, IFederationOperator provider, TimeSpan? completionBudget = null) : IFederationBrokerOperations { private const int MaximumLimit = CursorPagination.MaxLimit; private const string EntityType = "FederationConnection"; private const string RowQuery = "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; private static readonly TimeSpan ReportDeadline = TimeSpan.FromSeconds(10); - private static readonly TimeSpan CompletionBudget = TimeSpan.FromSeconds(3); private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + /// The completion's own budget, detached from the request; a test passes a shorter or longer one. + private readonly TimeSpan _completionBudget = completionBudget ?? TimeSpan.FromSeconds(3); + /// public Task ReportAsync( PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => - GuardAsync(() => ReportCoreAsync(admission, cursor, limit, cancellationToken), cancellationToken); + GuardAsync(_ => ReportCoreAsync(admission, cursor, limit, cancellationToken), cancellationToken); /// public Task RemoveAsync( PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => - GuardAsync(() => RemoveCoreAsync(admission, brokerAlias, cancellationToken), cancellationToken); + GuardAsync(progress => RemoveCoreAsync(admission, brokerAlias, progress, cancellationToken), cancellationToken); /// public Task DisableAsync( PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => - GuardAsync(() => DisableCoreAsync(admission, brokerAlias, cancellationToken), cancellationToken); + GuardAsync(progress => DisableCoreAsync(admission, brokerAlias, progress, cancellationToken), cancellationToken); + + /// Whether a provider change may have landed, which decides what a failure further on may claim. + private sealed class ActProgress + { + internal bool ChangeMayHaveLanded { get; set; } + } /// - /// A transient database fault is the unavailable owner it is, with its cause kept for the route's log, and never a raw - /// 500. It is raised only where nothing was changed: a completion that fails after a change is answered inside - /// as the unknown outcome, before it can reach this guard. + /// A failure after a change that landed or may have is the unknown outcome, with its cause kept for the route's log and + /// never "nothing changed"; before any change, a transient database fault is the unavailable owner, and never a raw 500. + /// What this guard does not catch (a refused credential, a missing grant before any change, a programmer error) is the + /// defect it is. /// - private static async Task GuardAsync(Func> operation, CancellationToken cancellationToken) + private static async Task GuardAsync(Func> operation, CancellationToken cancellationToken) { + var progress = new ActProgress(); try { - return await operation(); + return await operation(progress); } - catch (Exception failure) when (OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) + catch (Exception failure) when (progress.ChangeMayHaveLanded && !IsFatal(failure)) + { + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: failure); + } + catch (Exception failure) when (!progress.ChangeMayHaveLanded + && OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) { throw new OperatorRecoveryUnavailableException(cause: failure); } } + private static bool IsFatal(Exception failure) => failure is OutOfMemoryException or AccessViolationException or StackOverflowException; + private async Task ReportCoreAsync( PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken) { @@ -164,7 +180,7 @@ private async Task ReportCoreAsync( } private async Task RemoveCoreAsync( - PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken) + PlatformAdmission admission, string brokerAlias, ActProgress progress, CancellationToken cancellationToken) { RequireOperation(admission, PlatformOperations.FederationRemove); await using var handle = await scope.EnterAsync(admission, cancellationToken); @@ -190,7 +206,7 @@ private async Task RemoveCoreAsync( if (RefusesRemoval(facts, row)) { - // Amendment 10 item 3: a live row refuses a broker that reads. The tenant's own Delete retires it. + // Amendment 10 item 3 and Amendment 12 item 1: a live row refuses a broker that reads or is still enabled. return Known(FederationActOutcome.LiveConnection, owner); } @@ -202,6 +218,7 @@ private async Task RemoveCoreAsync( var again = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); FederationActOutcome outcome; string? cause = null; + Exception? failure = null; if (RefusesRemoval(facts, again)) { outcome = FederationActOutcome.LiveConnection; @@ -209,15 +226,18 @@ private async Task RemoveCoreAsync( } else { - outcome = await ChangeAsync(token => provider.RemoveAsync(owner, token), cancellationToken); + // A live row is let through only for a broker that does not read and is disabled, which the adapter proves + // again at the delete. + (outcome, failure) = await ChangeAsync( + token => provider.RemoveAsync(owner, requireDisabledUnreadable: IsLive(again), token), progress, cancellationToken); } - outcome = await CompleteAsync(handle, owner, classes, row, outcome, cause); - return Known(outcome, owner); + (outcome, failure) = await CompleteAsync(handle, owner, classes, row, outcome, cause, failure, progress); + return Known(outcome, owner, failure); } private async Task DisableCoreAsync( - PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken) + PlatformAdmission admission, string brokerAlias, ActProgress progress, CancellationToken cancellationToken) { RequireOperation(admission, PlatformOperations.FederationDisable); await using var handle = await scope.EnterAsync(admission, cancellationToken); @@ -253,55 +273,61 @@ private async Task DisableCoreAsync( } await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); - var outcome = await ChangeAsync(token => provider.DisableAsync(owner, token), cancellationToken); - outcome = await CompleteAsync(handle, owner, classes, row, outcome, cause: null); - return Known(outcome, owner); + var (outcome, failure) = await ChangeAsync(token => provider.DisableAsync(owner, token), progress, cancellationToken); + (outcome, failure) = await CompleteAsync(handle, owner, classes, row, outcome, cause: null, failure, progress); + return Known(outcome, owner, failure); } /// - /// The provider's change, with a caller that leaves recorded as an unknown outcome: the change may already have been - /// sent, and the adapter rethrows the caller's cancellation without saying which side of the send it fell on. + /// The provider's change. A caller that leaves, and any other failure after the change may have been sent, is an + /// unknown outcome with its cause kept: the adapter rethrows the caller's cancellation without saying which side of the + /// send it fell on, and an unexpected failure says nothing about whether the provider took the change. Either is + /// recorded in the completion row, never skipped. /// - private static async Task ChangeAsync( - Func> change, CancellationToken cancellationToken) + private static async Task<(FederationActOutcome Outcome, Exception? Failure)> ChangeAsync( + Func> change, ActProgress progress, CancellationToken cancellationToken) { + FederationActOutcome outcome; + Exception? failure = null; try { - return Map(await change(cancellationToken)); + outcome = Map(await change(cancellationToken)); } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + catch (Exception caught) when (!IsFatal(caught)) { - return FederationActOutcome.Uncertain; + outcome = FederationActOutcome.Uncertain; + failure = caught; } + + progress.ChangeMayHaveLanded = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; + return (outcome, failure); } /// /// Writes and commits the completion row on a bounded token detached from the request, and returns the outcome the - /// caller is to answer. A completion that cannot be written is the audit failure it is when nothing changed; after a - /// change that landed or may have, the intent row stands alone and the answer is the unknown outcome, never - /// "nothing changed, repeat it". + /// caller is to answer with the failure behind it. A completion that cannot be written is the audit failure it is when + /// nothing changed; after a change that landed or may have, the intent row stands alone and the answer is the unknown + /// outcome with the completion's failure as its cause, never "nothing changed, repeat it" and never a silent swallow. /// - private static async Task CompleteAsync( + private async Task<(FederationActOutcome Outcome, Exception? Failure)> CompleteAsync( IPlatformAdminScopeHandle handle, FederationBrokerOwner owner, IReadOnlyList classes, Row? row, - FederationActOutcome outcome, string? cause) + FederationActOutcome outcome, string? cause, Exception? failure, ActProgress progress) { var token = OutcomeToken(outcome); // The account review is owed for any change that may have landed: the provider removes federated links with a - // broker, and nothing here reads them (ADR-0099 Amendment 10 item 7). + // broker, and nothing here reads them (ADR-0099 Amendment 10 item 7). A disable owes it too (Amendment 12 item 6). var owed = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; var after = JsonSerializer.Serialize(new AfterState(token, cause, owed), Json); - using var budget = new CancellationTokenSource(CompletionBudget); + using var budget = new CancellationTokenSource(_completionBudget); try { await handle.WriteResultAsync(Result(owner, classes, row, after), budget.Token); await handle.CommitAsync(budget.Token); - return outcome; + return (outcome, failure); } - catch (Exception failure) when ( - outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain - && failure is AuditWriteFailedException or DbException or OperationCanceledException or IOException) + catch (Exception lost) when (progress.ChangeMayHaveLanded && !IsFatal(lost)) { - return FederationActOutcome.Uncertain; + return (FederationActOutcome.Uncertain, lost); } } @@ -309,8 +335,8 @@ outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain owner.TenantId, EntityType, owner.ConnectionId.ToString("D", CultureInfo.InvariantCulture), JsonSerializer.Serialize(new BeforeState(classes, RowState(row)), Json), after); - private static FederationActResult Known(FederationActOutcome outcome, FederationBrokerOwner owner) => - new(outcome, owner.TenantId.Value, owner.ConnectionId); + private static FederationActResult Known(FederationActOutcome outcome, FederationBrokerOwner owner, Exception? failure = null) => + new(outcome, owner.TenantId.Value, owner.ConnectionId, failure); private static FederationActOutcome Map(FederationOperatorOutcome outcome) => outcome switch { @@ -356,11 +382,12 @@ private static List ClassesOf(FederationBrokerFacts facts, Row? row, int /// /// A live connection row refuses the removal of a broker that reads: the tenant's own Delete retires that pair. A broker - /// that does not read is the exception (ADR-0099 Amendment 12 item 1), because the tenant's Delete treats it as foreign - /// and fails (Amendment 9 item 5), so nothing else could ever remove it; it already fails closed, and the tenant's - /// next readback finds it absent. + /// that does not read and is disabled is the exception (ADR-0099 Amendment 12 item 1 and Amendment 13 item 1), because + /// the tenant's Delete treats it as foreign and fails (Amendment 5 item 5), so nothing else could ever remove it. An + /// unreadable broker that is still enabled is refused: "unreadable" is a shape check, and the provider may still be + /// serving it, so the operator disables it first, which is reversible, and removes it after. /// - private static bool RefusesRemoval(FederationBrokerFacts facts, Row? row) => facts.Readable && IsLive(row); + private static bool RefusesRemoval(FederationBrokerFacts facts, Row? row) => IsLive(row) && (facts.Readable || facts.Enabled); private static bool IsLive(Row? row) => row is { Deleted: false } && !string.Equals(row.State, "Deleted", StringComparison.Ordinal); diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index 60e92aba..936f2100 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -63,16 +63,26 @@ public void The_one_admitted_query_is_the_listing_page_and_no_provider_file_buil ["?first=", "&max=", "&briefRepresentation=false"]); adapter.Where(source => source.Key != RoutesSource).SelectMany(source => QueryLiterals(source.Value)).Should().BeEmpty( "Fix: a provider query string is built in KeycloakFederationRoutes alone"); + // A query built without a literal that holds a separator (a builder, a helper, a property) is not a literal to find. + adapter.Where(source => QueryBuilders(source.Value)).Select(source => source.Key).Should().BeEmpty( + "Fix: no query is composed through UriBuilder, QueryHelpers or a Query property in the adapter"); } [Fact] public void The_query_detector_sees_a_planted_fragment() { + QueryBuilders("var u = new UriBuilder(uri) { Query = \"search=\" + term };").Should().BeTrue(); + QueryBuilders("var u = QueryHelpers.AddQueryString(path, \"search\", term);").Should().BeTrue(); + QueryBuilders("builder.Query = x;").Should().BeTrue(); + QueryBuilders("var clean = new Uri(options.AdminRealm, \"identity-provider/instances\");").Should().BeFalse(); QueryLiterals("var uri = \"identity-provider/instances?search=\" + term; var x = \"&briefRepresentation=false\";") .Should().Equal(["identity-provider/instances?search=", "&briefRepresentation=false"]); QueryLiterals("var clean = \"identity-provider/instances\";").Should().BeEmpty(); } + private static bool QueryBuilders(string source) => + Regex.IsMatch(source, @"\bUriBuilder\b|\bAddQueryString\b|\bQueryHelpers\b|\.Query\s*="); + /// The string literals of a source that hold a query separator, with whole-line comments set aside first. private static List QueryLiterals(string source) => [.. Regex.Matches(Regex.Replace(source, @"^\s*//.*$", string.Empty, RegexOptions.Multiline), @"""(?:[^""\\\r\n]|\\.)*""") diff --git a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs index 64dc2ed5..0c72c09e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs @@ -103,6 +103,7 @@ public async Task A_report_names_a_broker_with_no_row_a_tombstone_and_an_unreada result.Scanned.Should().Be(4); // A healthy live broker with no mapper drift is no finding, and its mapper count was asked once. operations.MapperCalls.Should().Equal(healthy.Alias); + result.Unread.Should().Be(0, "a tombstone, an absent row and an unreadable broker are never mapper-read, so none is unread"); } [Fact] @@ -171,12 +172,16 @@ public async Task A_report_the_provider_cannot_answer_is_unavailable_and_writes_ } [Theory] - [InlineData(true, true)] - [InlineData(true, false)] - public async Task A_remove_of_a_broker_that_reads_with_a_live_row_is_refused_before_anything_is_written_or_sent(bool readable, bool conforms) + [InlineData(true, true, true)] + [InlineData(true, false, true)] + [InlineData(true, true, false)] + [InlineData(false, true, true)] + public async Task A_remove_of_a_broker_that_reads_or_is_still_enabled_with_a_live_row_is_refused_before_anything_is_written_or_sent( + bool readable, bool conforms, bool enabled) { - // Readable and drifted, or readable and clean: the tenant's own Delete retires such a pair, so the operator refuses. - var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable, conforms), InspectedMappers = conforms ? 0 : 1 }; + // A pair that reads is retired by the tenant's own Delete, and an unreadable broker that is still enabled may be + // serving: the operator disables it first (ADR-0099 Amendment 13 item 1). + var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable, conforms, enabled), InspectedMappers = conforms ? 0 : 1 }; var admission = Admission(PlatformOperations.FederationRemove); var result = await Service(operations).RemoveAsync(admission, Alias(LiveA)); @@ -187,18 +192,19 @@ public async Task A_remove_of_a_broker_that_reads_with_a_live_row_is_refused_bef } [Fact] - public async Task A_remove_of_an_unreadable_owned_broker_is_applied_even_with_a_live_row_because_the_tenants_delete_cannot_reach_it() + public async Task A_remove_of_an_unreadable_disabled_broker_is_applied_even_with_a_live_row_because_the_tenants_delete_cannot_reach_it() { // The tenant's Delete reports an unreadable owned broker as foreign and fails, so a live row would otherwise hold it - // forever (ADR-0099 Amendment 12). The rows record the live state the operator found, and the tenant's row is left. + // forever (ADR-0099 Amendment 12). It is disabled first, and the adapter proves that again at the delete. var owner = OwnerOf(LiveA); - var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var operations = new Scripted { Inspected = Facts(owner, readable: false, enabled: false) }; var admission = Admission(PlatformOperations.FederationRemove); var result = await Service(operations).RemoveAsync(admission, owner.Alias); result.Should().Be(new FederationActResult(FederationActOutcome.Applied, SchemaFixture.TenantA, LiveA)); operations.Removed.Should().ContainSingle(); + operations.RemoveRequirements.Should().Equal([true], "the adapter is told to prove 'unreadable and disabled' at the delete"); var rows = await RowsAsync(admission.Operator.CorrelationId!); rows.Select(row => row.Operation).Should().Equal( PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); @@ -209,6 +215,33 @@ public async Task A_remove_of_an_unreadable_owned_broker_is_applied_even_with_a_ .Should().Be(1, "the operator never writes the tenant's row"); } + [Fact] + public async Task A_remove_whose_broker_stopped_being_unreadable_and_disabled_before_the_delete_is_refused_by_the_provider_proof() + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false, enabled: false), RemoveOutcome = FederationOperatorOutcome.Refused }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Refused); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("refused"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeFalse("nothing was deleted"); + } + + [Fact] + public async Task A_remove_of_an_orphan_does_not_ask_the_adapter_for_the_unreadable_proof() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: true, conforms: false), InspectedMappers = 1 }; + + await Service(operations).RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias); + + operations.RemoveRequirements.Should().Equal([false], "an orphan has no live row to be let through"); + } + [Theory] [InlineData("tombstone")] [InlineData("absent")] @@ -383,7 +416,7 @@ public async Task A_live_row_that_appears_after_the_intent_refuses_the_delete_an var owner = OwnerOf(connection, FederationDatabase.TenantC); var operations = new Scripted { Inspected = Facts(owner, readable: true, conforms: false), InspectedMappers = 1 }; var admission = Admission(PlatformOperations.FederationRemove); - var service = new FederationBrokerOperations(Scope(false, false, afterIntent: async () => + var service = new FederationBrokerOperations(Scope(false, false, afterIntent: async _ => { await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); await using var transaction = await app.BeginTransactionAsync(); @@ -391,7 +424,7 @@ public async Task A_live_row_that_appears_after_the_intent_refuses_the_delete_an await InsertAsync(app, transaction, connection, FederationDatabase.TenantC, IdentityMembershipFixture.AdminA, DateTimeOffset.UtcNow.AddMinutes(-5)); await transaction.CommitAsync(); - }), operations); + }), operations, TimeSpan.FromSeconds(30)); var result = await service.RemoveAsync(admission, owner.Alias); @@ -408,6 +441,165 @@ await InsertAsync(app, transaction, connection, FederationDatabase.TenantC, Iden after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeFalse("nothing was changed"); } + [Theory] + [InlineData("io")] + [InlineData("closed")] + [InlineData("timeout")] + public async Task A_commit_that_fails_after_a_change_answers_the_unknown_outcome_whatever_the_failure_and_keeps_its_cause(string kind) + { + Exception fault = kind switch + { + "io" => new NpgsqlException("the connection dropped", new IOException("reset")), + "closed" => new InvalidOperationException("The transaction has completed"), + _ => new TimeoutException("the commit timed out"), + }; + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { Commit = fault }), operations, TimeSpan.FromSeconds(30)); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain, "the change was sent and its record was not committed"); + result.Cause.Should().BeSameAs(fault, "the cause goes to the route's log"); + operations.Removed.Should().ContainSingle(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + } + + [Fact] + public async Task A_completion_write_that_outlives_its_budget_is_cut_and_answers_the_unknown_outcome() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { HangResult = true }), operations, TimeSpan.FromMilliseconds(200)); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + result.Cause.Should().BeAssignableTo("the budget, not the request, cut the write"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + } + + [Fact] + public async Task A_failure_while_the_handle_is_disposed_after_a_change_is_the_unknown_outcome_and_never_nothing_changed() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var fault = new InvalidOperationException("the connection could not be returned"); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { Dispose = fault }), operations, TimeSpan.FromSeconds(30)); + + var act = async () => await service.RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias); + + var thrown = (await act.Should().ThrowAsync()).Which; + (thrown.CommitOutcomeUnknown, thrown.InnerException).Should().Be((true, fault)); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task An_unexpected_provider_failure_after_the_change_may_have_been_sent_is_completed_as_uncertain_with_its_cause(string act) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var fault = new ObjectDisposedException("the host is shutting down"); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeRemove = () => throw fault; + operations.BeforeDisable = () => throw fault; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + result.Cause.Should().BeSameAs(fault); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, remove ? "platform.federation.remove_attempt" : "platform.federation.disable_attempt", + remove ? "platform.federation.remove" : "platform.federation.disable"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("uncertain"); + } + + [Fact] + public async Task A_caller_that_leaves_while_the_provider_disables_the_broker_is_recorded_as_uncertain() + { + var owner = OwnerOf(Guid.CreateVersion7()); + using var caller = new CancellationTokenSource(); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeDisable = () => + { + caller.Cancel(); + throw new OperationCanceledException(caller.Token); + }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias, caller.Token); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_broker_the_provider_finds_already_gone_or_disabled_after_the_intent_is_recorded_as_already_applied_with_no_review_owed(string act) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted + { + Inspected = Facts(owner, readable: false), + RemoveOutcome = FederationOperatorOutcome.AlreadyApplied, + DisableOutcome = FederationOperatorOutcome.AlreadyApplied, + }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.AlreadyApplied); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Should().HaveCount(3, "it changed between the first read and the provider call, so both rows exist"); + using var after = JsonDocument.Parse(rows[2].After); + (after.RootElement.GetProperty("outcome").GetString(), after.RootElement.GetProperty("accountReviewOwed").GetBoolean()) + .Should().Be(("already_applied", false)); + } + + [Fact] + public async Task A_listing_that_runs_out_of_the_pages_time_is_unavailable_and_never_an_empty_realm() + { + var operations = new Scripted { ListFailure = new OperationCanceledException("the page's time ran out") }; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Unavailable); + result.Items.Should().BeEmpty(); + } + + [Fact] + public async Task An_intent_commit_that_fails_for_any_reason_stops_the_act_as_the_audit_failure_before_the_provider_is_called() + { + // The connection is closed after the intent row is written and before it is committed, as a dropped link would be: + // the commit then fails with a failure that is not a database exception, and it must still be the audit failure. + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + Scope(false, false, afterIntent: async connection => await connection.CloseAsync()), operations, TimeSpan.FromSeconds(30)); + + var act = async () => await service.RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync(); + operations.Removed.Should().BeEmpty("the effect must not start on an intent nobody can prove was recorded"); + } + [Theory] [InlineData(FederationOperatorOutcome.Uncertain, "uncertain", FederationActOutcome.Uncertain)] [InlineData(FederationOperatorOutcome.Unavailable, "unavailable", FederationActOutcome.Unavailable)] @@ -614,10 +806,11 @@ await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sq ((long)(await distinct.ExecuteScalarAsync())!).Should().BeGreaterThanOrEqualTo(2); } - private FederationBrokerOperations Service(Scripted operations, bool failIntent = false, bool failResult = false) => - new(Scope(failIntent, failResult), operations); + // A generous budget keeps the cases that finish well inside it from depending on a stalled runner. + private FederationBrokerOperations Service(Scripted operations, bool failIntent = false, bool failResult = false, TimeSpan? budget = null) => + new(Scope(failIntent, failResult), operations, budget ?? TimeSpan.FromSeconds(30)); - private PlatformAdminScope Scope(bool failIntent, bool failResult, Func? afterIntent = null) + private PlatformAdminScope Scope(bool failIntent, bool failResult, Func? afterIntent = null) { var platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); var store = AuditStore(); @@ -708,6 +901,53 @@ public Task WriteResultAsync(PlatformResult result, CancellationToken cancellati } } + /// What a faulting handle does, each at the moment the owner reaches that call. + private sealed class HandleFaults + { + public Exception? Commit { get; init; } + public Exception? Dispose { get; init; } + public bool HangResult { get; init; } + } + + /// The real scope with a handle that fails its commit or its disposal, or hangs its result write until cut. + private sealed class FaultingScope(IPlatformAdminScope inner, HandleFaults faults) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine), faults); + + private sealed class Handle(IPlatformAdminScopeHandle real, HandleFaults faults) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + real.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) => real.QueryAsync(sql, parameters, map, cancellationToken); + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public async Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + { + if (faults.HangResult) await Task.Delay(Timeout.Infinite, cancellationToken); + await real.WriteResultAsync(result, cancellationToken); + } + + public Task CommitAsync(CancellationToken cancellationToken = default) => + faults.Commit is { } fault ? Task.FromException(fault) : real.CommitAsync(cancellationToken); + + public async ValueTask DisposeAsync() + { + await real.DisposeAsync(); + if (faults.Dispose is { } fault) throw fault; + } + } + } + /// A scope whose database cannot be reached: entering it fails with the fault it was given. private sealed class ThrowingScope(Exception fault) : IPlatformAdminScope { @@ -721,12 +961,15 @@ public Task EnterAsync( private sealed record AuditRow(string Operation, string Outcome, Guid Tenant, string Metadata, string Before, string After, string EntityId); /// Fails the intent or the completion row of the operator, as an outage at that moment would. - private sealed class FailingStore(IServiceScopeFactory inner, bool failIntent, bool failResult, Func? afterIntent = null) + private sealed class FailingStore( + IServiceScopeFactory inner, bool failIntent, bool failResult, Func? afterIntent = null) : IServiceScopeFactory { public IServiceScope CreateScope() => new Scope(inner.CreateScope(), failIntent, failResult, afterIntent); - private sealed class Scope(IServiceScope inner, bool failIntent, bool failResult, Func? afterIntent) : IServiceScope, IServiceProvider + private sealed class Scope( + IServiceScope inner, bool failIntent, bool failResult, Func? afterIntent) + : IServiceScope, IServiceProvider { public IServiceProvider ServiceProvider => this; @@ -737,7 +980,8 @@ private sealed class Scope(IServiceScope inner, bool failIntent, bool failResult public void Dispose() => inner.Dispose(); } - private sealed class Decorator(IAuditStore store, bool failIntent, bool failResult, Func? afterIntent) : IAuditStore + private sealed class Decorator( + IAuditStore store, bool failIntent, bool failResult, Func? afterIntent) : IAuditStore { public Task WritePlatformScopeAsync(AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => @@ -750,7 +994,7 @@ public async Task WritePlatformOperatorIntentAsync(AuditEntryDraft entry, Platfo if (failIntent) throw new AuditWriteFailedException("forced intent failure"); await store.WritePlatformOperatorIntentAsync(entry, admission, connection, transaction, cancellationToken); // Between the intent and the provider call, as a tenant that commits a row at that moment would. - if (afterIntent is not null) await afterIntent(); + if (afterIntent is not null) await afterIntent(connection); } public Task WritePlatformOperatorResultAsync(AuditEntryDraft entry, PlatformAdmission admission, @@ -795,6 +1039,9 @@ private sealed class Scripted : IFederationOperator public FederationOperatorOutcome RemoveOutcome { get; set; } = FederationOperatorOutcome.Applied; public FederationOperatorOutcome DisableOutcome { get; set; } = FederationOperatorOutcome.Applied; public Func? BeforeRemove { get; set; } + public Func? BeforeDisable { get; set; } + public Exception? ListFailure { get; set; } + public List RemoveRequirements { get; } = []; public Dictionary MapperCounts { get; } = new(StringComparer.Ordinal); public HashSet MapperDeadlines { get; } = new(StringComparer.Ordinal); public List Calls { get; } = []; @@ -808,6 +1055,7 @@ public Task ListAsync(int offset, int limit, CancellationT Calls.Add("list"); Events?.Add("list"); Offsets.Add(offset); + if (ListFailure is not null) return Task.FromException(ListFailure); if (Unavailable) return Task.FromResult(FederationBrokerPage.Unavailable); var page = Listed.Skip(offset).Take(limit).ToList(); return Task.FromResult(new FederationBrokerPage(FederationOperatorStatus.Ok, page, 0, page.Count)); @@ -834,19 +1082,22 @@ public Task InspectAsync(string brokerAlias, Cancell return Task.FromResult(MapperCounts.TryGetValue(owner.Alias, out var count) ? count : 0); } - public async Task RemoveAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + public async Task RemoveAsync( + FederationBrokerOwner owner, bool requireDisabledUnreadable = false, CancellationToken cancellationToken = default) { Calls.Add("remove"); Removed.Add(owner); + RemoveRequirements.Add(requireDisabledUnreadable); if (BeforeRemove is { } hook) await hook(); return RemoveOutcome; } - public Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + public async Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) { Calls.Add("disable"); Disabled.Add(owner); - return Task.FromResult(DisableOutcome); + if (BeforeDisable is { } hook) await hook(); + return DisableOutcome; } } } diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index ccb868d7..a3a753d6 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -443,6 +443,26 @@ public async Task A_Body_That_Is_Not_Json_Or_Not_Valid_Json_Is_Answered_As_A_Pro _toggle.Calls.Should().BeEmpty(); } + [Fact] + public async Task The_Served_Contract_Documents_The_Federation_Report_Its_Unread_Count_And_The_Removal_Rule() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var paths = document.RootElement.GetProperty("paths"); + + var report = paths.GetProperty("/api/platform/v1/federation/brokers").GetProperty("get"); + report.GetProperty("description").GetString().Should().Contain("mappersUnread").And.Contain("not the end"); + var schema = document.RootElement.GetProperty("components").GetProperty("schemas").GetProperty("FederationReportResponse"); + schema.GetProperty("properties").TryGetProperty("mappersUnread", out var unread).Should().BeTrue(); + unread.GetProperty("type").ToString().Should().Contain("integer"); + schema.GetProperty("required").EnumerateArray().Select(item => item.GetString()).Should().Contain("mappersUnread"); + + var remove = paths.GetProperty("/api/platform/v1/federation/brokers/{alias}/remove").GetProperty("post"); + remove.GetProperty("description").GetString().Should().Contain("reads or is still enabled").And.Contain("disabled"); + document.RootElement.GetProperty("info").GetProperty("description").GetString().Should().Contain("federation-operator.md"); + var conflict = remove.GetProperty("responses").GetProperty("409").GetProperty("description").GetString(); + conflict.Should().Contain("errors.owner").And.Contain("errors.connection").And.Contain("errors.class").And.Contain("errors.provider"); + } + [Fact] public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Document_Does_Not_Carry_It() { @@ -769,8 +789,13 @@ public async Task A_Federation_Act_Answers_A_Repeat_Or_A_Missing_Alias_Without_O var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}"); response.StatusCode.Should().Be(status); - if (token is null) return; using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + if (token is null) + { + body.RootElement.GetProperty("code").GetString().Should().Be("not_found"); + return; + } + (body.RootElement.GetProperty("outcome").GetString(), body.RootElement.GetProperty("accountReviewOwed").GetBoolean()).Should().Be((token, owed)); } diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs index 5cda2bda..942aa9ab 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs @@ -122,7 +122,13 @@ public async Task The_operator_removes_an_unreadable_orphan_and_the_provider_del (await tenant.DeleteAsync(broken)).Should().Be(FederationProviderResult.Foreign); var stored = (await admin.GetAsync("identity-provider/instances/" + unmarked.Alias)).GetRawText(); - (await op.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + // The owner removes a broker a live row names only while it is unreadable and disabled, proved at the delete: this one + // is unreadable but still enabled, so the provider refuses and nothing is deleted. Disabled, it is removed. + (await op.RemoveAsync(broken, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Refused); + (await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetProperty("alias").GetString().Should().Be(broken.Alias); + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + (await op.RemoveAsync(broken, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Applied); (await admin.GetAsync("identity-provider/instances")).EnumerateArray() .Select(instance => instance.GetProperty("alias").GetString()).Should().NotContain(broken.Alias); diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs index 0fb9e468..b564fe38 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs @@ -37,6 +37,42 @@ public async Task With_the_admin_secret_the_confined_adapter_and_guarded_fetcher provider.GetRequiredService().Count.Should().Be(1); } + [Fact] + public async Task Without_the_admin_secret_the_operator_port_is_closed_and_answers_nothing_it_could_act_on() + { + await using var provider = Build(new Dictionary()); + var operations = provider.GetRequiredService(); + var connection = Guid.CreateVersion7(); + var owner = new FederationBrokerOwner( + LearnStack.SharedKernel.Identifiers.TenantId.From(Guid.CreateVersion7()), connection, "lsf-" + connection.ToString("N")); + + operations.Should().BeOfType(); + (await operations.ListAsync(0, 5)).Status.Should().Be(FederationOperatorStatus.Unavailable); + (await operations.InspectAsync(owner.Alias)).Status.Should().Be(FederationInspectionStatus.Unavailable); + (await operations.CountMappersAsync(owner)).Should().BeNull(); + (await operations.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + (await operations.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + } + + [Fact] + public async Task With_the_admin_secret_the_operator_is_its_own_adapter_instance_with_its_own_resilience_pipeline() + { + await using var provider = Build(new Dictionary + { + ["Federation:ClientSecret"] = "federation-admin-secret", + ["Authentication:Tenant:Issuer"] = "https://keycloak.example.com/realms/learnstack", + }); + + var operations = provider.GetRequiredService(); + var tenant = provider.GetRequiredService(); + + operations.GetType().Name.Should().Be("KeycloakFederationProvider"); + operations.Should().NotBeSameAs(tenant, "a sweep must not share the tenant calls' bulkhead and breaker"); + var operatorPipeline = provider.GetRequiredService>(); + var tenantPipeline = provider.GetRequiredService>(); + operatorPipeline.Pipeline.Should().NotBeSameAs(tenantPipeline.Pipeline); + } + [Fact] public void Plain_http_issuer_is_admitted_only_for_development_loopback() { @@ -140,6 +176,8 @@ private static ServiceProvider Build(Dictionary values, string // The module's defaults are registered first, exactly as the Identity foundation does. services.TryAddSingleton(); services.TryAddSingleton(); + // The operator's port has its own fail-closed default, registered by the Identity foundation the same way. + services.TryAddSingleton(); services.AddLearnStackFederationAdapter(configuration); return services.BuildServiceProvider(validateScopes: true); } diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs index 0528ce5f..6cb93589 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs @@ -617,6 +617,40 @@ await adapter.DisableAsync(owner), await adapter.RemoveAsync(owner), .NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme").And.NotContain("idp.example.com"); } + [Theory] + [InlineData("readable_disabled", false, false)] + [InlineData("unreadable_enabled", true, true)] + [InlineData("readable_enabled", false, true)] + public async Task A_remove_that_requires_an_unreadable_disabled_broker_proves_it_again_at_the_delete_and_sends_nothing_otherwise( + string kind, bool unreadable, bool enabled) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak(); + provider.Brokers[owner.Alias] = unreadable ? Unreadable(owner, enabled) : Stored(owner, enabled); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Refused, kind); + + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + provider.Brokers.Should().ContainKey(owner.Alias); + } + + [Fact] + public async Task A_remove_that_requires_an_unreadable_disabled_broker_deletes_one_and_an_unrequired_remove_deletes_any_owned_broker() + { + var gone = OwnerOf(); + var healthy = OwnerOf(); + var provider = new FakeKeycloak(); + provider.Brokers[gone.Alias] = Unreadable(gone, enabled: false); + provider.Brokers[healthy.Alias] = Stored(healthy, enabled: true); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(gone, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Applied); + (await adapter.RemoveAsync(healthy)).Should().Be(FederationOperatorOutcome.Applied, "an orphan needs no live-row proof"); + + provider.Brokers.Should().BeEmpty(); + } + [Fact] public void The_operator_ports_result_types_can_carry_no_secret_or_provider_text_because_they_declare_no_member_that_could() { diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index be69ce37..a76338a8 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1188,6 +1188,10 @@ realm users. > (Amendment 9 item 5), the runner fails the Delete with an owner mismatch, and the > row stays live. An unreadable owned broker with a live row therefore had no > removal path at all. + > + > **Correction (2026-11-20, Amendment 13 item 3).** The rule that the tenant adapter + > reports a broker foreign when its marker matches and it no longer reads is + > Amendment 5 item 5. Amendment 9 item 5 is the readable nonconforming broker. 6. **Disable sends back what the provider returned.** An unreadable owned broker cannot be rebuilt from the fixed profile, so the operator disable is the one provider write that does not build its body from the allow-list: it reads the instance, proves the @@ -1229,6 +1233,11 @@ state, without changing Amendment 10's choice of option, what the implementation never writes the tenant's row. The rows record the live state found, and the account review is owed as for any remove. Amendment 10 item 3 and Amendment 11 item 5 are read accordingly, and a readable nonconforming broker is still disabled, not removed. + + > **Erratum (2026-11-20, Amendment 13 item 1).** "It already fails closed" is not + > supported: an unreadable broker can still be enabled and serving, so the removal + > needs it disabled first. The pointer "Amendment 9 item 5" is Amendment 5 item 5 + > (Amendment 13 item 3). 2. **An unread mapper count is a page counter.** Amendment 11 item 4 reports an unread count "unknown, never zero". A broker whose only possible class is an extra mapper has no other class to carry the unknown, so the page carries it: `mappersUnread` @@ -1259,3 +1268,39 @@ state, without changing Amendment 10's choice of option, what the implementation The Decision, Status, Date and prior amendments of this record are unchanged, except for the inline erratum beside Amendment 11 item 5 that item 1 records. Acceptance of the linked records is not proof that anything they decide is implemented. + +### Amendment 13 — Federation operator steps: review round 2 corrections (2026-11-20) + +The second review round of Step 5 found that Amendment 12 item 1 rests on a premise the +code does not support, and three places where the behaviour or the record said less +than it should. The maintainer chose the removal in Amendment 12 item 1; item 1 below +narrows how it is done and is reported to the maintainer. + +1. **An unreadable owned broker is removed with a live row only after it is disabled.** + Amendment 12 item 1 said such a broker "already fails closed". It does not: + "unreadable" is the shape check of one read, a broker edited in the provider's + console can be unreadable and still serve sign-ins, and the tenant's brokered + publication does not depend on a provider read. A remove of a broker a live row + still names therefore needs it to read as unreadable **and** to be disabled. An + unreadable broker that is still enabled is refused (`errors.connection`): the + operator disables it, which is reversible, and removes it after. The adapter proves + both conditions again when the delete is about to be sent and sends nothing + otherwise (`refused`), so an inspection seconds old is not trusted. Amendment 12 + item 1 is read accordingly, and the tenant's row is still never written. +2. **A failure after a change is the unknown outcome, with its cause.** Any non-fatal + failure after a provider change landed or may have (the provider call itself, the + completion row, its commit, the handle's disposal) answers `503` + `dependency_unavailable` with the reason `outcome_unknown`, and the failure goes to + the route's log (event 7110) and never into a response. An unexpected provider + failure or a cancellation is recorded `uncertain` and still completed. Before any + change, a transient database fault is the plain `503` and anything else is the + defect it is. Amendment 12 item 3 is read accordingly. +3. **Pointers.** The rule that the tenant adapter reports a broker foreign when its + marker matches and it no longer reads is Amendment 5 item 5, and Amendment 9 item 5 + is the readable nonconforming broker. The erratum beside Amendment 11 item 5 and + Amendment 12 item 1 carry inline corrections. + +The Decision, Status, Date and prior amendments of this record are unchanged, except for +the inline errata beside Amendment 10 item 6 (recorded by Amendment 11), Amendment 11 +item 5 and Amendment 12 item 1 (recorded by Amendments 12 and 13). Acceptance of the +linked records is not proof that anything they decide is implemented. diff --git a/docs/glossary.md b/docs/glossary.md index 19dfb84a..09c2a743 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -14,7 +14,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | | **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | | **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, the federation report, remove or disable ([Federation operator](#federation-operator)), or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act, an inspection and the federation acts run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | -| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, removes an unreadable owned broker even when a live row names it (the tenant's own Delete cannot reach one) and refuses to remove a broker that reads while a live row names it, and cannot list or remove a realm user, so the account review a remove owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), [runbook](runbooks/federation-operator.md)). | +| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, removes an unreadable owned broker that is disabled even when a live row names it (the tenant's own Delete cannot reach one) and refuses to remove one that reads, or that is still enabled, while a live row names it, and cannot list or remove a realm user, so the account review a remove or a disable owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), corrected by Amendments 12 and 13, and the [runbook](runbooks/federation-operator.md)). | | **Operator recovery** | The operator's inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and its two fenced transitions: a **replay** resets one dead-lettered subscriber delivery and a **producer reset** resets one retry-exhausted outbox row, which renews its six-attempt budget. Each transition carries a **fence**, the state the operator read at inspection (for a replay the replay count, the dead-letter instant to the microsecond and the terminal reason; for a reset the attempts and the instant), and is refused with a stale-fence conflict when the row no longer shows it. It writes a MUST audit row on the same transaction. Job recovery and a dashboard do not exist ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md), [runbook](runbooks/operator-recovery.md)). | | **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 46d6f8f8..9c433757 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,075 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,138 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -524,6 +524,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 4 — review round 2 and its fixes (2026-11-20)](#p03-9-step-4--review-round-2-and-its-fixes-2026-11-20) — 39 lines - [P03-9 Step 5 — federation operator steps (2026-11-20)](#p03-9-step-5--federation-operator-steps-2026-11-20) — 71 lines - [P03-9 Step 5 — review round 1 and its fixes (2026-11-20)](#p03-9-step-5--review-round-1-and-its-fixes-2026-11-20) — 67 lines + - [P03-9 Step 5 — review round 2 and its fixes (2026-11-20)](#p03-9-step-5--review-round-2-and-its-fixes-2026-11-20) — 63 lines @@ -25256,3 +25257,66 @@ Decided and not changed: `mappersUnread` bound the cost, and the runbook says so. - **The disable reads the row once.** Amendment 11 item 8 accepts the read-and-write interleave; the effect fails closed. + +### P03-9 Step 5 — review round 2 and its fixes (2026-11-20) + +Three further read-only reviews ran over the round 1 fix commit with different lenses: +an adversarial analysis of the fixes and of the authority change they carry; contract +and documentation truth after the round 1 edits; and test adequacy of the fixes with +fresh eyes on the whole step. Each finding was verified against the code first. + +Fixed, with the proof that now catches each: + +- **The removal rule rested on a false premise.** Amendment 12 item 1 let the operator + remove an unreadable owned broker with a live row because it "already fails closed". + It does not: "unreadable" is the shape check of one read, a broker edited in the + provider's console can be unreadable and still serve sign-ins, and the tenant's + brokered publication does not depend on a provider read. The remove of a broker a + live row names now needs it to be unreadable **and disabled**, which the adapter + proves again at the delete and refuses to send otherwise. ADR-0099 Amendment 13 + records it with inline errata beside the false premise and the wrong pointer. The + maintainer's choice to make the class removable stands; the rule that narrows it is + reported to the maintainer. Owner tests refuse each combination that reads or is + enabled and remove an unreadable, disabled one with the live row untouched; adapter + tests refuse a readable, an enabled and an unreadable-enabled broker without sending + a delete; the real provider refuses an enabled unreadable broker, accepts it once + disabled, and a mutation sweep kills the dropped conditions. +- **A failure after the change could still say "nothing changed".** The owner tracks + whether a change may have landed. Any non-fatal failure after that point (the + provider call, the completion row, its commit, the handle's disposal, an unexpected + provider failure, a cancellation) is the unknown outcome with the failure kept as its + cause for warning 7110, and a completion that cannot be written is no longer swallowed + silently. The completion budget is injectable, so the owner tests cut a hung write in + two hundred milliseconds and otherwise run on a generous one. Tests fail the commit + with a connection fault, a closed transaction and a timeout, hang the write, fail the + disposal, throw from the provider after the send, abort the caller during a disable, + and have the provider find the broker already gone. +- **A wider intent-commit catch.** It excludes the fatal exceptions, and a test closes + the connection between the intent row and its commit. +- **Public surface.** Only the transient-fault classifier of the recovery fault helper + is public. +- **Record against behaviour.** The runbook's live-row exception, the review a disable + owes, the read of one alias that does not exist, the entry-row audit failure, the + paging that shifts when a remove shortens the provider's list, the refusal table of + operator access, the Standard 05 sentence that said the table is granted to the + application role only, the glossary, and the served contract (a description of the + report and its unread count, the removal rule, the federation runbook, a pinned + document test) are corrected. Three lines over eighty-eight columns are reflowed. +- **Test gaps.** The composition tests resolve the operator's port closed without the + secret and as its own adapter with its own pipeline with it; the tokenizer behind the + pinned listing query also refuses a query built through a builder or a property; the + `not_found` body, the already-applied-after-intent case, the unread count of the + first report test and the listing that runs out of time are asserted. + +Decided and not changed: + +- **A completion lost after a certainly applied change answers `503` + `outcome_unknown`,** not a `200` with a marker: the record is the one thing known to + be missing, and the runbook says a repeat answers `already_applied` with no review + owed, so the operator keeps their own record. +- **An unknown enum member in the route throws.** It is a defect to see (a `500`, which + the contract says may follow a landed act), and every member is covered today. +- **The budget's disposal is not bounded** after a failed commit; Npgsql's own command + timeout applies, and no test showed a hang. +- **Offset paging.** The cursor stays an offset; the runbook says to read a page again + after acting on it. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 4ffb133e..4cd1cbac 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -37,7 +37,7 @@ > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | -> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding), Step 3 (controlled issuer rebind) and Step 4 (operator recovery of asynchronous work) delivered and twice reviewed, Step 5 pending | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding), Step 3 (controlled issuer rebind), Step 4 (operator recovery of asynchronous work) and Step 5 (federation operator steps) delivered and twice reviewed; the merge closeout remains | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | diff --git a/docs/runbooks/federation-operator.md b/docs/runbooks/federation-operator.md index ed42b5c1..5a1ae4f2 100644 --- a/docs/runbooks/federation-operator.md +++ b/docs/runbooks/federation-operator.md @@ -2,9 +2,9 @@ How an operator finds the identity-provider brokers a tenant's federation left orphaned, unreadable or nonconforming, and removes or disables one. Decided in -[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md) and -implemented as Amendment 11. There is **no dashboard** and **no way to list or remove -a realm user**: this is an API and this document. +[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md), implemented +as Amendment 11 and corrected by Amendments 12 and 13. There is **no dashboard** and +**no way to list or remove a realm user**: this is an API and this document. ## What exists @@ -55,13 +55,14 @@ A broker that conforms and has a live row is not reported. - **Listing or removing realm users.** No LearnStack credential may enumerate or remove them ([ADR-0099 Decision Q1](../decisions/0099-confined-tenant-federation.md)). The account review below is yours, with your own realm authority. -- **Removing a broker that reads while a live row names it.** Disable it here if it - must stop now, and let the tenant's own *Delete* retire the connection with its - broker; a remove is refused (`errors.connection`) while a live row names a broker - that reads. A broker that does *not* read is the exception, below. +- **Removing a broker that reads, or one that is still enabled, while a live row names + it.** A remove is refused (`errors.connection`). Disable it here if it must stop now, + and let the tenant's own *Delete* retire the connection with its broker. The one + exception is a broker that does *not* read and is disabled: the tenant's own Delete + treats it as foreign and cannot, so nothing else can, and it is removed here. - **Repairing a broker.** There is no rewrite from the fixed profile on this surface. - The tenant's next readback corrects its own broker; an unreadable one is removed - here, because the tenant's own Delete treats it as foreign and cannot. + The tenant's next readback records a drifted broker's state on its own row and leaves + the broker as found; an unreadable one is disabled and then removed here. - **A broker whose tenant is archived or deleted with a live row.** That is [P03-10](../roadmap/phase-03-identity-admin.md)'s. - **A provider-side fence.** A tenant's create that lands after a sweep produces a new @@ -119,14 +120,17 @@ curl -s -H "Authorization: Bearer $TOKEN" \ | The broker is | Do | |---|---| | `orphan`, readable or not | **Remove** it | -| `unreadable_owned`, with or without a live row | **Remove** it: the tenant's own Delete cannot reach a broker that does not read, so nothing else can. The tenant's row stays as it was and its next readback finds the broker absent, after which the tenant's own Delete completes. Disable it instead only if the loss of its federated links must wait | -| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback corrects it, and until then the sign-in option fails closed. The tenant's own Delete can remove it, because it reads; a remove here is refused | +| `unreadable_owned`, no live row | **Remove** it | +| `unreadable_owned` with a live row, still `enabled` | **Disable** it first. "Unreadable" is a shape check of one read, and an unreadable broker can still be serving sign-ins, so a remove is refused (`errors.connection`). The disable is reversible in the provider's console | +| `unreadable_owned` with a live row, `enabled` false | **Remove** it: the tenant's own Delete treats a broker that does not read as foreign and cannot reach it, so nothing else can. The provider proves again at the delete that it still does not read and is still disabled, or sends nothing (`errors.provider`). The tenant's row stays as it was and its next readback finds the broker absent, after which the tenant's own Delete completes | +| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback records the drift on its row and leaves the broker as found. The tenant's own Delete can remove it, because it reads; a remove here is refused | | healthy with a live row | Neither: a disable is refused with `not_applicable` | A **remove** also deletes the broker's federated links, which is why [an account -review](#account-review-after-a-remove) is owed. A **disable** changes only `enabled` -at the provider and the tenant's own row is left to its next readback. Neither writes -the tenant's connection row. +review](#account-review-after-a-remove-or-a-disable) is owed. A **disable** changes +only `enabled` at the provider and keeps the links, but people who sign in only +through that broker cannot while it is disabled, so its review is smaller and is owed +too. Neither writes the tenant's connection row. ## Act @@ -143,7 +147,8 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ Use `.../disable` the same way. Each act proves the owner marker at the provider and reads the connection row (a live -row refuses a remove at once and writes no tenant row). It then writes an **intent** +row refuses the remove of a broker that reads or is still enabled at once, and writes +no tenant row). It then writes an **intent** row; a remove reads the row again, as the last check before the delete. It changes the provider, reads it back, and writes a **completion** row on a bounded budget of its own, so a client that leaves while the provider works does not lose the record. @@ -154,14 +159,14 @@ so a client that leaves while the provider works does not lose the record. | `200`, `outcome: already_applied` | The broker was already absent (remove) or already disabled (disable). Nothing was sent, and when it was so at the first read **no tenant row was written**; if it changed between that read and the provider call, the intent and completion rows exist and the completion says `already_applied` | | `404` | A disable named an alias no instance has | | `409`, `errors.owner` = `lockey_not_owned` | The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. Nothing was touched | -| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names a broker that reads, so a remove is refused. Disable it if it must stop now, and the tenant deletes the connection | +| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names the broker and it reads or is still enabled, so a remove is refused. Disable it first; a broker that does not read is then removable, and one that reads is retired by the tenant's own Delete | | `409`, `errors.class` = `lockey_not_applicable` | A disable found a healthy owned broker with a live row | -| `409`, `errors.provider` = `lockey_provider_refused` | The provider definitively refused the change. Nothing changed | +| `409`, `errors.provider` = `lockey_provider_refused` | The provider definitively refused the change, or a remove that was let through for an unreadable, disabled broker found it reading or enabled again at the delete. Nothing changed | | `400` | The alias is not a derived one, or the body or the ticket is malformed. A refusal at the gate carries no per-field errors | | `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.federation.admin` for an act), the body size or type, or the request budget | -| `503`, `audit_unavailable` | The intent row could not be written or committed, or the completion of a change that did not happen could not be: nothing changed, though the intent row may stand alone. Retry after the delay; error line 7105 is in the API's log | +| `503`, `audit_unavailable` | The scope's entry row (no intent row exists), or the intent row, could not be written or committed, or the completion of a change that did not happen could not be: nothing changed, though the intent row may stand alone. Retry after the delay; error line 7105 is in the API's log | | `503`, `dependency_unavailable` | The provider or the database could not be reached before any change was sent. Nothing changed. Retry after the delay | -| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, the request was aborted while it ran, or the completion that records it could not be written. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, the request was aborted while it ran, an unexpected failure followed it, or the completion that records it could not be written. It **may have landed**: see [An unknown outcome](#an-unknown-outcome). Warning 7110 in the API's log carries the failure | | `500` | An unexpected failure or a deployment defect (a refused credential, a missing grant): the API's log names it | A client that never received an answer (a timeout, a gateway error) is in the same @@ -171,8 +176,10 @@ position as an unknown outcome. There is no provider-side fence, so reconcile by reading, in this order: -1. Read the report again, or read the one alias. A remove that landed leaves no - instance with that alias; a disable that landed shows `enabled` false. +1. Read the report again from the same cursor (there is no read of one alias), or + look at the instance in the provider's console. A remove that landed leaves no + instance with that alias, so a report no longer lists it; a disable that landed + shows `enabled` false. 2. If it did not land, repeating the act is safe: it re-proves the marker and the row. 3. To tell your act from another operator's, read the tenant's audit rows by the `correlationId` of the failed response, as in [Check it worked](#check-it-worked). @@ -180,26 +187,34 @@ There is no provider-side fence, so reconcile by reading, in this order: A repeat of an act that had landed answers `already_applied` with `accountReviewOwed` false, and writes no row; that alone cannot say whose act it was, and it does not say a review is owed. **After an unknown remove that shows the broker gone, treat the account -review as owed.** The record is the `remove_attempt` row, with no completion row or -with an `uncertain` one. +review as owed**, and after an unknown disable that shows `enabled` false, treat the +smaller review (people who signed in only through it) as owed. The record is the +`remove_attempt` or `disable_attempt` row, with no completion row or with an +`uncertain` one. -## Account review after a remove +## Account review after a remove or a disable The provider deletes **the broker's federated links** with the broker and keeps the accounts. A person who signed in only through that provider still has an account, and -has lost the way into it. LearnStack cannot list or repair these accounts, and -Keycloak keeps link events for seven days only, so the review is a realm -administrator's, in the provider's own console under their own authority: +has lost the way into it. A disable keeps the links, and the same people cannot use +them while the broker is disabled: review them the same way, and re-enable the broker +in the provider's console if the disable was a mistake. LearnStack cannot list or +repair these accounts, and Keycloak keeps link events for seven days only, so the +review is a realm administrator's, in the provider's own console under their own +authority: 1. If the removal is not urgent, **note the linked users before you remove**: the - console lists a user's identity-provider links. + console lists a user's identity-provider links. For an unreadable, enabled broker + this is the time between the disable and the remove. 2. After the remove, review the accounts that depended on it: whether each has another credential or sign-in route, and whether its sessions must be ended. 3. Tell the tenant's owner. No owner notification channel exists before [Phase 08a](../roadmap/phase-08a-assessment-notifications.md), so this is by hand. An `accountReviewOwed` of `true` in the answer, and the same member in the completion -row's `after_state`, are the reminder. Nothing in LearnStack closes the review. +row's `after_state`, are the reminder for an applied or an uncertain act. A repeat of a +landed act answers `already_applied` with `false`, so keep your own record. Nothing in +LearnStack closes the review. ## Check it worked @@ -261,7 +276,10 @@ a killswitch act does. ## Limits - **Pages are slices of the realm.** A realm with many instances takes many pages; - there is no filter by tenant, class or alias. A page whose instances are unusually + there is no filter by tenant, class or alias. The cursor is an offset into the + provider's list, and a remove shortens that list: **read a page again from the same + cursor after you act on it**, or sweep first and act afterwards, or an instance that + moved up is skipped. A page whose instances are unusually large (over 1 MiB together) is refused as unavailable: lower `limit`. - **The mapper reads are sequential.** Each costs a token and a call, so a page of many healthy brokers can run out of its ten seconds; `mappersUnread` says so. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md index 584423d8..cb740c7b 100644 --- a/docs/runbooks/operator-access.md +++ b/docs/runbooks/operator-access.md @@ -168,11 +168,11 @@ production realm. | 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached: at start, or for more than 15 minutes after its keys were last fetched | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | | 403 | The token is good and this operator holds no grant for the act | Ask for the grant | | 400 | The ticket or the body is malformed | Fix the request | -| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, a recovery that names no such row, or the surface is not configured | Check the key, the tenant or the row and the issuer setting | -| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant), or a recovery found a stale fence or a row it may not act on | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) or the [recovery runbook](operator-recovery.md#act) | +| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, a recovery that names no such row, a federation disable of an alias no instance has, or the surface is not configured | Check the key, the tenant or the row and the issuer setting | +| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant), or a recovery found a stale fence or a row it may not act on, or a federation act refused its state (`errors.owner`, `errors.connection`, `errors.class` or `errors.provider`; see the [federation runbook](federation-operator.md#act)) | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) or the [recovery runbook](operator-recovery.md#act) | | 415 | The body is not `application/json` | Send the header shown above | -| 503 | The audit row could not be written, or a connection or a lane was unavailable, so nothing changed, except that a recovery's `503` can carry `errors.outcome` for a commit that may have landed. `Retry-After` says when to try again | Retry; the act is safe to repeat. For a recovery that names `errors.outcome`, read the [recovery runbook](operator-recovery.md#an-unknown-outcome) first | -| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request. A recovery is not: list again first | +| 503 | The audit row could not be written, or a connection or a lane was unavailable, so nothing changed, except that a recovery's or a federation act's `503` can carry `errors.outcome` for a change that may have landed. `Retry-After` says when to try again | Retry; the act is safe to repeat. For a recovery that names `errors.outcome`, read the [recovery runbook](operator-recovery.md#an-unknown-outcome) first, and for a federation act the [federation runbook](federation-operator.md#an-unknown-outcome) | +| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request. A recovery is not: list again first; nor is a federation act, which may have changed the provider | The answer to a refused credential is always the same; the reason is in the signals, not the response. diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 2f4bedbe..4a06ab70 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6212,7 +6212,9 @@ owns qualification. classes): `[TenantOwned]` only, no organization column, the tenant-wide EF filter, `ENABLE` and `FORCE` RLS with the one tenant-only isolation policy of [the canonical template](#tenant-owned-and-organization-scoped-tables), and -`SELECT`, `INSERT`, `UPDATE` to `learnstack_app` only — no `DELETE` grant. It is the +`SELECT`, `INSERT`, `UPDATE` to `learnstack_app` and a four-column `SELECT` to +`learnstack_platform` ([below](#federation-operator-projection)); no `DELETE` grant. +It is the eighth member of the `SchemaTableClasses` Identity contextual class. The forward-only migration refuses reversal. @@ -6283,8 +6285,8 @@ alias, display name, issuer, client identifier, configuration digest or any othe is refused by PostgreSQL, and so is every write. The grant is a forward-only migration of the Identity chain, because the table is created there after the Platform chain has run. The reader is the one statement of the operator's owner, which sees tombstones -and reads by primary key; the architecture census pins it whole, and tests read the granted -columns, refuse every other, and read two tenants' rows through the role. +and reads by primary key; the architecture census pins it whole, and tests read the +granted columns, refuse every other, and read two tenants' rows through the role. ### Federation host-alias read diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 962ddd83..d5b94c2a 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -173,10 +173,10 @@ LearnStack runs **two Keycloak realms** per [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)), each behind an entry row and a per-act admission. The federation acts reach the identity provider only through the confined admin client and its operator port, after an intent row the - scope handle commits, and never read or remove a realm user. The executor that installs an - act's tenant context accepts only an admission the gate minted for that act within the - last 30 seconds and spends it once, and the seeder refuses to run outside a - Development deployment. The controlled issuer rebind + scope handle commits, and never read or remove a realm user. The executor that + installs an act's tenant context accepts only an admission the gate minted for that + act within the last 30 seconds and spends it once, and the seeder refuses to run + outside a Development deployment. The controlled issuer rebind ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)) is not an HTTP route at all: an offline tool validates the same operator token with the same validator, admits the act against the same per-act grant (`platform.identity_authority.admin`) and then diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index c0cea240..190e4805 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -487,13 +487,13 @@ bulkhead exactly 4 without a queue. These values are fixed: the composition root refuses any other value at startup, and refuses breaker parameters outside the ranges the provider specification states. The same class implements the operator port `IFederationOperator` -([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10 and 11), +([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendments 10 to 13), held only by the operator's owner and by the adapter, and built as a second instance with its own `IProviderResilience` pipeline of the same fixed shape so that an operator sweep cannot starve a tenant's calls; its fail-closed default -is registered beside the provider's. It adds one provider route, a paged listing of the realm's instances. -The operator egress allow-list `Federation:Egress:AllowedHosts` is composition -configuration, never tenant input. The +is registered beside the provider's. It adds one provider route, a paged listing of +the realm's instances. The operator egress allow-list `Federation:Egress:AllowedHosts` +is composition configuration, never tenant input. The [provider specification](../modules/identity/providers.md#tenant-federation-adapter) owns the admitted calls, profile and egress rules; the [realm runbook](../../infra/keycloak/README.md#federation-administration-client) owns the From 17c79db7af75983732646ccae4b22bafa5be2723 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 05:07:54 +0300 Subject: [PATCH 23/28] docs(roadmap): close P03-9 step 5 gate wording and verification record G13 and G14 now say their implementation is delivered, and the delivery log records the Step 5 verification, the two host-caused integration failures that are not defects, and the three questions still open for the maintainer. Co-Authored-By: Claude Sonnet 5.5 --- docs/roadmap/phase-03-delivery-log.md | 36 ++++++++++++++++++++++++- docs/roadmap/phase-03-identity-admin.md | 4 +-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 9c433757..b84acad2 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,138 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,171 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -525,6 +525,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — federation operator steps (2026-11-20)](#p03-9-step-5--federation-operator-steps-2026-11-20) — 71 lines - [P03-9 Step 5 — review round 1 and its fixes (2026-11-20)](#p03-9-step-5--review-round-1-and-its-fixes-2026-11-20) — 67 lines - [P03-9 Step 5 — review round 2 and its fixes (2026-11-20)](#p03-9-step-5--review-round-2-and-its-fixes-2026-11-20) — 63 lines + - [P03-9 Step 5 — verification and closeout (2026-11-21)](#p03-9-step-5--verification-and-closeout-2026-11-21) — 33 lines @@ -25320,3 +25321,36 @@ Decided and not changed: timeout applies, and no test showed a hang. - **Offset paging.** The cursor stays an offset; the runbook says to read a page again after acting on it. + +### P03-9 Step 5 — verification and closeout (2026-11-21) + +The final head of Step 5 passed every suite: 4,387 unit tests; 500 fast and 180 heavy +architecture tests, the heavy set including the lifecycle-census tests round 1 had +extended; and 4,884 integration tests against real PostgreSQL and the pinned Keycloak +26.7.5. Document lint, the fragment audit and the delivery-log index are clean, and a +mutation sweep over the guards of both review rounds killed every mutant but one +equivalent (a marker length check that the marker's round trip makes redundant). + +Two full integration runs of this head failed for the host and not for the code, and +are recorded so a later reader does not read them as a defect. The first lost the +container runtime's API mid-run (every failure a cancelled Docker request within a +millisecond); the second could not start its Keycloak fixtures in the fixed two-minute +window while the workstation was swapping nine of ten gigabytes. The run that counts +is the third, serialized with `xUnit.ParallelizeTestCollections=false` so that one +provider container exists at a time, and it took two hours and five minutes where the +parallel runs took about an hour and a half. + +The gate rows G13 and G14 of the decision register now say the implementation is +delivered, and the Status block says Step 5 is delivered and twice reviewed. What +remains of the packet is its merge closeout. + +Open for the maintainer, as recorded in Amendments 12 and 13: + +- **The audit outcome of a completion row is `success` for every closed provider + outcome.** A query for non-success rows misses a refused or uncertain provider call; + the provider outcome is `after_state.outcome`. +- **The marker's tenant is not checked against `tenants`.** Planting a marker needs + realm-console rights, which exceed a tenant administrator's. +- **The removal of an unreadable owned broker with a live row needs it disabled first.** + This narrows the choice the maintainer made in review round 1, because the premise + that an unreadable broker already fails closed was wrong. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 4cd1cbac..eb95ac64 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -150,8 +150,8 @@ named part, and the register links each explicit acceptance and vehicle. | G10 | What authenticated durable provider ingress is selected, and how are global events attributed? | Name producer, acknowledgement, stable provider-event dedup, ordering, tenantless/multi-membership routing, privacy and retention; enqueue through outbox, never direct business publication; no invented tenant or privileged app consumer | P03-6, or an earlier mechanism needing ingress | Provider-event ADR; ADR-0046/0057 boundaries, exact grants and Audit subscription | Accepted — 2026-11-11, [ADR-0097 and corrections](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11); [delivery and evidence record](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12) | | G11 | Which back-channel token profile, route and session targets are supported? | Separate OIDC purpose validation, signature/issuer/audience/time/events/no-nonce, replay retention, provider/session indexing and reachability; preserve late-work/accounting fences and unrelated/new session owners | P03-7 | ADR-0070 bounded extension; native route/provider configuration package | Accepted — 2026-11-12, [ADR-0098 and reviewed package](phase-03-delivery-log.md#p03-7-maintainer-review-corrections-and-acceptance-2026-11-12); implementation delivery is merged, with final-source evidence and the remaining pair qualification in the [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12) | | G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation delivery is merged, with evidence and follow-ups in the [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) | -| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Accepted — 2026-11-19, [ADR-0101](../decisions/0101-platform-operator-authority.md), [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); the machine-ingress slice was Accepted earlier under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md); implementation pending | -| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Accepted — 2026-11-19, [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); no dashboard is admitted; implementation pending | +| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Accepted — 2026-11-19, [ADR-0101](../decisions/0101-platform-operator-authority.md), [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); the machine-ingress slice was Accepted earlier under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md); implementation delivered by P03-9 Steps 1 to 3 and 5 (packet state in the Status block) | +| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Accepted — 2026-11-19, [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); no dashboard is admitted; implementation delivered by P03-9 Step 4 (packet state in the Status block) | | G15 | Who may request which person's data in which tenant/org scope and for which recipient/purpose? | Separate self/admin/delegate authority, subject predicates and org boundaries; category is not disclosure authority; resolve third-party data, holds, eligibility and post-erasure status access | P03-10 request writer | Data Protection/Identity request contract and module matrices | Open | | G16 | How do exports, closure and privileged redaction finish durably? | Decide artifact delivery/reauthorization/expiry, job/storage prerequisites, participant inventory/write fence, last-membership case and provider finalization; exact erasure grants/order/immutable references, user-reference locators and result-audit/inbox reconciliation | P03-1 only for shared closure-fence invariants; P03-10 workflow | Data Protection and ADR-0044/0046 privileged contract; migrations, module participation and phase package | Accepted shared fence; P03-10 workflow Open | | G17 | Which real production subjects and product journeys prove complete phase exit? | All deliverables/criteria, inherited catalogue clauses, no skips/empty censuses, real provider/native/app-role paths, manual accessibility and complete source-bound CI; analyzer escalation stays at exit | P03-11; packets retain their own proof | Phase package, evidence index, catalogue and existing test owners | Open | From bf434ebfc22161102aa0d0f3bec5ac4790b7e0ba Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 10:23:37 +0300 Subject: [PATCH 24/28] fix(platform): clear CA1068 and CA1822 that failed the hosted build The first hosted run failed every backend job at "Build Release with warnings as errors". CI=true turns analyzer warnings into errors, and the local runs never built with it. CA1068: the cancellation token of DeliveryInspection PageAsync is now its last parameter. CA1822: the Admission helper of the delivery-inspection integration test is now static. No behaviour changes. The delivery log records why the earlier verification missed it. Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperator/DeliveryInspection.cs | 19 ++++--- .../Database/DeliveryInspectionTests.cs | 52 +++++++++---------- docs/roadmap/phase-03-delivery-log.md | 26 +++++++++- 3 files changed, 62 insertions(+), 35 deletions(-) diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs index dc16f5c8..6f9dedea 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs @@ -74,14 +74,15 @@ internal static string DeliverySql(DeliveryInspectionState state, bool afterCurs { var byDeadLetter = state == DeliveryInspectionState.DeadLettered; return PageAsync( - admission, "outbox." + state, cursor, limit, cancellationToken, + admission, "outbox." + state, cursor, limit, (after, key, size) => new Statement( OutboxSql(state, after is not null), [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, size)]), reader => MapOutbox(reader), row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, row => row.EventId.ToString("D"), - key => Guid.TryParse(key, out _)); + key => Guid.TryParse(key, out _), + cancellationToken); } /// @@ -90,7 +91,7 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, { var byDeadLetter = state == DeliveryInspectionState.DeadLettered; return PageAsync( - admission, "delivery." + state, cursor, limit, cancellationToken, + admission, "delivery." + state, cursor, limit, (after, key, size) => { var parts = key?.Split('|'); @@ -108,14 +109,15 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, row => (byDeadLetter ? row.DeadLetteredAt!.Value : row.AvailableAfter).UtcTicks, row => $"{row.TenantId:D}|{row.SubscriptionId}|{row.EventId:D}", key => key.Split('|') is { Length: 3 } parts && Guid.TryParse(parts[0], out _) && Guid.TryParse(parts[2], out _) - && OutboxEventRegistry.ValidSubscriptionId(parts[1])); + && OutboxEventRegistry.ValidSubscriptionId(parts[1]), + cancellationToken); } /// public Task?> InspectJobsAsync( PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => PageAsync( - admission, "job.quarantined", cursor, limit, cancellationToken, + admission, "job.quarantined", cursor, limit, (after, key, size) => new Statement( """ SELECT j.id, j.tenant_id, j.organization_id, j.definition_key, j.profile, j.queue, j.capacity_group, @@ -134,19 +136,20 @@ [.. KeyParameters(after, key, Guid.TryParse(key, out var id) ? id : Guid.Empty, reader => MapJob(reader), row => row.CreatedAt.UtcTicks, row => row.JobId.ToString("D"), - key => Guid.TryParse(key, out _)); + key => Guid.TryParse(key, out _), + cancellationToken); private async Task?> PageAsync( PlatformAdmission admission, string scopeKey, string? cursor, int limit, - CancellationToken cancellationToken, Func statement, Func map, Func ticksOf, Func keyOf, - Func keyIsValid) + Func keyIsValid, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(admission); if (!ReferenceEquals(admission.Operation, PlatformOperations.DeliveryInspect)) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs index 36fadb58..9e644432 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs @@ -42,8 +42,8 @@ public async Task A_page_lists_dead_lettered_outbox_rows_oldest_first_with_the_f await proof.OutboxAsync(Guid.CreateVersion7(), "processed_at = now()"); await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted'"); - var first = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 2); - var second = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 2); + var first = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 2); + var second = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 2); first.Items.Select(row => row.EventId).Should().Equal(ids[0], ids[1]); first.NextCursor.Should().NotBeNull(); @@ -67,7 +67,7 @@ public async Task A_terminal_requested_row_is_listed_and_never_actionable() await proof.OutboxAsync(id, "attempts = 6, terminal_reason = 'retry_exhausted'"); await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); - var page = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 10); + var page = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 10); var row = page!.Items.Should().ContainSingle().Which; row.EventId.Should().Be(id); @@ -84,7 +84,7 @@ public async Task Deliveries_show_the_replay_fence_and_mark_what_a_replay_could_ await proof.DeliveryAsync(replayable, Subscription, "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.5+00', replay_count = 2, replayed_at = now()"); await proof.DeliveryAsync(envelope, Subscription, "terminal_reason = 'invalid_envelope', dead_lettered_at = '2026-10-02 12:00:00+00'"); - var page = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + var page = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); page!.Items.Select(row => row.EventId).Should().Equal(replayable, envelope); page.Items[0].Should().Match(row => row.ReplayCount == 2 && row.TerminalReason == "retry_exhausted" @@ -102,7 +102,7 @@ public async Task Quarantined_jobs_list_with_their_reservation_occupancy_and_no_ await SchemaQueries.ExecuteAsync(dispatcher, null, "UPDATE background_jobs SET phase = 'quarantined', quarantine_reason = 'unknown_outcome' WHERE id = @id", ("id", job.Value)); - var page = await proof.Inspection.InspectJobsAsync(proof.Admission(), null, 10); + var page = await proof.Inspection.InspectJobsAsync(Proof.Admission(), null, 10); var row = page!.Items.Should().ContainSingle().Which; row.JobId.Should().Be(job.Value); @@ -118,7 +118,7 @@ public async Task Each_page_writes_one_entry_row_naming_the_inspection_and_no_re { await using var proof = await Proof.CreateAsync(schema.Postgres); await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); - var admission = proof.Admission("INC-103"); + var admission = Proof.Admission("INC-103"); await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, null, 10); @@ -133,10 +133,10 @@ public async Task Each_page_writes_one_entry_row_naming_the_inspection_and_no_re public async Task A_malformed_or_foreign_cursor_answers_null_and_enters_no_scope() { await using var proof = await Proof.CreateAsync(schema.Postgres); - var admission = proof.Admission(); + var admission = Proof.Admission(); (await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, "not-a-cursor", 10)).Should().BeNull(); - (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("v1~outbox.DeadLettered~1~x")), 10)).Should().BeNull("a cursor of another resource is refused"); (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should().BeEmpty(); @@ -202,7 +202,7 @@ INSERT INTO background_job_reservations (tenant_id, capacity_group, job_id, atte WHERE j.id IN ('{held.Value}', '{neighbour.Value}'); """); - var page = await proof.Inspection.InspectJobsAsync(proof.Admission(), null, 10); + var page = await proof.Inspection.InspectJobsAsync(Proof.Admission(), null, 10); var row = page!.Items.Should().ContainSingle("only the quarantined job is listed").Which; row.JobId.Should().Be(held.Value); @@ -220,17 +220,17 @@ public async Task A_cursor_belongs_to_the_resource_and_state_that_issued_it_even await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index} 12:00:00+00'"); } - var outbox = (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; - var delivery = (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + var outbox = (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + var delivery = (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; outbox.Should().NotBeNull(); delivery.Should().NotBeNull(); // Each was issued for the route and state it came from: the same position under another one is refused. - (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, outbox, 10)).Should().BeNull(); - (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, delivery, 10)).Should().BeNull(); - (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().BeNull(); - (await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, delivery, 10)).Should().BeNull(); - (await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().NotBeNull(); + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().NotBeNull(); } [Fact] @@ -246,7 +246,7 @@ public async Task Deliveries_page_through_equal_instants_without_a_repeat_or_a_g var pages = 0; do { - var page = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, cursor, 2); + var page = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, cursor, 2); seen.AddRange(page!.Items.Select(row => row.EventId)); cursor = page.NextCursor; pages++; @@ -267,8 +267,8 @@ public async Task Terminal_requested_rows_page_in_the_order_their_dead_letter_is await proof.OutboxAsync(late, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-03 12:00:00+00'"); await proof.OutboxAsync(early, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-02 12:00:00+00'"); - var first = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 1); - var second = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.TerminalRequested, first!.NextCursor, 1); + var first = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 1); + var second = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, first!.NextCursor, 1); first.Items.Single().EventId.Should().Be(early); second!.Items.Single().EventId.Should().Be(late); @@ -306,8 +306,8 @@ public async Task The_last_error_a_page_shows_is_a_descriptor_or_the_word_unreco await proof.OutboxAsync(Guid.CreateVersion7(), $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); - var outbox = await proof.Inspection.InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); - var delivery = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + var outbox = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + var delivery = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); outbox!.Items.Single().LastError.Should().Be(shown); delivery!.Items.Single().LastError.Should().Be(shown); @@ -334,11 +334,11 @@ public async Task A_refused_credential_is_a_defect_and_an_unreachable_database_i // A retry cannot cure a refused credential, so it surfaces as the defect it is and not as a retryable outage. var refused = async () => await proof.InspectionOver(refusedSource) - .InspectOutboxAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + .InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); (await refused.Should().ThrowAsync()).Which.IsTransient.Should().BeFalse(); var outage = async () => await proof.InspectionOver(unreachableSource) - .InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + .InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); (await outage.Should().ThrowAsync()).Which.InnerException.Should().BeAssignableTo(); } @@ -353,8 +353,8 @@ public async Task Deliveries_with_equal_instants_page_by_tenant_then_subscriptio await proof.DeliveryAsync(larger, "a.first.v1", instant); await proof.DeliveryAsync(smaller, "b.second.v1", instant); - var first = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1); - var second = await proof.Inspection.InspectDeliveriesAsync(proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 1); + var first = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1); + var second = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 1); first.Items.Single().SubscriptionId.Should().Be("a.first.v1"); second!.Items.Single().SubscriptionId.Should().Be("b.second.v1", "the subscription orders before the event id"); @@ -487,7 +487,7 @@ INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at return proof; } - internal PlatformAdmission Admission(string? ticket = null) => TestPlatformAdmissions.Admission( + internal static PlatformAdmission Admission(string? ticket = null) => TestPlatformAdmissions.Admission( PlatformOperations.DeliveryInspect, ticket, correlationId: "00-inspect-" + Guid.NewGuid().ToString("N")); internal Task OutboxAsync(Guid id, string assignments) => SqlAsync($""" diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index b84acad2..6f08809a 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,171 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,194 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -526,6 +526,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — review round 1 and its fixes (2026-11-20)](#p03-9-step-5--review-round-1-and-its-fixes-2026-11-20) — 67 lines - [P03-9 Step 5 — review round 2 and its fixes (2026-11-20)](#p03-9-step-5--review-round-2-and-its-fixes-2026-11-20) — 63 lines - [P03-9 Step 5 — verification and closeout (2026-11-21)](#p03-9-step-5--verification-and-closeout-2026-11-21) — 33 lines + - [P03-9 Step 5 — hosted CI correction (2026-11-21)](#p03-9-step-5--hosted-ci-correction-2026-11-21) — 23 lines @@ -25354,3 +25355,26 @@ Open for the maintainer, as recorded in Amendments 12 and 13: - **The removal of an unreadable owned broker with a live row needs it disabled first.** This narrows the choice the maintainer made in review round 1, because the premise that an unreadable broker already fails closed was wrong. + +### P03-9 Step 5 — hosted CI correction (2026-11-21) + +The first hosted run of the pull request failed every backend job at the build, and the +verification record above did not catch it because the local runs never built with +`CI=true`. That setting turns analyzer warnings into errors +(`backend/Directory.Build.props`), so a plain local build shows them as warnings and the +suites ran against a tree the hosted gate refuses. The frontend, document, OpenAPI, +demo and secret-scan jobs passed. + +Two analyzer errors, both in Step 4 code and both hidden one behind the other, because +the first stopped the project every later project depends on: + +- **CA1068** in `DeliveryInspection.PageAsync`: the cancellation token preceded five + delegate parameters. It is now the last parameter. +- **CA1822** in the delivery-inspection integration test: the `Admission` helper read no + instance data. It is now static. + +Neither changes behaviour. The corrected tree builds clean with +`CI=true dotnet build LearnStack.slnx -c Release --no-incremental`, and the 136 +integration tests that exercise delivery inspection and the operator HTTP surface pass. +The record above stands for what it measured; this entry owns what it did not. The +build with warnings as errors is now part of the gate before any push of this packet. From 84914f985279d692b06a5a30b0c6879fcbd04d72 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 11:03:55 +0300 Subject: [PATCH 25/28] fix(platform): make two unit theories serializable for hosted CI The hosted discovery protocol refused two Step 1 theories that took an Exception and a PlatformOperation: xUnit cannot serialize either, so discovery listed one case and execution completed one id several times, failing backend-base with completed_case_unexpected. Both now take a label or an audit slug and build the object in the test. The delivery log records this and the unrelated Keycloak readiness timeout of ordinary-9. Co-Authored-By: Claude Sonnet 5.5 --- .../PlatformOperatorAuthenticationTests.cs | 60 ++++++++++++------- .../PlatformOperatorActCatalogTests.cs | 17 +++--- docs/roadmap/phase-03-delivery-log.md | 30 +++++++++- 3 files changed, 78 insertions(+), 29 deletions(-) diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs index 84cd273d..4b82fdd0 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorAuthenticationTests.cs @@ -127,30 +127,48 @@ public void Every_Profile_Cause_Has_A_Distinct_Closed_Label() labels.Should().OnlyHaveUniqueItems().And.OnlyContain(label => label.StartsWith("profile_", StringComparison.Ordinal)); } - public static TheoryData Failures() => new() + // A theory parameter must be one xUnit can serialize: a case holding an Exception is discovered as one + // case and executed as many, and the hosted discovery protocol refuses the second completion of one id. + // The label is the serializable key; the exception is built inside the test. + private static readonly (string Label, Func Failure, string Expected)[] FailureCases = + [ + ("no failure", () => null, "token_missing"), + ("profile refusal", () => new PlatformOperatorProfileException("profile_azp"), "profile_azp"), + ("expired", () => new SecurityTokenExpiredException("x"), "token_expired"), + ("not yet valid", () => new SecurityTokenNotYetValidException("x"), "token_lifetime"), + ("no expiration", () => new SecurityTokenNoExpirationException("x"), "token_lifetime"), + ("invalid signature", () => new SecurityTokenInvalidSignatureException("x"), "token_signature"), + ("signature key not found", () => new SecurityTokenSignatureKeyNotFoundException("x"), "token_signature"), + ("invalid issuer", () => new SecurityTokenInvalidIssuerException("x"), "token_issuer"), + ("invalid audience", () => new SecurityTokenInvalidAudienceException("x"), "token_audience"), + ("invalid algorithm", () => new SecurityTokenInvalidAlgorithmException("x"), "token_algorithm"), + ("invalid type", () => new SecurityTokenInvalidTypeException("x"), "token_type"), + ("aggregate of expiry and io", () => new AggregateException(new SecurityTokenExpiredException("x"), new IOException()), "token_expired"), + ("configuration unobtainable", () => new InvalidOperationException("IDX20803: Unable to obtain configuration."), "metadata_unavailable"), + ("wrapped io refusal", () => new InvalidOperationException("wrapped", new IOException("refused")), "metadata_unavailable"), + ("http down", () => new HttpRequestException("down"), "metadata_unavailable"), + ("other format fault", () => new FormatException("other"), "token_invalid"), + ]; + + public static TheoryData FailureLabels() { - { null, "token_missing" }, - { new PlatformOperatorProfileException("profile_azp"), "profile_azp" }, - { new SecurityTokenExpiredException("x"), "token_expired" }, - { new SecurityTokenNotYetValidException("x"), "token_lifetime" }, - { new SecurityTokenNoExpirationException("x"), "token_lifetime" }, - { new SecurityTokenInvalidSignatureException("x"), "token_signature" }, - { new SecurityTokenSignatureKeyNotFoundException("x"), "token_signature" }, - { new SecurityTokenInvalidIssuerException("x"), "token_issuer" }, - { new SecurityTokenInvalidAudienceException("x"), "token_audience" }, - { new SecurityTokenInvalidAlgorithmException("x"), "token_algorithm" }, - { new SecurityTokenInvalidTypeException("x"), "token_type" }, - { new AggregateException(new SecurityTokenExpiredException("x"), new IOException()), "token_expired" }, - { new InvalidOperationException("IDX20803: Unable to obtain configuration."), "metadata_unavailable" }, - { new InvalidOperationException("wrapped", new IOException("refused")), "metadata_unavailable" }, - { new HttpRequestException("down"), "metadata_unavailable" }, - { new FormatException("other"), "token_invalid" }, - }; + var labels = new TheoryData(); + foreach (var row in FailureCases) + { + labels.Add(row.Label); + } + + return labels; + } [Theory] - [MemberData(nameof(Failures))] - public void An_Authentication_Failure_Maps_To_One_Closed_Label(Exception? failure, string expected) => - PlatformOperatorFailure.Classify(failure).Should().Be(expected); + [MemberData(nameof(FailureLabels))] + public void An_Authentication_Failure_Maps_To_One_Closed_Label(string label) + { + var row = FailureCases.Single(candidate => candidate.Label == label); + + PlatformOperatorFailure.Classify(row.Failure()).Should().Be(row.Expected); + } [Theory] [InlineData("0")] diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs index 4933f038..5fa39873 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs @@ -25,8 +25,11 @@ public void The_Rebind_Operation_Is_Not_A_Pipeline_Act_Even_Though_It_Needs_No_P [Theory] [MemberData(nameof(NonPipelineOperations))] - public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_Catalog(PlatformOperation operation) + public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_Catalog(string auditSlug) { + // The slug, not the operation, is the theory parameter: xUnit cannot serialize a PlatformOperation, and a + // case it cannot serialize is discovered as one case and executed as five, which hosted CI refuses. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == auditSlug); operation.RunsInPipeline.Should().BeFalse(); var act = () => new PlatformOperatorActCatalog( @@ -35,13 +38,13 @@ public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_C act.Should().Throw(); } - public static TheoryData NonPipelineOperations() => new() + public static TheoryData NonPipelineOperations() => new() { - PlatformOperations.KillswitchToggle, - PlatformOperations.IdentityAuthorityRebind, - PlatformOperations.DeliveryInspect, - PlatformOperations.DeliveryReplay, - PlatformOperations.DeliveryReset, + PlatformOperations.KillswitchToggle.AuditSlug, + PlatformOperations.IdentityAuthorityRebind.AuditSlug, + PlatformOperations.DeliveryInspect.AuditSlug, + PlatformOperations.DeliveryReplay.AuditSlug, + PlatformOperations.DeliveryReset.AuditSlug, }; [Fact] diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 6f08809a..15ef933d 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,194 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,221 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -527,6 +527,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — review round 2 and its fixes (2026-11-20)](#p03-9-step-5--review-round-2-and-its-fixes-2026-11-20) — 63 lines - [P03-9 Step 5 — verification and closeout (2026-11-21)](#p03-9-step-5--verification-and-closeout-2026-11-21) — 33 lines - [P03-9 Step 5 — hosted CI correction (2026-11-21)](#p03-9-step-5--hosted-ci-correction-2026-11-21) — 23 lines + - [P03-9 Step 5 — hosted CI correction, second run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-second-run-2026-11-21) — 27 lines @@ -25378,3 +25379,30 @@ Neither changes behaviour. The corrected tree builds clean with integration tests that exercise delivery inspection and the operator HTTP surface pass. The record above stands for what it measured; this entry owns what it did not. The build with warnings as errors is now part of the gate before any push of this packet. + +### P03-9 Step 5 — hosted CI correction, second run (2026-11-21) + +With the build repaired, the second hosted run passed the build and 17 of the 19 backend +jobs, and failed two for different reasons. + +- **`backend-base`: `completed_case_unexpected`.** Two Step 1 theories took a parameter + xUnit cannot serialize, an `Exception?` and a `PlatformOperation`. Discovery lists such + a theory as one case, execution reports one result per data row under that same id, + and the hosted protocol refuses the second completion of an id. The last completed case + in the log, the first row of the exception theory, is where it stopped, after 395 of + 5,037 planned cases, so nothing after it had run. Both theories now take a serializable + key, a label and an audit slug, and build the object inside the test; discovery lists 16 + and 5 distinct cases for them. No local run could see this, because a local run reports + per row and the check lives in the hosted protocol only. +- **`backend-ordinary-9`: a Keycloak readiness timeout.** The one failed case, + `TenantRealmStockBaselineTests.Historical_stock_ordinary_reconciliation_…`, recorded + `readiness_timeout` at `provider_starting`, 120,001 ms and a TLS readiness outcome. It + is the hosted start-up flake already seen on this packet's earlier heads, in a test of an + older packet that passes locally; no code changed for it. + +Before pushing, the names a project discovers were compared with the names it executes for +all three assemblies of the base partition (4,387 unit, 656 integration without Docker, 13 +contract). They match, apart from the TRX escaping of surrogate pairs. A parameterised +theory that discovers as one case is the failure to look for, and the sweep over 1,398 +theories found only those two. The gate before any push of this packet is now the build +with warnings as errors and this comparison. From 82d18d8da0a94f8b41bd62e3115561334df4a375 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 12:21:08 +0300 Subject: [PATCH 26/28] fix(platform): wait on the realm request in the rebind signal test The hang-up case failed on the hosted runner under load. It polled for the tool's intent row as learnstack_platform, a role the tool's live-session count includes, so an open poll connection made the tool refuse the run as live sessions before the signal could cancel it. The test now waits for the realm's hung discovery request, which comes only after that count. Forty runs under load pass where one in ten failed. The tool is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .../IdentityAuthorityRebindToolTests.cs | 19 +++++-------- .../FakeKeycloakRealm.cs | 5 ++++ docs/roadmap/phase-03-delivery-log.md | 27 ++++++++++++++++++- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs index 750510f2..235282f3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs @@ -149,13 +149,16 @@ public async Task A_Signal_During_The_Realm_Read_Rolls_Back_Reports_Cancelled_An await using var run = await Run.StartAsync(parent); run.Realm.Fail("discovery-hang"); - // The intent row is written only after the signal handlers are in place, so its appearance is the readiness - // the signal waits for: no sleep guesses how long the runtime takes to start. + // The tool asks the realm only after its handlers are in place, its intent row is written and the sessions of + // every runtime role are counted, so the realm's hung request arriving is the instant the signal is meant for: + // no sleep guesses how long the runtime takes to start. The intent row is not that instant. It is written + // before the count, and a test that polls for it as the platform role holds a session of a runtime role that the + // count can see, which refuses the run as live sessions instead of cancelling it. // A process started under `nohup` inherits an ignored hang-up and keeps ignoring it, as it should, so the case // starts the tool with the default disposition restored: a tool the operator runs in tmux has it. var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, resetHangUp: signal == "HUP", whileRunning: async child => { - await run.WaitForRebindRowAsync(TimeSpan.FromSeconds(60)); + await run.Realm.DiscoveryHung.WaitAsync(TimeSpan.FromSeconds(60)); using var kill = Process.Start("kill", ["-" + signal, child.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)])!; await kill.WaitForExitAsync(); }); @@ -363,16 +366,6 @@ internal async Task RebindRowsAsync() return (long)(await command.ExecuteScalarAsync())!; } - internal async Task WaitForRebindRowAsync(TimeSpan within) - { - var clock = Stopwatch.StartNew(); - while (await RebindRowsAsync() == 0) - { - if (clock.Elapsed > within) throw new TimeoutException("The tool never wrote its intent row."); - await Task.Delay(100); - } - } - internal async Task> OperationsAsync(string correlation) { await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs index e9395589..2c2d1097 100644 --- a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -23,6 +23,7 @@ internal sealed class FakeKeycloakRealm : IAsyncDisposable private string? _failure; private int _pages; private int _firstPageRequests; + private readonly TaskCompletionSource _discoveryHung = new(TaskCreationOptions.RunContinuationsAsynchronously); private string _prefix = string.Empty; private FakeKeycloakRealm(WebApplication app, List users) @@ -50,6 +51,9 @@ private FakeKeycloakRealm(WebApplication app, List users) internal int Pages => Volatile.Read(ref _pages); + /// Completes when a discovery request has arrived at a realm set to never answer it. + internal Task DiscoveryHung => _discoveryHung.Task; + internal List> TokenRequests { get; } = []; internal List AdminAuthorization { get; } = []; @@ -91,6 +95,7 @@ private void Map(WebApplication app) if (_failure == "discovery-hang") { // The realm never answers: the request ends only when its caller gives up or goes away. + _discoveryHung.TrySetResult(); return Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, context.RequestAborted); } diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 15ef933d..c7622d79 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,221 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,245 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -528,6 +528,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — verification and closeout (2026-11-21)](#p03-9-step-5--verification-and-closeout-2026-11-21) — 33 lines - [P03-9 Step 5 — hosted CI correction (2026-11-21)](#p03-9-step-5--hosted-ci-correction-2026-11-21) — 23 lines - [P03-9 Step 5 — hosted CI correction, second run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-second-run-2026-11-21) — 27 lines + - [P03-9 Step 5 — hosted CI correction, third run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-third-run-2026-11-21) — 24 lines @@ -25406,3 +25407,27 @@ contract). They match, apart from the TRX escaping of surrogate pairs. A paramet theory that discovers as one case is the failure to look for, and the sweep over 1,398 theories found only those two. The gate before any push of this packet is now the build with warnings as errors and this comparison. + +### P03-9 Step 5 — hosted CI correction, third run (2026-11-21) + +The third hosted run passed the build, `backend-base` and every shard but one. The one +failure, `backend-ordinary-11`, was the hang-up case of +`IdentityAuthorityRebindToolTests.A_Signal_During_The_Realm_Read_…`, a Step 3 test; its +terminate case passed. The hosted record keeps no message for it, so the case was run in +an Ubuntu 24.04 container, the hosted distribution, against a real PostgreSQL. It passed +alone and ten times in a row, and failed once in ten under CPU load with the tool's own +line: `refused_live_sessions sessions=1` where the test expected `refused_cancelled`. + +The cause is the test, not the tool. The tool writes its intent row, then counts the +sessions of every runtime role, then reads the realm. The test took the appearance of the +intent row as the instant to signal, and polled for it as `learnstack_platform`, a role +the count includes. When a poll connection was still open as the tool counted, the tool +saw a live session and refused the run, which is what it exists to do. The signal never +had a chance to cancel a run that was already refused. The race needs load to show, which +is why every local run passed. + +The test now waits for the realm's hung discovery request to arrive. That request is made +only after the row is written and the sessions are counted, so it is the instant the signal +is meant for, and the test holds no database session while the tool counts. Under the same +load the hang-up case then passed 40 times in 40. The helper that polled for the row had no +other caller and is removed. The tool did not change. From f1e42f5581110b384218085b588f1d40dfa178a0 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 13:28:39 +0300 Subject: [PATCH 27/28] docs(roadmap): record the hosted layout-B result of P03-9 step 5 Layout A passes all jobs on the fix head; layout B refuses ordinary-11 at the 32 KiB filter ceiling of ADR-0063, deterministically. The record states the measured sizes and the maintainer's options; nothing in the plan or the ADR is changed. Co-Authored-By: Claude Sonnet 5.5 --- docs/roadmap/phase-03-delivery-log.md | 33 ++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index c7622d79..e53cf2d6 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,245 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,275 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -529,6 +529,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — hosted CI correction (2026-11-21)](#p03-9-step-5--hosted-ci-correction-2026-11-21) — 23 lines - [P03-9 Step 5 — hosted CI correction, second run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-second-run-2026-11-21) — 27 lines - [P03-9 Step 5 — hosted CI correction, third run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-third-run-2026-11-21) — 24 lines + - [P03-9 Step 5 — hosted CI, the opposite shard layout (2026-11-21)](#p03-9-step-5--hosted-ci-the-opposite-shard-layout-2026-11-21) — 30 lines @@ -25431,3 +25432,33 @@ only after the row is written and the sessions are counted, so it is the instant is meant for, and the test holds no database session while the tool counts. Under the same load the hang-up case then passed 40 times in 40. The helper that polled for the row had no other caller and is removed. The tool did not change. + +### P03-9 Step 5 — hosted CI, the opposite shard layout (2026-11-21) + +Head `82d18d8d` passed all 27 jobs in layout A (run attempt 1). Rerunning every job, as +[ADR-0063](../decisions/0063-complete-bounded-ci-test-shards.md) requires for the second +qualification, ran layout B (attempt 2) and failed two producers, for different reasons. + +- **`backend-ordinary-11`: `filter_bound`, no test ran.** The filter that lists the + shard's selectors came to 33,367 bytes against the 32,768-byte ceiling. It was computed + with the repository's own `assign` and `filter_for` over the run's discovery manifest and + the committed plan: layout B gives the twelve ordinary shards 21,794 to 33,367 bytes, with + `ordinary-7` at 31,989; layout A gives 27,144 to 28,123. Assignment is deterministic from + the manifest and the plan, so every layout-B attempt on this source refuses the same way + and a rerun cannot pass. The population is 2,052 distinct ordinary selectors; twelve + shards at the ceiling hold about 2,300 even when perfectly balanced, so the ceiling + binds layout A as well within a modest amount of further growth. +- **`backend-ordinary-7`: a Keycloak readiness timeout.** `readiness_timeout` at + `provider_starting`, 120,002 ms and a TLS readiness outcome at the first fixture, + failing the realm tests that share it. This is the hosted start-up flake already + recorded on this packet's earlier heads; no code is implicated. + +Nothing was changed for the first. ADR-0063 bounds filter arguments to 32 KiB, the +ordinary shards to eight through twelve (twelve are in use), and requires a reviewed plan +revision, an assignment diff and fresh qualification for any change of count, bound, +algorithm or salt. Whether to revise the plan, change the bound or reopen the decision is +the maintainer's. The candidates are a new B salt (cheap, and a lucky rebalance that the +next growth undoes), a byte-aware assignment (an algorithm version), a higher bound (which +the hosted boundary must then qualify) or a thirteenth shard (the envelope's end, which +reopens the decision). Until one is chosen, layout A is qualified on this source and layout +B is not. From db7776b9b50013fad61c2041863315ace54793ac Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 13:38:33 +0300 Subject: [PATCH 28/28] test: make unserializable theory data a build error xUnit1044 and xUnit1045 are off by default and are exactly the fault that failed backend-base on the hosted discovery protocol: a theory whose data xUnit cannot serialize is discovered as one case and completed once per row. Both are now errors for the test projects. The whole solution builds clean under them, and the two original bad shapes fail the build. Standards 06 states the rule beside the protocol it protects. Co-Authored-By: Claude Sonnet 5.5 --- backend/tests/.editorconfig | 7 +++++++ docs/roadmap/phase-03-delivery-log.md | 19 ++++++++++++++++++- docs/standards/06-testing.md | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/backend/tests/.editorconfig b/backend/tests/.editorconfig index b063d0c6..b1e26276 100644 --- a/backend/tests/.editorconfig +++ b/backend/tests/.editorconfig @@ -22,3 +22,10 @@ dotnet_diagnostic.CA1515.severity = none dotnet_diagnostic.CA1034.severity = none # `HttpClient.GetAsync(string)` overload is fine in test assertions. dotnet_diagnostic.CA2234.severity = none +# A theory whose data xUnit cannot serialize is discovered as one case and executed as +# one result per row under that single id, which the hosted discovery protocol refuses +# (`completed_case_unexpected`, ADR-0063) and no local run shows. Both rules are off by +# default in xunit.analyzers; an Exception, a record or a delegate in `TheoryData<...>` +# is the case. Pass a label or a key and build the object inside the test. +dotnet_diagnostic.xUnit1044.severity = error +dotnet_diagnostic.xUnit1045.severity = error diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index e53cf2d6..1662a500 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -509,7 +509,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines -- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,275 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,291 lines - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines @@ -530,6 +530,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-9 Step 5 — hosted CI correction, second run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-second-run-2026-11-21) — 27 lines - [P03-9 Step 5 — hosted CI correction, third run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-third-run-2026-11-21) — 24 lines - [P03-9 Step 5 — hosted CI, the opposite shard layout (2026-11-21)](#p03-9-step-5--hosted-ci-the-opposite-shard-layout-2026-11-21) — 30 lines + - [P03-9 Step 5 — a local guard for unserializable theory data (2026-11-21)](#p03-9-step-5--a-local-guard-for-unserializable-theory-data-2026-11-21) — 16 lines @@ -25462,3 +25463,19 @@ next growth undoes), a byte-aware assignment (an algorithm version), a higher bo the hosted boundary must then qualify) or a thirteenth shard (the envelope's end, which reopens the decision). Until one is chosen, layout A is qualified on this source and layout B is not. + +### P03-9 Step 5 — a local guard for unserializable theory data (2026-11-21) + +The maintainer asked for a guard that shows locally what only the hosted discovery +protocol showed: a theory whose data xUnit cannot serialize. The rule already exists. The +`xunit.analyzers` package that comes with xUnit 2.9.2 ships `xUnit1044` (the type argument +is not serializable) and `xUnit1045` (it might not be), both off by default. A scratch +theory with the two original shapes, a `PlatformOperation` record and an `Exception?` in +`TheoryData`, fails the build with them at error severity: `xUnit1044` for the first, +`xUnit1045` for the second. With both set to error in `backend/tests/.editorconfig`, the +whole solution builds with no warning and no error, so no existing theory breaks the rule. + +This replaces the reflection rule the question proposed. An analyzer knows what xUnit can +serialize, shows the fault in the editor and needs no catalogue entry, and the architecture +catalogue and its counts are unchanged. Standards 06 states the rule beside the +discovery protocol it protects. diff --git a/docs/standards/06-testing.md b/docs/standards/06-testing.md index 88b5c691..8a29719b 100644 --- a/docs/standards/06-testing.md +++ b/docs/standards/06-testing.md @@ -237,6 +237,11 @@ source of truth; the finite workflow matrix must agree before launch. Actual Release discovery supplies assembly, case ID and FullyQualifiedName. Selected filters are independently rediscovered before execution; all theory rows stay with their selector. Advisory weights never define membership or a wall bound. +A theory's data must be serializable by xUnit, or discovery lists one case and +execution completes one id once per row, which the protocol refuses as +`completed_case_unexpected`; no local run shows it. `xUnit1044` and `xUnit1045` are +errors in `backend/tests/.editorconfig` for that reason: pass a label or a key and +build the object inside the test. `scripts/ci-test-shards.py` and `scripts/ci-test-shard-results.py` implement the two always-running aggregates under the unchanged backend/integration required