From 77aa67fb15ab78b035f6445071df1cba829be279 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sat, 21 Nov 2026 17:59:25 +0300 Subject: [PATCH 01/61] docs(roadmap): close P03-9 delivery after merge Record PR #46's merge, the final-head layout A run beside the four hosted-only faults the pull request exposed, and the evidence that stays open: layout-B and pair qualification (the filter ceiling is ADR-0105, PR #47), the maintainer items and the pre-commit worktree note. Mark P03-9 complete in the phase Status block and close G13 and G14's rows, bring the README's Identity row up to the delivered packet and point the ADR-0099 index row at Amendments 10 to 13. ADR: 0069 Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- docs/decisions/README.md | 2 +- docs/roadmap/phase-03-delivery-log.md | 63 ++++++++++++++++++++++++- docs/roadmap/phase-03-identity-admin.md | 36 +++++++------- 4 files changed, 82 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index c3bb3aaa..1ea676dc 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, 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) | +| **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, confined tenant SAML/OIDC federation, an admitted Platform operator gate with a killswitch writer, production tenant onboarding, a controlled issuer rebind, fenced operator recovery of asynchronous work, and operator steps for the federation brokers a tenant left behind | DSAR, export and erasure 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 0530e17d..0b930134 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 (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. | +| 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; [Amendment 10](0099-confined-tenant-federation.md#amendment-10--federation-operator-steps-2026-11-19) decides the P03-9 federation operator steps and Amendments 11 to 13 record their implementation contract and two review rounds, the last making an unreadable broker removable only once it is disabled ([Amendment 13](0099-confined-tenant-federation.md#amendment-13--federation-operator-steps-review-round-2-corrections-2026-11-20)). | | 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) | 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. | diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 1662a500..03a18fe7 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,291 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,351 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 @@ -531,6 +531,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [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 + - [P03-9 merge and delivery closeout (2026-11-21)](#p03-9-merge-and-delivery-closeout-2026-11-21) — 60 lines @@ -25479,3 +25480,63 @@ This replaces the reflection rule the question proposed. An analyzer knows what 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. + +### P03-9 merge and delivery closeout (2026-11-21) + +[PR #46](https://github.com/HodeTech/LearnStack/pull/46) merged into `main` at +`2026-11-21T14:55:37Z` as `0a2de9bc`, from head `db7776b9`. The packet delivered the +admitted Platform gate with its killswitch writer, production tenant onboarding, the +controlled issuer rebind, fenced operator recovery of asynchronous work and the federation +operator steps, under ADR-0101 to ADR-0104, ADR-0099 Amendments 10 to 13 and ADR-0044 +Amendment 18. No dashboard and no operator CLI or UI exist; the client is the served +`platform-v1` contract and the runbooks. G13 and G14 are closed as Accepted with their +implementation delivered; G20 stays Open. + +**Final-head evidence.** Head `db7776b9` passed all 27 jobs in layout A on its first +attempt (run `44895323320`). The local suites on the Step 5 head were 4,387 unit tests, 500 +fast and 180 heavy architecture tests and 4,884 integration tests; the later heads add only +the corrections below, each verified by the targeted local and hosted runs its record names. +No original-archive verification was performed for this head, and no manual evidence was +produced because the packet has no UI. + +**What the hosted runs corrected.** The first hosted run of the pull request exposed four +faults that no local run had shown, recorded in the entries above: two analyzer errors that +only `CI=true` raises, two theories with parameters xUnit cannot serialize, a rebind-tool +signal test that polled the database as a role the tool counts as a live session, and a +layout-B filter above the 32 KiB ceiling. The first three are fixed on `main`. The fourth is +Accepted as [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md) and +carried by [PR #47](https://github.com/HodeTech/LearnStack/pull/47). `xUnit1044` and +`xUnit1045` are now build errors in the test projects, so the second fault cannot recur +unseen. + +**Layout-B and pair qualification stays open.** Layout B for the P03-9 population is +refused at the filter ceiling, deterministically (33,367 bytes against 32,768; head +`82d18d8d`, attempt 2). PR #47 raises the bounds; on its source layout B passed 27/27, its +layout A first attempt failed on two hosted flakes (a Keycloak readiness timeout in +`ordinary-1` and a frontend development-server test with no frontend file in the diff) and a +second layout-A attempt was running when this was written. Merging #46 does not waive the +qualification, which stays open before P03-11 exit. + +**Open for the maintainer**, as recorded in the step records and the ADR amendments: + +- The completion row's audit outcome is `success` for every closed provider outcome; the + provider outcome is `after_state.outcome`. +- The federation marker's tenant is not checked against `tenants`. +- Removing an unreadable owned broker with a live row needs it disabled first; this narrows + the choice made in review round 1 (ADR-0099 Amendment 13). +- The Step 2 and Step 4 questions: a user-eligibility-aware recovery predicate, the failure + descriptor in the recovery audit row, and the platform role's loss of `SELECT` on the + correlation columns of the outbox, which constrains P03-10 and Phase 11. +- The hosted Keycloak start-up timeout (`readiness_timeout`, TLS, 120 seconds) recurred on + this packet's heads in three shards, in both layouts and on #47. Its cause is still + unproven and no code is implicated. +- **Tooling.** `.githooks/pre-commit` runs `git init` and `git config` for its + `.leakwatchignore` isolation under the `GIT_DIR` a commit exports. In a linked worktree + that `GIT_DIR` is the shared repository, so a worktree commit rewrote the main + checkout's configuration (`core.bare = true` and a stray `core.excludesFile`). The + settings were restored and the hook is unchanged; clearing `GIT_DIR` for those two calls + is the candidate correction, and until then commits belong in a full clone. + +P03-10 (subject-scoped DSAR, export, erasure and closure, with G15 and G16 Open) and P03-11 +(complete evidence, gateway scaffold correction, analyzer escalation, with G17 and G18 +Open) remain unstarted. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index eb95ac64..8da5d623 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -1,15 +1,10 @@ # Phase 03: Identity Domain, Authorization, and Admin Foundation -> **Status (2026-11-19).** P03-0 through P03-8 implementation delivery is complete; +> **Status (2026-11-21).** P03-0 through P03-9 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). -> Its [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12) -> records three steps, reviews/corrections, final-head `dd9721f0` layout B -> (27/27 jobs) and 25 verified originals. Opposite-layout A/pair qualification -> remains open before P03-11 exit; merge does not waive it. -> P03-3/P03-4 final-head B/original-archive follow-ups and P03-6 opposite-layout -> A/pair qualification also remain open before phase exit. P03-4 has final-source +> P03-3/P03-4 final-head B/original-archive follow-ups and P03-6/P03-7 opposite-layout +> A/pair qualification remain open before phase exit; merge waives none (P03-7 merged in +> [PR #44](https://github.com/HodeTech/LearnStack/pull/44) with final-head layout B only). P03-4 has final-source > A only; earlier-source pairs do not close these gaps. P03-5 has verified > final-head `b96c2f65` A/B (27/27 each) and fifty originals. > P03-3 [manual accessibility evidence](phase-03-delivery-log.md#p03-3-maintainer-approved-manual-deferral-and-step-10-continuation-2026-10-30) @@ -19,12 +14,17 @@ > 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 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-10 and P03-11 remain unstarted. +> [ADR-0099](../decisions/0099-confined-tenant-federation.md) and [ADR-0100](../decisions/0100-p038-federation-contract-transition.md) +> with final-head layout A only; B/pair qualification stays open before P03-11 exit, manual +> accessibility was not performed and G12 is closed as Accepted. +> P03-9 is merged in [PR #46](https://github.com/HodeTech/LearnStack/pull/46) under Accepted +> [ADR-0101](../decisions/0101-platform-operator-authority.md) to +> [ADR-0104](../decisions/0104-controlled-issuer-rebind.md), ADR-0099 Amendments 10–13 and +> ADR-0044 Amendment 18, with final-head layout A only. The layout-B filter ceiling it met is +> [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), carried by +> [PR #47](https://github.com/HodeTech/LearnStack/pull/47); B/pair qualification stays open +> before P03-11 exit. No manual UI evidence is owed. G13 and G14 are 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 | 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-9 | Platform authority and operational recovery | Complete and merged — [closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21); final-head opposite-layout/pair qualification remains open (the layout-B filter ceiling is [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md)); the maintainer items, the P03-10 and Phase 11 constraint and the tooling note are owned in the closeout | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | @@ -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 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) | +| 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 and merged by P03-9 Steps 1 to 3 and 5 ([closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21)) | +| 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 and merged by P03-9 Step 4 ([closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21)) | | 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 211b9fd3cc3d551472b0ba17b9ecb791bd687a79 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 00:34:30 +0300 Subject: [PATCH 02/61] docs(roadmap): record the ADR-0105 merge and hosted qualification PR #47 merged as 8ac14286. The record carries the hosted layout A and B result on the reviewed source, a direct 64 KiB and 131,000-byte filter check on the runner image, the Sourcery dispositions, the unfinished runs on the merge commit and on main after #46, and why the P03-9 pair gap stays open. Co-Authored-By: Claude Sonnet 5.5 --- docs/roadmap/phase-03-delivery-log.md | 60 ++++++++++++++++++++++++- docs/roadmap/phase-03-identity-admin.md | 10 ++--- 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 31af879b..8b76b4fa 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,375 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,432 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 @@ -533,6 +533,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [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 - [ADR-0105 acceptance and implementation (2026-11-21)](#adr-0105-acceptance-and-implementation-2026-11-21) — 24 lines - [P03-9 merge and delivery closeout (2026-11-21)](#p03-9-merge-and-delivery-closeout-2026-11-21) — 60 lines + - [ADR-0105 merge and hosted qualification (2026-11-22)](#adr-0105-merge-and-hosted-qualification-2026-11-22) — 57 lines @@ -25565,3 +25566,60 @@ qualification, which stays open before P03-11 exit. P03-10 (subject-scoped DSAR, export, erasure and closure, with G15 and G16 Open) and P03-11 (complete evidence, gateway scaffold correction, analyzer escalation, with G17 and G18 Open) remain unstarted. + +### ADR-0105 merge and hosted qualification (2026-11-22) + +[PR #47](https://github.com/HodeTech/LearnStack/pull/47) merged into `main` at +`2026-11-21T21:31:48Z` as the squash commit `8ac14286`. The reviewed change is the single +commit `76501822`, which differs from the P03-9 final head `db7776b9` only in the two +bounds, the shard-test controls, ADR-0105, ADR-0063 Amendment 4 and the acceptance record; +no backend, frontend or schema file changed. GitHub later added the merge commit `86030d22` +(`main` into the branch) with a tree identical to `76501822`. + +**Hosted qualification of the larger filter.** Run `44909390165` on `76501822`, one source +in every attempt: layout B (attempt 2) 27/27, including `backend-ordinary-11`, which layout B +refused at 33,367 bytes before this change; layout A (attempt 3) 27/27. Layout A's first +attempt failed on two hosted flakes with no file of the change involved: the Keycloak +readiness timeout in `ordinary-1` and a frontend development-server test. A filter above +32 KiB therefore passes discovery, independent rediscovery and execution on the hosted +chain. The largest real filter in those runs is 33,367 bytes, 51 % of the new bound, so the +hosted evidence does not itself reach the ceiling. + +**The ceiling itself.** On the runner's image (`dotnet/sdk:10.0.402-noble`, Ubuntu 24.04), +`dotnet test --list-tests` and a real run of the unit assembly accepted a shard-shaped +filter of exactly 65,536 bytes (two real tests plus padding selectors) and one of 131,000 +bytes, and listed and ran exactly the two real tests: nothing was refused, truncated or +altered. This is a direct check of the claim ADR-0105 leaves to qualification; it is a +synthetic filter, not a hosted shard. + +**Review.** Sourcery raised two findings on the head and no other reviewer posted one. The +first, that the 64 KiB boundary test fails as `selector_unsupported`, does not reproduce: the +control builds 33 selectors of about 1,900 characters and pads only the last to 1,860 +characters, under the 2,048-character method grammar, and 88 shard tests pass. (The +single-padded-method shape it describes does fail that way, which is why the test uses many +methods.) The second, that a filter above 32 KiB may not survive the hosted chain, is answered +by the two checks above, and a filter the chain altered would still be refused by the +population comparison (`selected_population_mismatch`) or by `filter_bound` before spawn. +Both threads carry these replies; no code changed. + +**What the pull request's last runs showed.** The pull-request run on the merge commit +(`44938380249`) never produced a complete result, and the qualification rests on the +identical-tree run above. Attempt 1 (layout A) failed `ordinary-9` on a 30-second poll in +`BackgroundJobRecurrenceStoreTests.Four_actual_recipient_owners_remain_bounded_and_excluded_after_expiry_while_other_recipients_progress` +(`recurrence_runtime`, a `timeout`); six runs of it under load in the Linux image passed, so +the cause is unproven and no code is implicated. Attempt 2 (layout B) failed `ordinary-1` on the +Keycloak readiness timeout (TLS, 120 seconds, fixture ordinal 3). Attempt 3 did not complete: +its jobs were cancelled around the merge. + +**`main` after #46.** The push run for the #46 merge commit `0a2de9bc` (`44916448250`, +layout A) failed `ordinary-4` and `ordinary-11` on the same Keycloak timeout, once reported +as `completed_case_unexpected` instead of `tests_failed`. Rerunning it would run layout B +against the old 32 KiB ceiling and be refused, so it is superseded by the push run for +`8ac14286` (`44952008120`), whose result this record does not carry. + +**Consequence for the open qualification.** The P03-9 code now has a complete layout A and a +complete layout B on one source, `76501822`, but that source is not the merged P03-9 final +head `db7776b9`, and the earlier packets' rule keys qualification to the final head. The +Status block therefore keeps the P03-9 pair gap open and names this run; whether it closes +the gap is the maintainer's decision. The Keycloak readiness timeout has now recurred in +both layouts on #46, on #47 and on `main`, with its cause still unproven. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 8da5d623..dc6c7493 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-21).** P03-0 through P03-9 implementation delivery is complete; +> **Status (2026-11-22).** P03-0 through P03-9 implementation delivery is complete; > Phase 03 remains in progress. Packet closeouts below own the delivered scope. > P03-3/P03-4 final-head B/original-archive follow-ups and P03-6/P03-7 opposite-layout > A/pair qualification remain open before phase exit; merge waives none (P03-7 merged in @@ -21,9 +21,9 @@ > [ADR-0101](../decisions/0101-platform-operator-authority.md) to > [ADR-0104](../decisions/0104-controlled-issuer-rebind.md), ADR-0099 Amendments 10–13 and > ADR-0044 Amendment 18, with final-head layout A only. The layout-B filter ceiling it met is -> [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), carried by -> [PR #47](https://github.com/HodeTech/LearnStack/pull/47); B/pair qualification stays open -> before P03-11 exit. No manual UI evidence is owed. G13 and G14 are closed as Accepted; G20 +> [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), merged in +> [PR #47](https://github.com/HodeTech/LearnStack/pull/47) and [qualified in both layouts](phase-03-delivery-log.md#adr-0105-merge-and-hosted-qualification-2026-11-22) +> on its own source; the P03-9 B/pair gap stays open before P03-11 exit. No manual UI evidence is owed. G13 and G14 are 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 | Complete and merged — [closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21); final-head opposite-layout/pair qualification remains open (the layout-B filter ceiling is [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md)); the maintainer items, the P03-10 and Phase 11 constraint and the tooling note are owned in the closeout | +> | P03-9 | Platform authority and operational recovery | Complete and merged — [closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21); final-head opposite-layout/pair qualification remains open (the layout-B filter ceiling was raised by [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), [qualified](phase-03-delivery-log.md#adr-0105-merge-and-hosted-qualification-2026-11-22)); the maintainer items, the P03-10 and Phase 11 constraint and the tooling note are owned in the closeout | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | From e4b9c0c78ea74d5e3087621debd39e56d5dc8785 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 04:02:54 +0300 Subject: [PATCH 03/61] docs(decisions): accept the P03-10 data-request package ADR-0106 to ADR-0108 close G15 and the G16 workflow after the maintainer's questions and seven independent reviews; dated amendments in eleven ADRs, an erratum in Standard 05 and corrections in Data Protection, Audit and the phase text carry the changes. The step plan and the dispositions are in the Phase 03 delivery log. ADR: 0106, 0107, 0108 Co-Authored-By: Claude Sonnet 5.5 --- docs/architecture/23-data-protection.md | 51 +- docs/architecture/31-audit-subsystem.md | 45 +- .../0010-cross-module-communication.md | 4 + docs/decisions/0016-audit-log-subsystem.md | 4 + ...-cross-cutting-port-and-event-contracts.md | 4 + docs/decisions/0044-audit-write-path.md | 4 + ...046-durable-event-delivery-and-recovery.md | 4 + ...72-application-owned-identity-bootstrap.md | 4 + ...evision-pinned-membership-custom-fields.md | 4 + .../0099-confined-tenant-federation.md | 4 + .../0101-platform-operator-authority.md | 4 + .../0102-production-tenant-onboarding.md | 4 + ...-operator-recovery-of-asynchronous-work.md | 4 + ...ject-data-requests-authority-and-status.md | 236 +++++++++ ...request-fulfillment-and-account-closure.md | 469 ++++++++++++++++++ .../0108-privileged-audit-redaction.md | 202 ++++++++ docs/decisions/README.md | 3 + docs/glossary.md | 6 + docs/modules/audit/README.md | 5 +- docs/modules/audit/permissions.md | 4 +- docs/roadmap/phase-02a-kernel-tenancy.md | 3 +- docs/roadmap/phase-03-delivery-log.md | 75 +++ docs/roadmap/phase-03-identity-admin.md | 25 +- docs/standards/05-database.md | 11 +- 24 files changed, 1123 insertions(+), 56 deletions(-) create mode 100644 docs/decisions/0106-subject-data-requests-authority-and-status.md create mode 100644 docs/decisions/0107-data-request-fulfillment-and-account-closure.md create mode 100644 docs/decisions/0108-privileged-audit-redaction.md diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 201da2e4..1d26036b 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -123,10 +123,14 @@ The capabilities below are the engineering primitives. The tenant-facing data-pr Both KVKK Madde 11 ("kişisel verileri elde etme") and GDPR Article 15 require giving the user their data. -- The user (or the tenant admin on their behalf) requests an export. -- The platform emits a `DataExportRequestedV1` integration event. -- Each module exports its data for that user into a structured JSON bundle. -- The bundle is delivered as a downloadable file with a signed URL; expires in 7 days. +- The user (or the tenant admin on their behalf) requests an export, bound to one scope + group ([ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md)). +- A transactional job runs each module's `IUserDataParticipant` for that user into one + structured JSON bundle; no integration event carries the request + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 1). +- The bundle is an encrypted private artifact, retrievable only by the subject through a + 15-minute ticketed download in their live session, readable for 7 days after completion + and revocable (ADR-0107 § 4); no URL is a bearer credential. - Exports include: identity, memberships, profiles, enrollments, progress, attempts, bookings, attendance, recordings (metadata + signed download links), audit entries where the user is the actor. - Exports exclude: another user's data, tenant-internal admin notes about the user, internal system identifiers that have no meaning outside LearnStack. @@ -163,8 +167,11 @@ Both regimes recognise exceptions (legal obligation, contract performance). Lear Per category: -- PII-Identity → anonymisation (`name = "deleted user"`, `email = "deleted_@learnstack.invalid"`). -- PII-Behaviour → anonymisation (progress / attempts retained for cohort statistics; actor field is replaced). +- PII-Identity → the contextual profile (display name, locale, custom values) is cleared; the + Membership stays as a Revoked pseudonymised tombstone and the global `users` row is + untouched (ADR-0107 § 5). The model carries no `name` or `email` field to replace. +- PII-Behaviour → anonymisation (progress / attempts retained for cohort statistics); the + immutable actor identifier is retained and reported, never called anonymous. - PII-Sensitive → hard delete (recordings deleted from storage; metadata anonymised). - Payment → retained for legal period; user notified of the exception. - Audit → redact the six permitted human-facing columns; retain the action record. @@ -178,10 +185,14 @@ separated by authority. Conflating them lets a tenant admin close a person's acc **Tenant-scoped erasure.** Initiated by a tenant admin, or by the person acting inside that tenant. -1. Eligibility is validated (no active payment dispute, no legal hold). -2. The `Membership` and its `MembershipProfile` are removed. +1. Eligibility is validated (the structural checks and the hold port of ADR-0106 § 7; no + payment or hold source exists until Phase 09). +2. The group's role assignments are removed, the `MembershipProfile` is cleared and the + `Membership` becomes a Revoked pseudonymised tombstone (ADR-0107 § 5). 3. That tenant's behaviour rows are anonymised; its audit entries keep the action - record, with redaction subject to the [first-writer prerequisites](#erasure-authority-and-first-writer-prerequisites). + record, with the six permitted columns redacted by an operator act + ([ADR-0108](../decisions/0108-privileged-audit-redaction.md)) and the surviving + references reported. 4. This flow preserves the [permanent global binding/tombstone](#identity-foundation-and-classification-ownership). Nothing in this flow touches Keycloak. @@ -200,15 +211,19 @@ requesting person, any required approver, service actor and privileged executor. The participant inventory/write fence must reconcile new memberships, pending invites and delayed mirrors so completed closure cannot recreate account data. -1. The platform admin enters scope through the audited `EnterPlatformAdminScope(reason)` - — the only path that reads across tenants. -2. Eligibility is validated (no active payment dispute, no legal hold). -3. `UserAnonymisationRequestedV1` fans out to every tenant the person belongs to. -4. Each module consumes the event and performs its part: anonymise rows, delete storage - objects. **The Keycloak user is invalidated once, at the end, by the platform-scoped - step — never by a module reacting to a tenant-scoped request.** -5. A final reconciliation job confirms every module reported completion within 30 days. - Failures escalate to platform admin. +1. After the 24-hour window, a platform operator, who has confirmed the request with the + person, runs the audited Begin act under [ADR-0101](../decisions/0101-platform-operator-authority.md): + it takes the User fence and every participant tenant fence, checks eligibility and the + last-administrator rule, and moves the User to Closing, which is irreversible. +2. A per-group fan-out creates each participant group's erasure request and job in that + group's own transaction; there is no integration event. +3. Each group erases as in the tenant-scoped flow and waits for the privileged step. +4. The operator's Finalize act redacts the audit rows, deletes the Keycloak user once at + the end — never a module reacting to a tenant-scoped request — and sets the User + Closed, removing the raw provider subject and keeping the key and actor tombstone + (ADR-0107 § 7). +5. The operator inspection lists overdue requests; a request not completed within 30 days + is a defect escalated by the runbook. ### Durable asynchronous store inventory diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index ab3680f7..7b70d88c 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -1690,30 +1690,33 @@ declared job name is not proof of deletion or production capacity. ## 10. GDPR / PII redaction -When a user is GDPR-erased (`UserGdprDeletedIntegrationEvent` published), audit rows -containing that user's PII are **redacted in place** (not deleted — the audit row's -existence must remain auditable): +When a person's data is erased or their account is closed, audit rows containing that +person's PII are **redacted in place** (not deleted — the audit row's existence must remain +auditable). No `UserGdprDeletedIntegrationEvent` carries the request; the redaction is an +operator act ([ADR-0108](../decisions/0108-privileged-audit-redaction.md)): Redaction is one of exactly **two** sanctioned mutations of `audit_log` (the other is the retention purge, § 9). It is not an exception carved out of the append-only rule by convention — it is the shape the `audit_log_append_only_guard` trigger in § 7 was written to permit, and nothing else. -**Phase 03 target; no privileged consumer is shipped.** ADR-0046 requires a -separate privileged execution contract before this consumer can become Active. -P02b-3's ordinary app-role executor refuses privileged subscriptions. Its shared -inbox cannot atomically complete a platform-role transaction on another connection. -The former handler-owned inbox sketch is superseded as the current target. - -Phase 03 uses audited `EnterPlatformAdminScope(reason)` and specifies bounded -result-audit access before the handler ships. Scope entry commits its own audit -before work; the redaction and its MUST result audit then share the platform -working transaction. Per-module `IUserReferenceLocator` implementations redact -only declared payload references through that same handle. Idempotent progress -and durable event reconciliation prevent duplicate result audits after a crash; -no two-connection atomicity or external exactly-once effect is promised. The -ordinary event-terminal fifth seam authorizes no privileged redaction caller. -Phase 11 owns retention purge, not redaction. +**Phase 03 decision, Accepted; implementation is P03-10.** No privileged subscription is +registered: ADR-0046's ordinary app-role executor keeps refusing them, and its shared inbox +cannot atomically complete a platform-role transaction on another connection. The privileged +half is a human-operator act on the platform scope under +[ADR-0101](../decisions/0101-platform-operator-authority.md), with the platform operation +`complete_erasure` (audit slug `audit.redaction.apply`) and, for a closure, the Finalize act. + +Scope entry commits its own audit before work. One Audit-owned executor behind the +SharedKernel port `IAuditRedactor`, reached through one method of the scope handle bound to +those operations, redacts the six granted columns; the facade rule that platform scope SQL +cannot name `audit_log` stays. Per-module `IUserReferenceLocator` implementations only +*declare* where person references live (entity type, property, kind); they run no SQL. The +redaction, the request's status change and the witness-bound result row share one platform +transaction, and a closure's Finalize uses the intent checkpoint of ADR-0044 Amendment 18, +so a crash cannot duplicate a result row. No two-connection atomicity or external +exactly-once effect is promised, and no new `IAuditStore` method exists. Phase 11 owns +retention purge, not redaction. `actor_user_id`, `module`, `operation`, `operation_type`, `operation_class`, `outcome`, `correlation_id` and `timestamp` are **never** redacted; the trigger rejects an `UPDATE` @@ -1912,7 +1915,7 @@ for MUST-class would lock in exactly the defect ADR-0033 removes. | P02b-1 Steps 1–3 | Common audit/transaction coordinators, capture-owned audit frames, producer ancestry/receipts and no-listener trace groundwork; Steps 2–3 deliver immediate outbox enqueue, successful-save collection/promotion and owner-only domain drain. Hosted dispatch is implemented in P02b-2 Step 3; P02b-3 implements consumer delivery/inbox. | | P02b-2 Steps 1–4 | Schema/grants and confined producer transitions with MUST audit through the row-bound fifth seam; real-role atomicity/identity proofs. Steps 1–2 completed both review rounds. Step 3 implements hosted dispatch and observation, with both independent review rounds complete; Step 4 enforcement and local closeout are complete; all four steps completed both independent review rounds. The [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-2-merge-and-closeout-2026-10-13) owns CI/merge status. | | P02b-3 Steps 1–6 | Shared transport-owned inbox and retained delivery envelopes, durable acceptance, per-subscription audit frames and fenced business completion; independent scheduling/replay and Tenancy-owned subscriber terminal audit through the row-bound fifth seam. Ordinary executor refuses privileged subscriptions. Both real default subscriptions are Active with nested initializer MUST audits and semantic Seeder handoff; Step 6 extends classification to each concrete integration handler, with actual API/Seeder catalogue and missing-Off controls. P02b-3 is complete and merged through PR #31; its [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-3-merge-and-closeout-2026-10-15) owns final verification. | -| [03](../roadmap/phase-03-identity-admin.md) | Admin API endpoints over the audit stream; `UserGdprDeletedIntegrationEventHandler` + per-module `IUserReferenceLocator`. | +| [03](../roadmap/phase-03-identity-admin.md) | Admin API endpoints over the audit stream; the privileged redaction executor behind `IAuditRedactor` and per-module `IUserReferenceLocator` declarations ([ADR-0108](../decisions/0108-privileged-audit-redaction.md)). | | [06](../roadmap/phase-06-renderer-admin-studio.md) | Admin Studio audit UI: timeline view, filters, diff viewer, CSV / JSON export. | | [09](../roadmap/phase-09-billing-integrations-analytics.md) | Hub-side `hub_audit_log` + cross-stream correlation query. | | [11](../roadmap/phase-11-production-hardening.md) | **Scale, not correctness**, and nothing in [ADR-0028](../decisions/0028-audit-log-partition-management.md) is executed by the Packet 9 migration ([its 2026-09-07 amendment](../decisions/0028-audit-log-partition-management.md)): `PARTITION BY RANGE (timestamp)` plus monthly partitions, the daily partition-management job, the daily retention purge, off-archive policy for partitions older than a year, per-tenant retention enforcement under plan limits. Trigger: measured `audit_log` growth ([ADR-0035](../decisions/0035-demand-gated-infrastructure.md)). | @@ -1935,8 +1938,8 @@ for MUST-class would lock in exactly the defect ADR-0033 removes. (standard). - [15-event-and-outbox.md](15-event-and-outbox.md) — audit fan-out to external sinks rides the outbox; MUST-class audit does not. -- [29-dapr-integration.md](29-dapr-integration.md) — `UserGdprDeletedIntegrationEvent` - transport. +- [29-dapr-integration.md](29-dapr-integration.md) — transport; no `UserGdprDeletedIntegrationEvent` + is introduced ([ADR-0108](../decisions/0108-privileged-audit-redaction.md)). ### Native logout notification evidence diff --git a/docs/decisions/0010-cross-module-communication.md b/docs/decisions/0010-cross-module-communication.md index 87a6729d..82a73668 100644 --- a/docs/decisions/0010-cross-module-communication.md +++ b/docs/decisions/0010-cross-module-communication.md @@ -201,3 +201,7 @@ remain forbidden. The central audit store remains the row writer. Joint ADR-0072/0073 approval accepts this authority, not its implementation. P03-1 Step 3 must prove the exact installer, function bodies, table references, grants and call sites, with controls that detect widening. + +## Amendment 6 — Foundation-port registrations are not module-to-module communication (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) collect per-module implementations of a SharedKernel port (`IUserDataParticipant`) at the composition root, as `IAuditCatalogSource` and `IOperationPolicySource` already are. A registration of that kind is not a call from one module to another: no module references another module's code or participant type, and an architecture rule pins that. The four mechanisms stay four and no fifth is introduced. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0016-audit-log-subsystem.md b/docs/decisions/0016-audit-log-subsystem.md index dda46079..940b2237 100644 --- a/docs/decisions/0016-audit-log-subsystem.md +++ b/docs/decisions/0016-audit-log-subsystem.md @@ -406,3 +406,7 @@ The audit-coverage standard already treats `platform-admin` as MUST; no MUST/SHO tier change. Architecture test `OperationType_Enum_Matches_Catalog` is added to assert the enum members match the OperationType list in [18-audit-coverage.md § Operation Types](../standards/18-audit-coverage.md). + +### 2026-11-22 — Erasure redaction path; no `UserGdprDeletedIntegrationEvent` + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) settle the redaction this record sketches. No `UserGdprDeletedIntegrationEvent` or handler is introduced: the privileged redaction is an operator act on the platform scope through one Audit-owned executor and module `IUserReferenceLocator` declarations, and the result is reported with the rows and references that survive. Where this record names the event or a handler consuming it, read the operator act of ADR-0108. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0038-cross-cutting-port-and-event-contracts.md b/docs/decisions/0038-cross-cutting-port-and-event-contracts.md index 6299d71f..d81b9e27 100644 --- a/docs/decisions/0038-cross-cutting-port-and-event-contracts.md +++ b/docs/decisions/0038-cross-cutting-port-and-event-contracts.md @@ -263,6 +263,10 @@ The [Step 6 record](../roadmap/phase-02b-delivery-log.md#p02b-3-step-6--producti owns runtime proofs, bounded production censuses and current review/PR status. Original acceptance metadata, body and previous amendments are unchanged. +### Amendment 5 — An erased actor is a pseudonymous, linkable identifier (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) keep the permanent key and actor tombstone of [ADR-0072](0072-application-owned-identity-bootstrap.md) and the immutable `actor_user_id` and `metadata` of audit rows. The statement above that an erased user's audit actor is "an orphan surrogate key with no path back to a natural person" is therefore false: the retained identifier stays linkable through the subject key and is pseudonymous, not anonymous, and an erasure reports it as retained. The Decision, Status, Date and every other section of this record are unchanged. + ## References - [ADR-0006 — Events and Outbox](0006-events-and-outbox.md) diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index 256efc2c..0f20b626 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1363,3 +1363,7 @@ Amendment 11 records the implementation. 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 19 — Privileged audit redaction seam (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) add the redaction executor without a new store method. `IAuditStore` keeps its fifteen writes and `WritePlatformScopeAsync` its single entry-row caller. The Audit-owned executor sits behind the SharedKernel port `IAuditRedactor` and is reached through one new method on the platform scope handle, `RedactAuditAsync`, which refuses unless the scope's admission names `audit.redaction.apply` or the closure Finalize operation. The result is the witness-bound platform operator result write of Amendment 17, naming the real tenant for a single-tenant act and the sentinel tenant for the platform-wide Finalize row, and Finalize uses the intent checkpoint of Amendment 18. The redaction touches only the six granted columns and the append-only trigger is unchanged. § 9's statement that `organization_id` is the announcement's organization is what the redaction selection relies on. The Decision, Status, Date and every other section are unchanged. diff --git a/docs/decisions/0046-durable-event-delivery-and-recovery.md b/docs/decisions/0046-durable-event-delivery-and-recovery.md index 6edc825c..f55504f7 100644 --- a/docs/decisions/0046-durable-event-delivery-and-recovery.md +++ b/docs/decisions/0046-durable-event-delivery-and-recovery.md @@ -538,6 +538,10 @@ 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. +### Amendment 6 — The privileged erasure consumer is an operator act (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) answer the privileged execution contract this record requires before an erasure consumer can become Active: no privileged subscription is registered. The privileged half of an erasure is an operator act on the platform scope under [ADR-0101](0101-platform-operator-authority.md), and the ordinary event executor keeps refusing privileged subscriptions. Erasure never rewrites or deletes an outbox, delivery or inbox row, and the replay floor is stated in [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) § 9. The Decision, Status, Date and every other section of this record are unchanged. + ## References - [ADR-0006](0006-events-and-outbox.md), [ADR-0010](0010-cross-module-communication.md) diff --git a/docs/decisions/0072-application-owned-identity-bootstrap.md b/docs/decisions/0072-application-owned-identity-bootstrap.md index 56b77368..df7b3590 100644 --- a/docs/decisions/0072-application-owned-identity-bootstrap.md +++ b/docs/decisions/0072-application-owned-identity-bootstrap.md @@ -412,3 +412,7 @@ 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. + +### Amendment 8 — Closure writer, fence meaning and Closing irreversibility (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) name the separately admitted closure owner this record defers to P03-10. The platform session, as a human-operator act, moves a User Active to Closing and Closing to Closed by a direct UPDATE of `status` and `provider_subject` only, under one trigger exception that requires the exclusive User fence and every participant tenant fence held on that connection; the `users` policy and the application role are unchanged. "Retaining the fences through completion" means through the transaction that makes the User nonadmitting. Closing is irreversible and Closed removes the raw provider subject while the key and actor tombstone stay. A closed key never reappears and closure refunds nothing, as before. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0095-revision-pinned-membership-custom-fields.md b/docs/decisions/0095-revision-pinned-membership-custom-fields.md index 46ddbad0..1f4234ae 100644 --- a/docs/decisions/0095-revision-pinned-membership-custom-fields.md +++ b/docs/decisions/0095-revision-pinned-membership-custom-fields.md @@ -743,3 +743,7 @@ unchanged. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +### Amendment 5 — Retained own scope for data requests (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) reuse the consent subject's retained own-scope model for data requests. The statement in the consent-only entry section above that no extra global reader, function or owner is introduced does not extend to them: they add the definer function `fn_identity_own_data_request_scopes`, one new `TenantContextOrigin` and a few native retained-entry operations, each with its own denied proof, and the function and setter censuses of Standard 05 grow by that function. The consent surface itself is unchanged, and P03-10 settles an admitted withdrawal concurrent with closure as retained revocation evidence that is reported. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index a76338a8..d632d701 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1304,3 +1304,7 @@ The Decision, Status, Date and prior amendments of this record are unchanged, ex 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. + +### Amendment 14 — Offboarding of the federation row and broker is Phase 11 data operations (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) assign the tenant offboarding this record routes to P03-10. Per-person erasure and closure leave `federation_connections` and its broker untouched and report the pseudonymous pending and test actor identifiers as `federation_actor_reference`. Whole-tenant deprovisioning, including the removal of the row and broker and a tenant archived or deleted with a live row, belongs to Phase 11 data operations, triggered by the first real tenant offboarding request. Until then Disable, Delete and the operator sweep apply, and the statements above that P03-10 removes the connection are superseded by this one. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0101-platform-operator-authority.md b/docs/decisions/0101-platform-operator-authority.md index 3650049d..04f775d2 100644 --- a/docs/decisions/0101-platform-operator-authority.md +++ b/docs/decisions/0101-platform-operator-authority.md @@ -298,6 +298,10 @@ the ticket is recorded on the sentinel-tenant audit rows, where § 9 puts it. Th stays for a future non-ticket explanation; nothing writes it. The Decision, Status, Date and every other section are unchanged. +### Amendment 2 — Data request keys and operations (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) add two non-assignable Platform keys to the closed set of § 5: `platform.data_request.read` (inspect requests awaiting an operator step) and `platform.data_request.write` (complete an erasure's privileged step, begin and finalize a global account closure, and the per-group fan-out act). The operations are closed registry entries of § 7 with audit slugs outside the `identity` module, as the operator result write requires, and the human-operator population of § 1 is unchanged: no service or machine operator acts for them. The Decision, Status, Date and every other section of this record are unchanged. + ## References - [ADR-0102](0102-production-tenant-onboarding.md), diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md index 06e134d7..b4ba41b0 100644 --- a/docs/decisions/0102-production-tenant-onboarding.md +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -368,6 +368,10 @@ sentence of theirs is stale. The Decision, Status, Date and every other section unchanged. Acceptance of the linked records is not proof that anything they decide is implemented. +### Amendment 2 — The confined announcement serves the closure fan-out act (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) reuse § 1's confined announcement for one more operator act: the per-group fan-out of a global account closure, which creates a group's erasure request and enqueues its job in that group's own transaction. The announcement is extended to carry the group's organization, because the Identity row policies admit a write of an organization-bound row only under that organization's announcement. No new setter is added, and the act is idempotent and resumable. The Decision, Status, Date and every other section of this record are unchanged. + ## References - [ADR-0101](0101-platform-operator-authority.md), diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md index 496bc6cd..b483a157 100644 --- a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -365,3 +365,7 @@ recovery. 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 2 — The replay floor after erasure (2026-11-22) + +Accepted [ADR-0106](0106-subject-data-requests-authority-and-status.md), [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](0108-privileged-audit-redaction.md) (the [P03-10 decision package](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)) define the replay floor § 9 asks of P03-10. Erasure never rewrites or deletes an outbox, delivery, inbox or job row; a replayed or reset delivery re-runs its handler under that handler's own subject rules, which refuse a Closing or Closed User but not a tenant-erased one; the recovery runbook states that erasure does not reset replay; and the step records prove both cases with an actual replay. The Active-tenant test of § 2 and § 3 stays. The Decision, Status, Date and every other section of this record are unchanged. diff --git a/docs/decisions/0106-subject-data-requests-authority-and-status.md b/docs/decisions/0106-subject-data-requests-authority-and-status.md new file mode 100644 index 00000000..14c5edf2 --- /dev/null +++ b/docs/decisions/0106-subject-data-requests-authority-and-status.md @@ -0,0 +1,236 @@ +# ADR-0106: Subject Data Requests: Authority, Scope and Status + +## Status + +Accepted — 2026-11-22, after the maintainer reviewed the drafts, four independent reviews of them and the corrections those reviews led to. The dated record is the [Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22). Acceptance closes gate G15 of +[Phase 03](../roadmap/phase-03-identity-admin.md#the-decision-register) and, with +[ADR-0107](0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108](0108-privileged-audit-redaction.md), is the P03-10 decision package. It +authorizes the code it describes and is not proof that anything is implemented. + +**Date:** 2026-11-22 +**Deciders:** @cemil + +The maintainer chose, on the questions the package put to them, the human-operator +privileged step, reuse of the existing `identity.membership.admin` key for administrator +requests, and a 24-hour cancellable window +([ADR-0107](0107-data-request-fulfillment-and-account-closure.md) carries the other +choices). + +## Decision Drivers + +- [Data Protection](../architecture/23-data-protection.md#rights-we-support) separates a + tenant-scoped request from global closure and says RLS is one boundary, not the + subject predicate. G15 asks who may request which person's data, in which scope, for + which recipient and purpose, and what status survives the loss of the Membership. +- No request, status, permission or surface exists. Every existing self-service operation + carries no assignable key. +- The pinned OpenAPI gate refuses every further assignable permission key (G20, + [ADR-0100](0100-p038-federation-contract-transition.md)). +- The row policies of `memberships`, `membership_profiles` and role assignments admit a + write only when the announced organization equals the row's (or both are absent); + `app.scope='tenant'` widens reads only. A job or act therefore writes the rows of one + organization, or of none, per transaction, and existing administration already refuses a + target whose organization differs from the context's. +- A learner needs a request and status path with no Studio rights, including after the + Membership is gone, and a Suspended person has no native session. +- Targets: an export within 7 days, a deletion within 30 days, failures escalated. + +## Considered Options + +1. **A request bound to one scope group, self plus administrator-on-behalf under the + existing membership-administration authority, with a retained own-scope path and no + delegate** (chosen). +2. **A request spanning every organization of a tenant** (rejected). It needs one + transaction to write rows under several organization announcements, or a new RLS + exception, which the policies forbid. +3. **A dedicated assignable `identity.data_request.admin` key** (rejected now). It needs a + registry release, a role migration, SDK and BFF changes and a G20 transition record, + and no tenant yet needs the roles separated. +4. **Self-service only, administrators acting through the platform operator** (rejected). + A tenant could not meet its controller duty without a platform operator. +5. **A delegate or representative authority** (rejected for this packet). It needs a + proof of the third party that no corpus document specifies. + +## Decision + +1. **Kinds.** A *data request* is `export`, `erasure` or `closure`. `export` and `erasure` + are described here; `closure` is global and described in + [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) § 7, and shares this + ADR's identity, status vocabulary, idempotency and audit rules. Distinct operation + names, routes and copy keep erasure and closure apart. +2. **Scope group.** A request is bound to one *scope group*: a tenant and either one + organization or none (tenant-wide), the group of the context in which it is filed. It + covers the subject's Membership in that group, of which a person has at most one + current row. A person with Memberships in several organizations files one request per + group, and the UI lists them from the person's contexts. +3. **Authority.** + + | Requester | May request | Scope | + |---|---|---| + | The person, through a live session | `export`, `erasure` for themselves; `closure` | The group of the session's context (for a closure, the originating group; the closure itself is global) | + | The person, through the retained own-scope path (§ 9) | The same | Any group where they hold or held a Membership or have a request | + | A holder of `identity.membership.admin` covering the group | `export` for a person with a Membership of any status in the group; `erasure` only for a Membership that is already Revoked | That group | + + A Tenant-scoped holder covers every group of their tenant, an Organization-scoped + holder only their organization's group. An administrator erases the data of an Active + or Suspended member only after revoking that Membership, an existing and separately + audited act, so no administrator destroys a working member's data in one step; the + Revoked target needs its own target authorization, because the membership + administration authorization refuses Revoked targets. An administrator never creates a + `closure`, never reads a closure request, and a Platform operator creates no tenant + request. No + delegate, guardian or representative authority exists; naming it needs its own decision, + its owning phase is Phase 06 and the trigger is the first tenant that requires it. +4. **Permissions.** Self operations carry no key and use two new policy kinds, + `OwnDataRequest` (an Active Membership in the announced context) and + `OwnDataRequestEntry` (the retained own scope, which also serves a Suspended person). + Administrator operations are `Protected` with the existing alternatives + `[identity.membership.admin at Tenant, at Organization]`. **No assignable key is added + and the grant union's bytes do not change, so G20 is not triggered and stays Open.** A + dedicated key is the next decision when a tenant needs a data-protection role distinct + from membership administration; the owning phase is Phase 06. +5. **Subject predicate and third parties.** Every participant selects rows by the subject's + `UserId` and the request's group inside the tenant's `ITenantContext` as + `learnstack_app`. A row that names another person as a different party is included + only with that reference replaced by the literal `third_party`, and a field that holds + another person's data (an invitee's address on an invitation the subject issued) is + omitted. A same-tenant second person, another organization's rows and tenant-internal + notes never appear. PII category is never disclosure authority. +6. **Recipient and purpose.** The recipient of an export is always the subject, for data + subject access (GDPR Art. 15, KVKK Madde 11). An administrator who requests one sees + its status and counts and never its content; the artifact is retrievable only through + the subject's own surface ([ADR-0107](0107-data-request-fulfillment-and-account-closure.md) + § 4). +7. **Eligibility, holds and refusals.** A closed port `IDataRequestEligibility` decides at + creation and again at execution. Its default implementation checks structure: the + subject holds a Membership of any status in the group (a Revoked tombstone counts; on + the retained path, held one or has a request there); no non-terminal request of the same + kind, subject and group exists, which a partial unique index on the non-terminal rows + enforces so two concurrent creations cannot both pass (the answer is 409 + `business_rule_violation` with the `lockey_request_already_active` message, shown only to + a requester the group's scope covers); and an `erasure` is refused when the subject is + the only eligible tenant-wide administrator. A second port `IDataRequestHoldSource` has the + default `NoHoldSource`; its owning phase is Phase 09 (payments and disputes) and its + trigger the first aggregate that can carry a hold. A refusal at creation is a response + (`blocked_last_administrator`, `blocked_hold`) and writes no request; the status + `blocked` is reserved for a request that reached execution and failed its re-check. The + hold check also runs at a closure's Begin. A refusal that leaves a scheduled request in + place records its closed code in the request's `last_refusal`, which the receipt shows + so the person can act on it. +8. **Status and transitions.** The closed statuses and their only transitions are: + + | Kind | Path | + |---|---| + | `export` | `requested` → `fulfilling` → `completed`; `fulfilling` → `failed`; `requested` → `cancelled` | + | `erasure` | `scheduled` → `fulfilling` → `awaiting_privileged_step` → `completed`; `scheduled` → `cancelled`; `fulfilling` → `blocked` or `failed` | + | `closure` | `scheduled` → `fulfilling` (Begin) → `completed` (Finalize); `scheduled` → `cancelled` until Begin commits | + + A closure has no stored `awaiting_privileged_step`: the participant groups are other + tenants' rows, so Finalize's precondition and the operator inspection read them. A + fan-out erasure of a closure starts `fulfilling` at once, has no window and cannot be + cancelled, because closure is irreversible once Begin commits. An export finishes once + it is `fulfilling` and its artifact is then revoked if an erasure began; it is not + cancelled mid-run. Every terminal status (`completed`, `blocked`, `failed`, + `cancelled`) frees the one-active slot, so a failed request is recovered by filing a + new one. `failed` is read from the job phase (a quarantined or dead-lettered job), as + the invitation status reader does, so no hook runs in a dead job; the one-active check + and the receipt use the same reader. A request holds an immutable snapshot of the + subject and group, so removing the Membership strands neither pending work nor its + status. `completed` means every step, including the privileged one, finished; the + receipt never says it earlier. +9. **Retained own scope.** A person reads and files requests after their Membership is + gone, and a Suspended person does so at all, through a path modelled on the consent + subject of [ADR-0095](0095-revision-pinned-membership-custom-fields.md): a new definer + function `fn_identity_own_data_request_scopes` finds the groups where the subject has + any Membership or any request, with the same confinement, grants and quota rules as + the consent function; a new `TenantContextOrigin` admits the resulting tenant context; + and the closed native retained-entry set grows by the operations list, create, read, + cancel, ticket and chunk. ADR-0095's statement in its consent-only entry section that no + extra global reader, function or owner is introduced receives a dated Amendment 5, and + the function and setter censuses of Standard 05 grow by this function. The function + reads `data_subject_requests` and `memberships` through owner arms added for it alone, + as the consent function reads its table through one, and the step record states each + arm. The status receipt holds only the request identity, kind, status, timestamps, + `last_refusal` and the closed retained-reference kinds of ADR-0107 § 6; it holds no + personal data beyond the subject identifier the request row itself carries. +10. **Idempotency and transport.** Creation requires an `Idempotency-Key` and answers 202 + with the request resource and its `ETag`; every later mutation requires `If-Match` + ([ADR-0037](0037-idempotency-key-contract.md), + [ADR-0079](0079-bounded-identity-administration.md)). OpenAPI and the SDK change only + by additions. +11. **Cancellation window.** An `erasure` and a `closure` start `scheduled` with an + execution time 24 hours after creation, except a closure's fan-out erasure (§ 8). The + requester or the subject cancels until then, and a closure until its Begin commits. An + `export` has no window; its download ticket's lifetime is a separate, shorter limit. +12. **Targets and escalation.** An export is ready within minutes and always within 7 + days; an erasure or closure not `completed` after 30 days is a defect. The operator + inspection of [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) § 8 + lists requests awaiting an operator step, overdue `scheduled` closures and stuck + `fulfilling` requests, and the runbook names the escalation. +13. **Audit.** Every creation, cancellation, completion, administrator status read and + artifact retrieval is a MUST-class operation committed with its state change + ([ADR-0033](0033-audit-durability-model.md)); a read of another person's request is + `read-sensitive` and refuses on audit failure. The Step 1 record fixes the operation + names and registers them in the Identity audit matrix. + +## Context + +- **Why the group is the unit.** The policies that protect organizations also decide what + one transaction may write, so a request that spans organizations would need a new RLS + exception. A request per group keeps every write under the context that owns it, at the + cost of one filing per organization for a person in several. +- **Why no delegate.** A guardian changes who may receive personal data and nothing in + the corpus defines how that party is proven. Refusing it is safe and cheap to widen. +- **Why reuse `identity.membership.admin`.** The holder can already revoke and read a + member; a request is not a wider capability over the same person. A separate key costs + a G20 transition and a registry release this packet does not need. +- **What was not decided here.** The right to restriction and the right to object stay as + [Data Protection](../architecture/23-data-protection.md#right-to-restriction-of-processing) + states them with no mechanism; the owning phase is Phase 08a (the first notification + writer) and Phase 09 for analytics ingestion. Marketplace purposes stay outside Phase 03 + ([ADR-0049](0049-institution-sites-and-course-marketplace.md) is Proposed). + +## Consequences + +### Positive + +- A learner exports or erases their own data in a group with no administrator, no new + key and no change to the row policies. +- Terminal states free the slot, so no request can block a person forever. +- No assignable key is added, so the pinned OpenAPI document changes only by additions. + +### Negative + +- A person in several organizations files once per organization. +- The retained own-scope path grows by several operations, each with its own denied proof. +- An administrator-created request reaches a subject who may not know of it; the subject + sees it on their own status page, and the audit row records the administrator. + +### Neutral + +- The group, not the tenant, is the unit of every tenant request and receipt; a closure is + the one global request and is filed in its originating group. + +## Implementation Notes + +- The tables, policies, grants, native operations and census updates land in the P03-10 + steps recorded in the Phase 03 delivery log. Each new tenant table follows the canonical + template in [Database Standards](../standards/05-database.md) and gets isolation tests + as `learnstack_app`. +- Rules that enforce this ADR: `Tenant_Scoped_Export_Contains_No_Foreign_Tenant_Rows` + (two-tenant person, a same-tenant second person and a foreign organization), + `Permission_Registry_Has_DeniedTest` for every administrator operation, and a census + that no assignable key and no grant-union byte changed. + +## References + +- [ADR-0033](0033-audit-durability-model.md), [ADR-0037](0037-idempotency-key-contract.md), + [ADR-0079](0079-bounded-identity-administration.md), + [ADR-0095](0095-revision-pinned-membership-custom-fields.md), + [ADR-0100](0100-p038-federation-contract-transition.md), + [ADR-0107](0107-data-request-fulfillment-and-account-closure.md), + [ADR-0108](0108-privileged-audit-redaction.md) +- [Data Protection](../architecture/23-data-protection.md), + [Identity module](../modules/identity/README.md), + [Phase 03](../roadmap/phase-03-identity-admin.md) diff --git a/docs/decisions/0107-data-request-fulfillment-and-account-closure.md b/docs/decisions/0107-data-request-fulfillment-and-account-closure.md new file mode 100644 index 00000000..12a19917 --- /dev/null +++ b/docs/decisions/0107-data-request-fulfillment-and-account-closure.md @@ -0,0 +1,469 @@ +# ADR-0107: Data Request Fulfillment and Global Account Closure + +## Status + +Accepted — 2026-11-22, after the maintainer reviewed the drafts, four independent reviews of them and the corrections those reviews led to. The dated record is the [Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22). Acceptance closes the workflow part +of gate G16 of [Phase 03](../roadmap/phase-03-identity-admin.md#the-decision-register) +(its shared fence part was Accepted earlier) and, with +[ADR-0106](0106-subject-data-requests-authority-and-status.md) and +[ADR-0108](0108-privileged-audit-redaction.md), is the P03-10 decision package. It +authorizes the code it describes and is not proof that anything is implemented. + +**Date:** 2026-11-22 +**Deciders:** @cemil + +The maintainer chose, on the questions the package put to them: a human operator for +the privileged step; an encrypted PostgreSQL artifact behind a port; anonymise-and-revoke +for the Membership; a 24-hour cancellable window; deletion of the Keycloak user; no +whole-tenant offboarding in this packet; and in-product status with no new notification. +The maintainer also confirmed that the application is in development and not in use, so +no backward compatibility is owed for the schema, grants or contracts this ADR changes. + +## Decision Drivers + +- G16 asks how exports, closure and privileged redaction finish durably: artifact + delivery, reauthorization, expiry, job and storage prerequisites, participant + inventory, the write fence, the last-membership case, provider finalization, exact + grants and order, and reconciliation. +- No object storage port or adapter exists, no download path exists, the native web + transport carries only JSON of at most 256 KiB in 10 seconds, and the only e-mail + carrier serves invitations. +- [ADR-0101](0101-platform-operator-authority.md) admits human operators only and refuses + job and external frames the platform scope; the platform scope facade refuses SQL that + names `audit_log`, writes one result row per scope, and refuses a row whose module is + `identity`. +- `users` refuses UPDATE and DELETE for every role by trigger. `memberships` refuses + DELETE for every role and the UPDATE of a Revoked row; the aggregate refuses profile + and assignment changes outside Active or Suspended; a Revoked Membership's profile cannot + change; invitations hold their recipient immutably and the aggregate refuses the system + actor; `membership_field_consents` is append-only. +- The row policies of the Identity tables carry no owner arm, and admit a write of an + organization-bound row only under that organization's announcement, so the unit of every + write is one scope group + ([ADR-0106](0106-subject-data-requests-authority-and-status.md) § 2). +- The identity fence contract orders a User fence before every affected exclusive Tenant + key ([ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0074](0074-membership-admission-under-ordered-locks.md)). +- Erasure must not claim more than it does: retained references are reported truthfully + ([Data Protection](../architecture/23-data-protection.md)). + +## Considered Options + +1. **Participant registrations inside the module boundary, transactional jobs per scope + group for the tenant side, human-operator acts for the privileged side, and + PostgreSQL custody for the artifact** (chosen). +2. **Fan-out by integration events** (`DataExportRequestedV1`, + `UserAnonymisationRequestedV1`) (rejected). Every consumer needs an inbox, a + subscription and replay semantics, and a global closure has no real tenant for the + ordinary outbox. The work is group-local and needs one transaction. +3. **An automatic confined database role for the privileged step** (rejected). It would + supersede ADR-0101's rule that no machine acts privileged and add a trigger exception + and a standing connection. +4. **A storage port and a SeaweedFS adapter now** (rejected). It pulls Phase 04's media + work forward and adds a provider SDK and its boundary rule for one artifact class. +5. **A single-part artifact of about 192 KiB** (rejected). An administrator's own audit + rows exceed it quickly, so the export would fail for the people who act most. +6. **Hard delete of the Membership and profile rows** (rejected). It needs a critical + DELETE exception on a table closed to every role, while the same person's identifier + survives in audit and in the global binding. +7. **Hold every tenant key in one operator transaction through the whole closure** + (rejected). The per-group erasure runs as the application role and needs those keys. +8. **Definer functions for the closure participant list and the `users` transitions** + (rejected). The Identity tables have no owner arm and the `users` policy admits only + the application role, so a migration-owned function sees no rows and its UPDATE fails + the policy. The platform role bypasses row security, so column-limited grants and one + trigger exception are smaller and need no new policy arm. + +## Decision + +### 1. Participants + +LearnStack introduces no integration event for these workflows. A foundation port +`IUserDataParticipant` in `LearnStack.SharedKernel.DataProtection` is implemented by each +applicable module (`Export`, `Erase`, `DescribeRetained` for a subject and a scope group) +and collected by the composition root, as `IAuditCatalogSource` and `IOperationPolicySource` +are. These are registrations, not module-to-module calls: no module references another +module's code, so the four mechanisms of [ADR-0010](0010-cross-module-communication.md) +stay four, and ADR-0010 gains a dated clarification saying foundation-port registrations +are outside them. An architecture rule pins that no module references another module's +participant type. + +**One transaction per participant.** The job runs each participant's `Erase` in its own +transaction and records the participant's completion in the request's progress record +before the next, so no transaction writes two modules' tables +([Database Standards](../standards/05-database.md): no cross-module write transaction), and +a resumed job skips completed participants. Today only Identity writes; Tenancy +(membership consents), Customization (definition attribution) and Education (creator +attribution) describe retained references, and Audit's participant only describes and +plans because its work is privileged (ADR-0108). Content and Media are scaffolds with no +table. Any module that adds a table holding a person reference, Phase 04's media and Phase +07's learner behaviour included, registers a participant and a locator before its first +writer ships; `Every_PII_Module_RegistersUserReferenceLocator` becomes a census over every +module with a classified person reference, with a planted missing registration. + +### 2. Jobs + +Per scope group the module declares, under +[ADR-0047](0047-transactional-background-job-runtime.md), a `TenantWide` and an +`Organization` transactional definition for each of export, erasure and artifact purge +(`identity.data_export_*`, `identity.data_erasure_*`, `identity.data_export_purge_*`, +version 1), with identifier-only parameters. The request is created in the group's own +context, so it submits the job of the matching scope. They run as SystemActor with a +trusted job policy and never enter the platform scope. The erasure and the purge are +submitted with `ScheduleAsync` at their due time (the 24-hour window and the artifact +expiry), so no recurrence is introduced. The runtime has no cancel call, so a job whose +request was cancelled or revoked meanwhile completes as a recorded no-op. The production +job census tests change in the commit that registers a definition. + +### 3. Export bundle + +The bundle is one JSON document with a schema version, the request identity, the +generation time and one section per participant, for the request's group. + +- **Membership, profile and consents.** The Membership with status, organization, role + names and timestamps; the display name and locale; every custom-field value with its + definition revision, label and classification, including values withheld from ordinary + disclosure by a withdrawn consent (`None` is not an exclusion); and the consent history. +- **Invitations.** Those in which the person is the recipient or the acceptor, with their + own address and role; those the person issued, with the recipient address omitted (a third + party). +- **Audit.** The rows of the request's scope in which the person is the actor, or the entity + (an administrator's change to their Membership), as envelope fields (time, module, + operation, outcome, entity type) with the person's own `ip_address` and `user_agent`, and + the payload columns only for rows whose entity is the subject's own Membership, profile or + consent, with any other person's reference replaced by `third_party`. A self-requested + export selects these rows across the whole tenant, an administrator-requested one only + within the group, as ADR-0108 § 4 states for redaction. A self-requested export also lists + the person's own global identity events (their creation and failed attempts matched by the + subject key) as envelope fields. The section is capped at 8 MiB, newest first; a cap hit + is stated in the bundle (`truncated`, the rows included and the rows total) and in the + receipt. +- **Excluded.** Tenant settings, other people's data, internal administrator notes, + internal identifiers (including the `UserId`), the subject key, the raw provider subject + and every credential, verifier, ciphertext and key. + +### 4. Artifact custody, retrieval and expiry + +- A port `IDataExportArtifactStore` with the default `PostgresDataExportArtifactStore`. + The owning phase of an object-storage adapter is Phase 04 and the trigger is that phase + shipping `IStorageProvider`, or a measured need to exceed the ceiling below. +- The bundle is encrypted with AES-256-GCM, a fresh 12-byte nonce per chunk, from a key + ring in `ISecretProvider` (`DataExport:KeyRing`, one to four 32-byte keys with an active + version, like the invitation envelope; the web launcher allow-list carries the name). The + associated data binds format and key version, tenant, request, artifact, chunk index and + chunk count. A chunk holds at most 128 KiB of plaintext. The bundle ceiling is the + setting `DataExport:MaxBytes`, 16 MiB by default and 64 MiB at most; above it the request + ends `failed` with the closed reason `export_too_large`, which the 8 MiB audit cap makes + rare. A subject has at most one `available` artifact per group: a new export revokes the + previous one, which bounds the stored volume; a per-tenant quota is Phase 11's, triggered + by the first tenant storage limit. +- The artifact row has its own lifecycle `available`, `revoked`, `expired`, `purged`. It + expires 7 days after completion, so a request filed on the last allowed day is readable + for 7 more. Expiry is a time check: a read after `expires_at` is refused whether or not + the purge job ran, and the operator inspection lists expired artifacts not yet purged. The + delayed purge job deletes the chunk rows and keeps the metadata row as the receipt. The + subject or the requesting administrator may revoke an unexpired artifact, which purges it + at once. +- Retrieval is subject-only, through the live session or the retained own-scope path of + ADR-0106 § 9. A CSRF-protected POST mints a ticket valid 15 minutes, bound to the session + and the request and stored as a digest in `data_export_tickets`. It is a download cursor: + it authorizes the sequential chunk reads of one download, is marked consumed when the + final chunk is served, and a resumed or repeated download mints a new ticket. The API + decrypts each chunk and serves it as JSON (`index`, `count`, base64 `bytes`, at most 256 + KiB) that the BFF concatenates into one `attachment` response; no ciphertext leaves the + API and no URL is a bearer credential. Every ticket mint and every chunk read is a MUST + `read-sensitive` audit row, and an audit failure refuses the disclosure. The + reauthorization is this explicit ticketed act in the live session; no step-up + authentication claim exists for tenant sessions and none is made. +- This replaces the "signed URL" of Data Protection, which contradicted both + [Security](../standards/11-security.md)'s short-lived URL rule and the revocation + requirement. + +### 5. Tenant-scoped erasure + +The erasure job takes the canonical fences (the subject's exclusive User fence, then the +tenant key exclusively), re-runs the eligibility of ADR-0106 § 7, and in one transaction of +its group: + +1. revokes the group's unexpired export artifacts of the subject and cancels its not yet + started export requests (an export job re-reads the erasure state under the shared + tenant fence before it writes and discards its output if an erasure began); +2. erases the Membership with explicit domain operations, `RemoveAssignmentsForErasure`, + `ClearProfileForErasure` (display name and locale to NULL, custom values to `[]`) and + `RevokeForErasure`. They accept the system actor and any status, are idempotent, and run + only under the erasure witness, so a Suspended or an earlier-revoked Membership is + handled by the same path and the ordinary methods keep their rules; +3. revokes the pending invitations the person issued in the group through a domain + operation that takes the subject as the aggregate actor (the aggregate refuses the system + actor), while the audit actor stays the job's. + +The database accepts the profile clearing on a Membership of any status through one +exception in the contextual mutation guard: a clearing UPDATE of exactly those three profile +columns when the User fence and the tenant fence are held and an `erasure` request for that +subject and group in `fulfilling` exists. No other column, table or caller is widened. The +Membership row stays as a Revoked tombstone holding the pseudonymous `UserId`, organization, +status and the existing timestamps and actors; the phase text "removes the Membership and its +MembershipProfile" is corrected to say so. Tenant erasure never touches `users`, the +provider account or another group, and a person whose only Membership is erased keeps a +working global account with zero memberships. The request then moves to +`awaiting_privileged_step` and an operator completes it (§ 8). + +### 6. Per-store treatment and the retained report + +Every store that can carry the subject has one closed outcome, and the receipt reports the +closed kind, never a row identifier. The kinds are: `consent_evidence`, `invitation_record`, +`invitation_envelope`, `audit_actor_reference`, `audit_entity_reference`, +`audit_metadata_reference`, `unscoped_audit_rows`, `transport_evidence`, +`execution_evidence`, `provider_event_record`, `idempotency_cache`, +`attribution_reference`, `federation_actor_reference`, `request_receipt`, `external_copy` +and `unserved_group`. + +| Store | Outcome | +|---|---| +| `membership_profiles` (name, locale, custom values) | cleared (§ 5) | +| `membership_role_assignments` | deleted | +| `memberships` | pseudonymised tombstone: Revoked, `UserId` retained | +| `data_export_chunks` | purged at revocation, expiry or erasure | +| `data_export_artifacts`, `data_export_tickets`, `data_subject_requests` | retained as `request_receipt`, holding no personal data beyond the subject identifier; retention target and purge are Phase 11's | +| `membership_field_consents` | `consent_evidence`: append-only evidence of lawful basis; a withdrawal admitted concurrently appends and is reported | +| `invitations` the person issued, pending | revoked | +| `invitations` the person accepted, pending ones addressed to them, `invitation_email_envelopes`, `invitation_email_attempt_receipts` | `invitation_record` and `invitation_envelope`: retained as the record of an authority-granting offer; no erasure transition exists, a pending offer is not locatable by subject and envelope ciphertext is immutable; Phase 11 retention | +| `audit_log` | six columns redacted by the privileged step (ADR-0108); the rest `audit_actor_reference`, `audit_entity_reference` and `audit_metadata_reference` | +| `outbox_messages`, `event_deliveries`, `inbox_messages`, `background_*`, Hangfire tables | `transport_evidence` and `execution_evidence`: immutable; erasure proves no quiescence | +| `identity_provider_event_receipts`, `_targets`, `_problems`, `_scan` | `provider_event_record`: independent 32-day retirement; tenant targets reported | +| `idempotency_keys` | `idempotency_cache` until the existing 24-hour retention; no new purge authority | +| creator, updater and deleter attribution on every mapped aggregate | `attribution_reference`: pseudonymous `UserId` | +| `federation_connections` (pending and test actor identifiers) | `federation_actor_reference`: retained; the broker and the row are untouched by subject erasure, and closure leaves them because the tenant owns them | +| `users` | untouched by tenant erasure; see § 7 | +| Keycloak events, diagnostics, WAL, backups, SMTP copies, BFF sessions | `external_copy`: reported only; Phase 11 owns purge and reconciliation | +| Phase 07 and later learner behaviour, Phase 04 media | integrated by the first writer through § 1 | + +The retained outcomes are the truthful report of the request; none is called anonymous. The +recipient address of invitations the person accepted, and its encrypted envelope, is the +largest retained personal copy and stays until Phase 11 retention; acceptance of this ADR is +the maintainer's acceptance of that retention. The controller's own legal-basis review of +each retained class is owed per deployment and is not provided here. + +### 7. Global account closure + +- **Request.** Closure is a data request of kind `closure`, created by the person alone, + through a live session or the retained path of ADR-0106 § 9, in the originating group, + with the 24-hour window. The row lives in that originating tenant, no administrator + creates or reads it (the administrator operations exclude the kind), and no Platform + permission is involved. A person with no Membership has no tenant context and cannot file + a closure through this surface; they hold no tenant data, and the global-self extension for + them is owned by Phase 11 data operations and triggered by the first such request. The + surface warns before submission that the account will stop working and that no in-product + status will remain. +- **Approver.** The platform operator is the human approver. The runbook requires the + operator to confirm the request with the person through the e-mail the identity provider + holds, read in the realm console and never stored by LearnStack, before Begin; this is the + control a hijacked session cannot supply. +- **Participants.** The operator's service reads, on the platform connection through a + column-limited SELECT grant, every (tenant, organization-or-none) group in which the + person holds a Membership of any status, including a Revoked one whose profile may still + hold data, and reads each tenant's lifecycle through the existing Tenancy port + `IIdentityScopeLifecycleReader`, so no cross-module join exists. The set is read live and + stored in no tenant-readable table. +- **Begin.** An operator act in the platform scope (`PlatformScope` executor) takes the + subject's exclusive User fence and then every participant tenant key exclusively in + canonical order, on the platform connection, bounded by the scope's own wait (the step + record names the mechanism), using the same key derivation as `IIdentityMutationLocks`, + which is tenant-announced and single-tenant and cannot be used here; + `Identity_Membership_Invariants_Use_Fresh_Ordered_Locks` gains a separate census leg for + this acquirer. It refuses `blocked_window` before the request's execution time, + `blocked_hold` when a hold source reports one, and `blocked_last_administrator` when a + participant tenant that allows ordinary work would be left without another eligible + tenant-wide administrator (an Active User with an Active tenant-wide administrator + Membership); a tenant that does not allow ordinary work (not Trial or Active, per + ADR-0102's lifecycle) is not checked and does not block. A refusal leaves the request + `scheduled` with its `last_refusal`, so the person can act on it. Otherwise, in one + transaction, it moves the User Active to Closing, sets the closure request `fulfilling` + and writes the result row. The User move is a direct UPDATE by the platform role of + `status` and `provider_subject` only, under one trigger exception that requires the + platform session, the exclusive User fence and every participant tenant fence held on that + connection and permits only that transition. If the User is already Closing for another of + the person's closure requests, Begin resumes it instead. The fences are held through that + transaction, which is the nonadmitting transition they exist to order; Standard 05 and + Phase 03 G16 gain a dated erratum saying that "through completion" means this. The same + operator call then performs the fan-out. +- **Fan-out.** `fan_out_closure` is the per-group pipeline act `begin_closure` invokes, not + a separately routed endpoint. For each participant group, under ADR-0102's confined + announcement extended to announce the group's organization, it creates that group's + `erasure` request in the group's own transaction (origin closure, `fulfilling`, no + window, business actor SystemActor with the operator attribution in the audit metadata) + and enqueues its erasure job. An existing non-terminal erasure of the same subject and + group is adopted instead of conflicting; a terminal one that did not complete is replaced + by a new request. A repeated Begin call resumes every group lacking a completed or + in-flight request, and the fan-out erasure ends `awaiting_privileged_step`. +- **Closing is irreversible and cannot stick.** There is no path from Closing back to + Active, and a person cannot be resurrected by a delayed mirror, a pending invitation, a + new Membership, provider intake or delayed work, which all refuse a non-Active User by the + existing rules. Closure retries until it finishes: a group whose job failed is retried by + repeating Begin; a group whose tenant does not allow ordinary work is `unserved_group`. + Finalize may complete with unserved groups, which it must name; their data stays and is + reported, and Phase 11's offboarding owns them. +- **Finalize.** A second operator act, allowed when every participant group's request is + `awaiting_privileged_step` or `completed`, or its group is named `unserved_group`, runs in + two transactions. The first redacts the subject's audit rows in every participant tenant + and the platform sentinel tenant (ADR-0108) and writes the intent row that carries the + redaction counts. The Keycloak user is then deleted through `IIdentityProviderAccountRemoval` + (a missing user is success). The second transaction sets Closed, removes the raw provider + subject through the same column-limited UPDATE under the same trigger exception, keeps the + key and actor as the permanent tombstone, marks every participant request and every + non-terminal closure request of the subject `completed`, and writes the result row. A crash + between the steps is repaired by re-running the act, which is idempotent. +- **Provider port.** `IIdentityProviderAccountRemoval` is bound to + `IProviderResilience`, has the default implementation + `RefusingIdentityProviderAccountRemoval`, which fails closed, and a Keycloak adapter + selected at the composition root. The adapter's confined realm client holds `manage-users`; + that role also lets the client create and update users and reset credentials in the shared + realm, so a leaked secret reaches every tenant's users. The accepted mitigations are the + secret store, rotation by the runbook and the provider's own admin-event stream, whose + retention is Phase 11's. Fine-grained admin permissions are not relied on; if the pinned + Keycloak supports scoping the deletion, the adapter adopts it by a dated amendment. +- **Reach and status.** A Closing or Closed person's sessions fail at the next API + admission with the uniform 401; deleting the Keycloak user ends refresh, and an issued + access token grants nothing because binding admission fails. While Active the person + reads the request through their session; afterwards there is no in-product status, and the + operator confirms completion out of band from the retained closure request. A consent + withdrawal needs an admitted entry, so none follows closure; the consent evidence stays and + is reported. +- **No refund.** Closure refunds no creation budget or permanent allocation, and a Closed + key never reappears at issuer rebind. + +### 8. Principals, grants, operations and keys + +| Principal | Grant | +|---|---| +| `learnstack_app` | SELECT, INSERT and UPDATE of the status, `row_version`, progress and result columns on `data_subject_requests`; INSERT, SELECT and UPDATE of status on `data_export_artifacts`; INSERT, SELECT and UPDATE of the consumed marker on `data_export_tickets`; INSERT, SELECT and DELETE on `data_export_chunks`; EXECUTE on `fn_identity_own_data_request_scopes`; the profile clearing of § 5 under its witness | +| `learnstack_platform` | A closed-column SELECT on `memberships`, `users` and `data_subject_requests`; UPDATE of the status, `row_version`, completion time and result columns on `data_subject_requests`; UPDATE of `status` and `provider_subject` on `users` under the trigger exception of § 7; its existing six-column UPDATE on `audit_log`; no other privilege | +| Keycloak | One new realm client with `manage-users`, its secret in `ISecretProvider` | + +The one new definer function, `fn_identity_own_data_request_scopes`, reads +`data_subject_requests` and `memberships` through an owner arm added for it alone, the way +the consent function reads its table. Two non-assignable Platform keys are registered: +`platform.data_request.read` and `platform.data_request.write`. The platform operations are +closed registry entries. Read: `inspect` (a platform-scope read with an entry row, in the +style of [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) § 6, listing requests +awaiting an operator step, overdue `scheduled` closures, stuck `fulfilling` requests and +expired artifacts not yet purged). Write: `complete_erasure` (audit slug +`audit.redaction.apply`, ADR-0108), `begin_closure`, `fan_out_closure` (pipeline executor) +and `finalize_closure`. The Begin and Finalize rows use a non-`identity` module because the +operator result write refuses `identity` +([ADR-0044](0044-audit-write-path.md) Amendment 17) and carry the platform sentinel tenant; +each participant tenant's own fan-out request carries its tenant's MUST rows, which is the +"requested, recorded against every affected tenant" evidence. The step records fix the exact +slugs and spellings, and ADR-0101 (the key table) and ADR-0102 (the announcement) gain dated +amendments. An ordinary job, a dispatcher credential or a SystemActor holds none of this +authority. + +### 9. Transport stores and the replay floor + +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md) § 9 asked for a floor. It is: +erasure never rewrites or deletes an outbox, delivery, inbox or job row; a replayed or reset +delivery re-runs its handler under that handler's own subject rules, which refuse a Closing +or Closed User but not a tenant-erased one, whose User stays Active, so a replayed +subject-linked delivery may write rows for that person and is reported as retained transport +evidence; the recovery runbook states that erasure does not reset replay; and the step +records prove both cases with an actual replay. The Active-tenant test stays. + +### 10. Out of scope, with owners + +| Item | Owner and trigger | +|---|---| +| Whole-tenant deprovisioning, including the `federation_connections` row and broker of an archived tenant, and the data of an `unserved_group` | Phase 11 data operations; the first real tenant offboarding request. ADR-0099 gets a dated amendment saying so. | +| E-mail or other notification of a request | Phase 08a | +| Right to restriction | Phase 08a (notifications) and Phase 09 (analytics) | +| Terminated-host recovery for consent-only entry | Phase 11; the first terminated tenant host | +| Closure for a person with no Membership | Phase 11 data operations; the first such request | +| Audit-log read-API export files and their retention | Phase 06 (Studio audit screens); the first export writer | +| The Hub compliance cap `gdpr.hard_delete.enabled` | Governs hard delete of tenant content; anonymise-and-revoke uses none, and no consumer is added | + +## Context + +- **Why the privileged half is human.** ADR-0101 makes the operator a person with a + per-act permission and refuses jobs and external frames the platform scope. The + privileged half is small and rare, and a visible `awaiting_privileged_step` is honest + about the wait. An automatic role would be a standing principal on a table closed to + every role. +- **Why anonymise and revoke.** The identifier survives in audit and in `users` + regardless, so deleting the Membership row removes little. The aggregate already + transitions to Revoked, and the one new database exception is the narrowest that makes an + earlier-revoked person's profile erasable. +- **Why two operator acts for closure.** The fences must be held while the User becomes + nonadmitting and free while the per-group erasure runs as the application role. Begin and + Finalize separate those, and each is idempotent and resumable. +- **Why a sole administrator can be refused and an unserved tenant cannot.** A tenant that + allows ordinary work needs an administrator, so the person hands over first; the 30-day + target of ADR-0106 § 12 counts from when no refusal stands. A tenant that is suspended or + archived has no ordinary work to protect, so it must not hold a person's closure hostage; + its data stays, is reported, and has a named owner. +- **The recovery predicate.** The P03-9 closeout asked whether operator recovery needs a + user-eligibility-aware predicate. It does not: Begin refuses to leave an operable tenant + without another eligible administrator, and operator recovery can name a new + administrator for any other tenant. +- **What would change our minds.** A hold source, a delegate authority, an object-storage + adapter, a second administrator population or a real offboarding request each reopens the + part this ADR names, with the phase and trigger above. + +## Consequences + +### Positive + +- Every Accepted retained-reference promise is reported per request, not asserted. +- The widened database authority is the witnessed clearing, one `users` trigger exception + and column-limited platform grants; no new owner arm except the one retained-scope function. +- No new integration event, recurrence or notification sender is introduced. + +### Negative + +- Erasure and closure each wait for an operator for the privileged step. +- A person in several organizations files and tracks one request per group. +- The recipient address of invitations the person accepted remains until Phase 11. +- A sole administrator of an operable tenant cannot close until they hand over. +- A Closing person gets no in-product confirmation. +- The audit section of a very large export is capped and reports the cap. + +### Neutral + +- The Membership tombstone keeps a pseudonymous identifier, as audit and `users` do. + +## Implementation Notes + +- The step records name the exact slugs, keys, tables, migrations and function names and add + them to the module matrices, the permission matrix, the audit catalogue and the + architecture-test catalogue. +- New tables join the durable asynchronous store inventory or its exclusion list + (`Durable_Async_Store_Inventory_Covers_The_Storage_Census`) and the personal-data + classification census in the same commit. The function and setter censuses of Standard 05 + and ADR-0095 grow by `fn_identity_own_data_request_scopes`. +- The acceptance commit corrects the carriers that still describe the old design: Data + Protection (the `DataExportRequestedV1` and `UserAnonymisationRequestedV1` fan-out, the + removal of the Membership, the Keycloak invalidation, the final reconciliation job, the + `name`/`email` placeholders and the signed URL), the Phase 03 text and C18, the Identity + module spec, Audit Subsystem § 10 and ADR-0016's and ADR-0044's mentions of + `UserGdprDeletedIntegrationEvent`, and the glossary. +- Bulk changes use tracked aggregates, never `ExecuteUpdate`, `ExecuteDelete` or + `ExecuteSql*` (`No_Set_Based_Write_Bypasses_The_Audit_Capture`). + +## References + +- [ADR-0010](0010-cross-module-communication.md), + [ADR-0037](0037-idempotency-key-contract.md), + [ADR-0044](0044-audit-write-path.md), + [ADR-0047](0047-transactional-background-job-runtime.md), + [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0074](0074-membership-admission-under-ordered-locks.md), + [ADR-0079](0079-bounded-identity-administration.md), + [ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md), + [ADR-0099](0099-confined-tenant-federation.md), + [ADR-0101](0101-platform-operator-authority.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-0106](0106-subject-data-requests-authority-and-status.md), + [ADR-0108](0108-privileged-audit-redaction.md) +- [Data Protection](../architecture/23-data-protection.md), + [Database Standards](../standards/05-database.md), + [Phase 03](../roadmap/phase-03-identity-admin.md) diff --git a/docs/decisions/0108-privileged-audit-redaction.md b/docs/decisions/0108-privileged-audit-redaction.md new file mode 100644 index 00000000..8269acbb --- /dev/null +++ b/docs/decisions/0108-privileged-audit-redaction.md @@ -0,0 +1,202 @@ +# ADR-0108: Privileged Audit Redaction + +## Status + +Accepted — 2026-11-22, after the maintainer reviewed the drafts, four independent reviews of them and the corrections those reviews led to. The dated record is the [Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22). Acceptance settles the redaction +seam, the locator contract and the surviving-reference treatment that +[Phase 03](../roadmap/phase-03-identity-admin.md#the-decision-register) and +[ADR-0044](0044-audit-write-path.md) § 10 owe before the first redaction writer, and with +[ADR-0106](0106-subject-data-requests-authority-and-status.md) and +[ADR-0107](0107-data-request-fulfillment-and-account-closure.md) is the P03-10 decision +package. It authorizes the code it describes and is not proof that anything is +implemented. + +**Date:** 2026-11-22 +**Deciders:** @cemil + +## Decision Drivers + +- `audit_log` allows two mutations by one role: `learnstack_platform` may UPDATE six + columns (`actor_email`, `ip_address`, `user_agent`, `before_state`, `after_state`, + `changes`) and DELETE rows for the retention purge, and a trigger rejects every other + change. The facade rule below keeps the executor from using the DELETE. No redaction code, no + `IUserReferenceLocator` and no `audit.redaction.apply` operation exists. +- The platform scope facade refuses any SQL that names `audit_log`, the handle exposes no + connection, and a scope's result row is its last write. + [ADR-0101](0101-platform-operator-authority.md) admits human operators only and + refuses job and external frames, so a subscription consumer cannot be the executor. +- [ADR-0044](0044-audit-write-path.md) Amendments 17 and 18 already added witness-bound + result and intent writes, so the "one caller of `WritePlatformScopeAsync`" question + Phase 03 raised is answered without a new store method. +- `actor_user_id`, entity and causation identifiers, `correlation_id` and all of + `metadata` (which carries `causal_actor_user_id`, authorization Membership and Role + references and `identity_subject_key`) are outside the grant and the trigger. Redacting + six columns is not anonymisation. +- The corpus disagrees on what a locator does: Audit Subsystem § 10 has module locators + redact payload references, while Data Protection and Audit's own spec say locate and + report only. + +## Considered Options + +1. **An operator platform-scope act that calls one Audit-owned executor with fixed + statements, driven by module-declared locators, and reports what survives** (chosen). +2. **Widen the grant and the trigger to `metadata` and `actor_user_id`** (rejected). Both + are the attributable history that audit exists to keep, and the subject key is a + deliberate permanent tombstone; widening them would end the append-only guarantee for + the columns that make rows trustworthy. +3. **A new `IAuditStore` method for the redaction result** (rejected). The existing + witness-bound result write carries it, and a sixteenth method breaks the pinned + count for no gain. +4. **Let the facade accept SQL that names `audit_log`** (rejected). It would remove the + rule that keeps every other platform act from touching the log. +5. **A subscription consumer on a privileged delivery** (rejected). ADR-0046 says the + ordinary executor refuses privileged subscriptions and ADR-0101 refuses a machine + executor. + +## Decision + +1. **Executor.** The privileged half of an erasure request, and the redaction inside a + closure's finalize ([ADR-0107](0107-data-request-fulfillment-and-account-closure.md) + § 7), is an operator act in the platform scope. The standalone act is the registry + platform operation `complete_erasure` of ADR-0107 § 8, whose audit slug is + `audit.redaction.apply` (module `audit`), off the MediatR path, MUST and + `security-event`, under the non-assignable Platform key `platform.data_request.write`, + which settles the key Audit's permission spec names "pending". ADR-0101's key table + gains it by dated amendment, and the Audit matrix drops the `(planned)` marker. +2. **Seam.** An Audit-owned executor with fixed, parameterized statements lives in + `LearnStack.Infrastructure.Audit` behind a SharedKernel port `IAuditRedactor`, which the + platform scope resolves by dependency injection, so `LearnStack.Infrastructure` gains no + reference to the Audit infrastructure project. The scope handle exposes one new method, + `RedactAuditAsync(plan)`. The method is bound to the admitted operation: it refuses unless the scope's admission names `audit.redaction.apply` or the + closure Finalize operation, so no other platform-scope service can call it. The facade + rule that statements cannot name `audit_log` stays unchanged and tested. The executor's + file is the one sanctioned redaction site, added by exact path to the append-only + architecture test's allow-list. Modules never write `audit_log`. +3. **Result row.** The result is the existing witness-bound platform-scope result write. + `IAuditStore` keeps its fifteen writes and `WritePlatformScopeAsync` keeps its single + entry-row caller. The standalone act concerns one tenant, so its row names that real + tenant; the closure Finalize concerns several and writes one platform-wide row under the + sentinel tenant (ADR-0044 Amendment 17), whose report lists the tenant identifiers + (not personal data) and the per-tenant counts, while each tenant's own fan-out request + carries its tenant's MUST evidence. Rows carry `actor_user_id` NULL, the closed reason + slug, the correlation id and the operator attribution, and hold a closed report in + `after_state`: counts of rows redacted per column and counts of retained references per + kind, never a person identifier. +4. **Plan and selection.** The plan carries the tenant, the request's scope group, the + request's origin, the subject `UserId`, the request's frozen Membership identifiers and, + for a closure, the subject key. A row's `organization_id` is the announcement's + organization of the transaction that wrote it + ([ADR-0044](0044-audit-write-path.md) § 9), not the entity's, so the selection depends on + who asked. An erasure the person requested, and every participant tenant of a closure, + selects across the whole tenant. An erasure an administrator requested selects only rows + whose `organization_id` is the group's (a tenant-wide group selects rows with no + organization, an organization group only that organization's), so an organization + administrator never alters another branch's records. In either case a row is selected + when `actor_user_id` equals the subject, or `entity_id` equals the subject or a + Membership of the snapshot, or a locator-declared reference in `before_state`, + `after_state` or `changes` holds one of those identifiers. A closure's Finalize also runs + the selection over the platform sentinel tenant, by `metadata.identity_subject_key`, for + the subject's global creation and failed attempts. Rows the selection cannot reach are + reported as `unscoped_audit_rows`. +5. **What is redacted.** `ip_address`, `user_agent` and `actor_email` become NULL. + String values at declared pointers in the three JSON columns become + `SensitiveTokenCatalog.RedactedValue`, the one sentinel the capture already writes. The + statements are idempotent, touch only the six granted columns and refuse any other + change at the trigger as today. +6. **What survives and is reported.** `actor_user_id`, `entity_id`, causation and + correlation identifiers, `module`, `operation`, outcome, timestamps and all of + `metadata` are retained. Each request reports the retained kinds and counts under the + closed vocabulary of ADR-0107 § 6, together with the retention target of + [Audit Coverage](../standards/18-audit-coverage.md#retention) for the row's class, + which no code enforces yet (Phase 11 owns purge). The tombstone and the subject key + are never called anonymous. ADR-0038's statement that an erased actor is "an orphan + surrogate key with no path back to a natural person" is false once the subject key is + kept, and is corrected by amendment (as is the same sentence in Phase 02a) to say that the + retained identifier is pseudonymous and stays linkable through the subject key. +7. **Locators.** Each applicable module registers an `IUserReferenceLocator` that + declares, for its entities, the properties that hold a person or Membership reference + and the retained-linkage kinds it knows, as `(entityType, propertyName, referenceKind)`. + The paths of `changes` items are instance-qualified (`/{EntityType}/{EntityId}/...`, + [CapturedEntityChange](../../backend/src/LearnStack.SharedKernel/Audit/CapturedEntityChange.cs)), + so the executor matches a declaration by entity type and property name in `before_state` + and `after_state` (entity property maps) and by entity type and path suffix in `changes`, + and resolves the entity identifier from the row itself. The locator performs no SQL and + holds no privilege; the Audit executor applies the declarations. A census over the + existing personal-data classification requires every mapped property of person-reference + type (`UserId`, `MembershipId`) in an audited entity to be declared or listed as an + explicit retained reference, and each module's canary test embeds a reference at every + declared pointer, runs the redaction and asserts it is gone, so an omitted declaration + fails the build. This + reconciles Audit Subsystem § 10 (the module knows where its references are) with Data + Protection (the module never reaches `audit_log`). +8. **Idempotency and crash behaviour.** For `complete_erasure`, the redaction, the + request's status change and the result row commit in one platform transaction, so no + state exists in which one is recorded without the others. A closure's Finalize uses the + intent checkpoint of ADR-0044 Amendment 18: the first transaction redacts and writes the + intent row that carries the redaction counts, the provider call follows, and the second + transaction writes the Closed transition and the result row, so the redaction's MUST + evidence is the intent row in the transaction that did it. A re-run after the commit + finds the request `completed` and returns its recorded result with no second row; a + re-run after a rollback repeats statements that are idempotent. The closed report is + bounded: counts per kind and column, aggregated into totals beyond 200 groups so it stays + under the 32 KiB state limit. No inbox is involved, because the act is an HTTP operator + act and not a delivery. +9. **Grants.** No grant on `audit_log` and no change to the append-only trigger function + is made. The platform role's request-table privileges are those of ADR-0107 § 8. + +## Context + +- **Why not anonymise the retained columns.** `actor_user_id` is what lets a reviewer + answer who did something; replacing it makes the log unauditable, and the subject key is + kept deliberately to prevent recreation. The honest contract is redaction of what is + not needed to attribute an action, plus a truthful report of what remains. +- **Why one executor file.** The facade rule and the single sanctioned site make + "who can redact" a one-line census, which is the property the append-only test needs. +- **What would change our minds.** A retention policy that allows removing the attributable + columns, or a Phase 11 purge that deletes rows past their target, would change what + survives; neither is assumed. + +## Consequences + +### Positive + +- The redaction has one executor, one result row and one idempotency story, with no new + store method and no new grant on `audit_log`. +- Modules declare where their references live without gaining any audit access. + +### Negative + +- A person's identifier survives in audit and in `metadata` after erasure, and the status + says so. +- Each erasure waits for an operator act for the redaction. + +### Neutral + +- The retention targets are reported, not enforced, until Phase 11. + +## Implementation Notes + +- Step 2 adds the executor, the facade method, the operation, the locators and their + census, the runbook and the sanctioned-site entry, and updates the tests that pin them + (`AuditEntry_Is_AppendOnly`, the platform-scope convention census and a test that no + other operation can call `RedactAuditAsync`). `IAuditStore_Exposes_No_Update_Method` and + the audit schema grant tests do not change, because no store method or grant is added. + The comment in `AuditEntry_Is_AppendOnly` and the catalogue text that name the + redaction handler, the purge job and a module locator as three sanctioned sites are + corrected in the same commit, since the one executor replaces them. +- Criterion C18's "redelivery finds the existing result audit" is met by the one platform + transaction of § 8, not by a delivery inbox, and the phase text is corrected to say so. +- Corrections owed to [Audit Subsystem § 10](../architecture/31-audit-subsystem.md), + [Data Protection](../architecture/23-data-protection.md), the Audit module spec and the + catalogue ride the acceptance commit. + +## References + +- [ADR-0033](0033-audit-durability-model.md), + [ADR-0038](0038-cross-cutting-port-and-event-contracts.md), + [ADR-0044](0044-audit-write-path.md), + [ADR-0046](0046-durable-event-delivery-and-recovery.md), + [ADR-0101](0101-platform-operator-authority.md), + [ADR-0107](0107-data-request-fulfillment-and-account-closure.md) +- [Audit Subsystem](../architecture/31-audit-subsystem.md), + [Audit Coverage](../standards/18-audit-coverage.md) diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4d69d991..2d007c78 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -148,6 +148,9 @@ records hosted qualification. Phase 11 owns production qualification. | 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. | | 0105 | [CI Selector Filter And Argument Bounds](0105-ci-selector-filter-and-argument-bounds.md) | Accepted 2026-11-21: raises ADR-0063's 32 KiB filter and 64 KiB argument bounds to 64 KiB and 128 KiB after layout B refused a 33,367-byte filter; counts, salt and algorithm unchanged. | +| 0106 | [Subject Data Requests: Authority, Scope and Status](0106-subject-data-requests-authority-and-status.md) | Accepted 2026-11-22: requests bound to a scope group, self and administrator-on-behalf under the existing `identity.membership.admin` (an administrator erases only a Revoked Membership), no delegate, retained own-scope path, closed status transitions; G15 closed and G20 untouched. | +| 0107 | [Data Request Fulfillment and Global Account Closure](0107-data-request-fulfillment-and-account-closure.md) | Accepted 2026-11-22: per-group transactional jobs, encrypted PostgreSQL export artifact behind a port, anonymise-and-revoke erasure, operator-driven Begin and Finalize closure with fences and Keycloak deletion, exact grants and retained-reference kinds; closes the G16 workflow. | +| 0108 | [Privileged Audit Redaction](0108-privileged-audit-redaction.md) | Accepted 2026-11-22: one operator-admitted executor on the platform scope behind `IAuditRedactor`, locator declarations, a truthful surviving-reference report, no new grant or store method. | ## Proposed ADRs diff --git a/docs/glossary.md b/docs/glossary.md index 09c2a743..c4c95e2a 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -298,6 +298,12 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | **Right of Access** | The user's KVKK/GDPR right to receive an export of their personal data. | | **Right to Erasure** | The user's right to have their personal data deleted, subject to retention exceptions (legal hold, financial records). | | **Anonymisation** | Replacement of PII fields with pseudonymous values; row stays for analytics / audit integrity. Distinct from soft delete and hard delete. | +| **Data request** | A subject-scoped `export`, `erasure` or `closure` request with an immutable snapshot, a closed status and one scope group, under [ADR-0106](decisions/0106-subject-data-requests-authority-and-status.md). Also called a DSAR when it exercises the rights above. | +| **Scope group** | A tenant and either one organization or none (tenant-wide): the context a data request is filed in and the unit of every tenant write, because the row policies admit an organization-bound write only under that organization's announcement. | +| **Retained own scope** | The path by which a person reads and files data requests in a tenant after their Membership is gone, or while Suspended, discovered by `fn_identity_own_data_request_scopes` on the model of the consent subject ([ADR-0106](decisions/0106-subject-data-requests-authority-and-status.md) § 9). | +| **Privileged step** | The part of an erasure or closure only a human platform operator may run on the platform scope: the audit redaction and, for closure, Begin, Finalize and the provider deletion ([ADR-0107](decisions/0107-data-request-fulfillment-and-account-closure.md)). | +| **Global account closure** | The person-authorized, irreversible ending of the global account: User Active to Closing to Closed, the raw provider subject removed, the key and actor tombstone kept, the provider user deleted. Distinct from tenant-scoped erasure and absent from the tenant-admin surface. | +| **Retained-reference kind** | One of the closed kinds ([ADR-0107](decisions/0107-data-request-fulfillment-and-account-closure.md) § 6) under which an erasure reports what it did not remove; nothing it reports is called anonymous. | | **Consent Record** | An append-only per-purpose record (terms of service, recording, marketing). "Changing one's mind" creates a new record, never edits an old one. | | **Sub-processor** | A third-party service LearnStack uses to process tenant data (Keycloak, LiveKit, S3 / SeaweedFS, email provider, ...). Changes require 30-day tenant notice. | diff --git a/docs/modules/audit/README.md b/docs/modules/audit/README.md index 4f23937e..e489626c 100644 --- a/docs/modules/audit/README.md +++ b/docs/modules/audit/README.md @@ -26,8 +26,9 @@ The **read** side — the query API of [§ Querying](../../architecture/31-audit-subsystem.md), its export job and its permission registry — lands with Identity in [Phase 03](../../roadmap/phase-03-identity-admin.md), and so does the GDPR redaction -path, triggered by a user's erasure — `UserGdprDeletedIntegrationEventHandler` and each -module's `IUserReferenceLocator` +path, an operator act on the platform scope with one Audit-owned executor behind +`IAuditRedactor` and each module's `IUserReferenceLocator` declarations +([ADR-0108](../../decisions/0108-privileged-audit-redaction.md)) ([Audit Subsystem § 10](../../architecture/31-audit-subsystem.md)). Partitioning and the retention purge land in [Phase 11](../../roadmap/phase-11-production-hardening.md) against written triggers ([ADR-0035](../../decisions/0035-demand-gated-infrastructure.md)). diff --git a/docs/modules/audit/permissions.md b/docs/modules/audit/permissions.md index 90dfc55a..9120041f 100644 --- a/docs/modules/audit/permissions.md +++ b/docs/modules/audit/permissions.md @@ -32,8 +32,8 @@ audited, and the two mutating paths that exist — GDPR redaction, which lands w erasure handler in [Phase 03](../../roadmap/phase-03-identity-admin.md), and the retention purge, which lands in [Phase 11](../../roadmap/phase-11-production-hardening.md) — run as `learnstack_platform` through `EnterPlatformAdminScope(reason)` and are gated by a -Platform-scope key rather than a tenant-facing one. **That key's name is pending.** Phase 03 -registers it with the permission registry and the erasure handler, in the closed action +Platform-scope key rather than a tenant-facing one. **That key is `platform.data_request.write`** ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8, +[ADR-0108](../../decisions/0108-privileged-audit-redaction.md) § 1), which Phase 03 registers with the permission registry and the redaction executor, in the closed action set [Permission Standards](../../standards/19-permissions.md) fixes, and Phase 11's purge takes the same key or a sibling Phase 03 names — so no writer of `audit_log` lands with a permission nobody has declared. Tenant-facing audit-row creation is not an admitted operation. diff --git a/docs/roadmap/phase-02a-kernel-tenancy.md b/docs/roadmap/phase-02a-kernel-tenancy.md index e70b9271..a8b8230b 100644 --- a/docs/roadmap/phase-02a-kernel-tenancy.md +++ b/docs/roadmap/phase-02a-kernel-tenancy.md @@ -396,7 +396,8 @@ appears in no document and no source file; the canonical template writes `actor_user_id uuid NULL` with none either. The absence is deliberate: [31-audit-subsystem.md](../architecture/31-audit-subsystem.md) depends on the erased actor becoming an orphan surrogate key, which any `ON DELETE` action would -make unreachable. See +make unreachable. (Corrected 2026-11-22 by [ADR-0038 Amendment 5](../decisions/0038-cross-cutting-port-and-event-contracts.md): +the retained identifier is pseudonymous and stays linkable, not an orphan.) See [ADR-0038 Amendment 1](../decisions/0038-cross-cutting-port-and-event-contracts.md). `users` is created by the first Identity migration in [Phase 03](phase-03-identity-admin.md), which owns the table. This packet ships diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 8b76b4fa..374cc57f 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -534,6 +534,8 @@ not acceptance of implementation choices. Navigate by the generated index below. - [ADR-0105 acceptance and implementation (2026-11-21)](#adr-0105-acceptance-and-implementation-2026-11-21) — 24 lines - [P03-9 merge and delivery closeout (2026-11-21)](#p03-9-merge-and-delivery-closeout-2026-11-21) — 60 lines - [ADR-0105 merge and hosted qualification (2026-11-22)](#adr-0105-merge-and-hosted-qualification-2026-11-22) — 57 lines +- [P03-10 — Subject data requests, erasure and global account closure](#p03-10--subject-data-requests-erasure-and-global-account-closure) — 73 lines + - [P03-10 decision package and acceptance (2026-11-22)](#p03-10-decision-package-and-acceptance-2026-11-22) — 71 lines @@ -25623,3 +25625,76 @@ head `db7776b9`, and the earlier packets' rule keys qualification to the final h Status block therefore keeps the P03-9 pair gap open and names this run; whether it closes the gap is the maintainer's decision. The Keycloak readiness timeout has now recurred in both layouts on #46, on #47 and on `main`, with its cause still unproven. + +## P03-10 — Subject data requests, erasure and global account closure + +### P03-10 decision package and acceptance (2026-11-22) + +The decision pass re-verified G15, G16 and G20 against `HEAD` `211b9fd3` and found no +request, status, locator, export, storage, redaction or closure code, no data-request key +and no object-storage port; `users` and `memberships` refuse UPDATE and DELETE by trigger, +the platform scope facade refuses SQL naming `audit_log`, and the Identity row policies admit +a write of an organization-bound row only under that organization's announcement. Five +read-only reconnaissance maps (Identity, Audit, storage/jobs/delivery, frontend/OpenAPI and a +register of about 100 scattered "P03-10 owns" obligations with 16 contradictions) fed the +package. The maintainer then accepted +[ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md), +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108](../decisions/0108-privileged-audit-redaction.md), closing G15 and the G16 +workflow. G20 is untouched, because the package adds no assignable key. + +**The maintainer's choices.** A human operator performs the privileged half; the export +artifact is encrypted PostgreSQL custody behind a port; the Membership is anonymised and +revoked, not deleted; an administrator uses the existing `identity.membership.admin` key; a +24-hour cancellable window precedes erasure and closure; the Keycloak user is deleted; +whole-tenant offboarding is out of scope; status is in-product only. The maintainer also +confirmed that the application is in development and not in use, so no backward +compatibility is owed. + +**Reviews and what changed.** An independent adversarial review of the first drafts found 2 +blockers and 12 major defects, the larger ones verified against code: organization-bound +rows could not be written by a tenant-wide job (the request became one per scope group), the +state machines had dead ends, a closure stored the person's other tenants in a tenant-readable +row, the Keycloak role claim was false, the operator result write refuses the `identity` +module, and the retained own-scope path was undefined. The maintainer then supplied three +further reviews. Their findings were checked against the corpus and the code, and most were +adopted: definer functions were replaced by column-limited platform grants and one trigger +exception, because the Identity tables have no owner arm and the `users` policy admits only +the application role; erasure gained explicit domain operations because the aggregate +refuses a Revoked or system actor; participants run in separate transactions; the fence +sentence of Standard 05 gained an erratum; a closure can finish with named unserved groups +instead of sticking; an administrator may erase only a Revoked Membership; the audit +selection splits by who asked; the locator contract and its census were defined; the error +code, ticket lifecycle, artifact quota and report bound were fixed. One finding was accepted +as a stated risk instead of a change: the recipient address of accepted invitations and its +encrypted envelope stay until Phase 11, because the Accepted storage contract has no erasure +transition and the ciphertext is immutable. + +**Carriers amended with this acceptance.** Dated amendments in ADR-0010, ADR-0016, ADR-0038, +ADR-0044, ADR-0046, ADR-0072, ADR-0095, ADR-0099, ADR-0101, ADR-0102 and ADR-0103; an +erratum in Standard 05 (what "through completion" means); corrections in Data Protection, +Audit Subsystem § 10, the Audit module spec and permissions, Phase 02a, this phase document +and the glossary. The index rows of ADR-0106 to ADR-0108 are Accepted. + +**Step plan.** Four steps, each with its own review rounds: + +1. The request core and the export: the request, artifact, ticket and chunk tables and their + policies and grants; the request aggregate with its status machine; the participant port, + registry and locator census; the retained own-scope function and origin; the export job, + encrypted artifact store, ticketed retrieval and purge; the eligibility and hold ports; + endpoints, audit operations and the additive OpenAPI and SDK changes. +2. Tenant erasure and the privileged redaction: the erasure domain operations, the erasure + witness in the contextual guard, the erasure job, the Audit executor behind + `IAuditRedactor`, the scope method, the operations `complete_erasure` and `inspect`, the + Platform keys, the locators and their canaries, and the runbook. +3. Global account closure: the `users` trigger exception and platform grants, Begin, the + per-group fan-out, Finalize with its intent checkpoint, the Keycloak removal port and + adapter, the platform-side lock acquirer and its census leg, and the replay-floor proofs. +4. The web surface and closeout: the BFF operations and retained-entry paths, the SDK, the + data-request and closure screens with their copy in both locales and the accessibility + proof, the architecture-test catalogue and the Phase 03 Status block. + +**Open for the maintainer.** None blocks the steps. The recipient address of accepted +invitations (retained until Phase 11), the Keycloak `manage-users` exposure, the per-group +filing for a person in several organizations and the missing closure path for a person with +no Membership (Phase 11) are recorded in the ADRs as accepted trade-offs. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index dc6c7493..8a6e36ef 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -24,7 +24,7 @@ > [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), merged in > [PR #47](https://github.com/HodeTech/LearnStack/pull/47) and [qualified in both layouts](phase-03-delivery-log.md#adr-0105-merge-and-hosted-qualification-2026-11-22) > on its own source; the P03-9 B/pair gap stays open before P03-11 exit. No manual UI evidence is owed. G13 and G14 are closed as Accepted; G20 -> stays Open. P03-10 and P03-11 remain unstarted. +> stays Open. P03-10's decisions are Accepted and its implementation is in progress; P03-11 remains unstarted. > > | Packet | Title | State | > |---|---|---| @@ -38,7 +38,7 @@ > | 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 | Complete and merged — [closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21); final-head opposite-layout/pair qualification remains open (the layout-B filter ceiling was raised by [ADR-0105](../decisions/0105-ci-selector-filter-and-argument-bounds.md), [qualified](phase-03-delivery-log.md#adr-0105-merge-and-hosted-qualification-2026-11-22)); the maintainer items, the P03-10 and Phase 11 constraint and the tooling note are owned in the closeout | -> | P03-10 | DSAR and global account closure | Not started | +> | P03-10 | DSAR and global account closure | In progress — G15 and the G16 workflow Accepted ([package](phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)); Step 1 not started | > | P03-11 | Exit enforcement | Not started | ## Goal @@ -152,8 +152,8 @@ named part, and the register links each explicit acceptance and vehicle. | 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 delivered and merged by P03-9 Steps 1 to 3 and 5 ([closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21)) | | 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 and merged by P03-9 Step 4 ([closeout](phase-03-delivery-log.md#p03-9-merge-and-delivery-closeout-2026-11-21)) | -| 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 | +| 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 | Accepted — 2026-11-22, [ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) and the [package](phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22); no delegate authority exists (decided absent) and no assignable key is added; implementation is P03-10 Steps 1 to 4 | +| 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; workflow Accepted — 2026-11-22, [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) and [ADR-0108](../decisions/0108-privileged-audit-redaction.md) with the [package](phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22); implementation is P03-10 Steps 1 to 4 | | 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 | @@ -303,17 +303,20 @@ by this note. G15 separates self/admin/delegate requests and prevents an org admin from requesting another branch's data. A learner needs a self-service path without Studio administration rights, including a scoped status receipt after erasure. -- A tenant-scoped erasure removes the `Membership` and its `MembershipProfile`, +- A tenant-scoped erasure removes the Membership's role assignments, clears its + `MembershipProfile` and leaves the `Membership` a Revoked pseudonymised tombstone + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 5), anonymises that tenant's behaviour rows, and redacts the permitted human-facing audit fields while keeping the action record. Audit identifiers and causal - metadata remain subject to the first-writer decision below. Tenant erasure + metadata survive and are reported ([ADR-0108](../decisions/0108-privileged-audit-redaction.md)). Tenant erasure preserves the [permanent global binding/tombstone](../architecture/23-data-protection.md#identity-foundation-and-classification-ownership). - **Global account closure has no tenant-admin endpoint.** The person authorizes the request without receiving a Platform permission. G13/G16 define the privileged executor, stable participant inventory and write fence against new - memberships, delayed mirrors and pending invitation acceptance. It fans out - `UserAnonymisationRequestedV1` and reconciles Data Protection's completion - workflow; request creation or event emission alone is not completion. + memberships, delayed mirrors and pending invitation acceptance. Two operator + acts, Begin and Finalize, and a per-group fan-out of erasure requests carry it + (ADR-0107 § 7); no integration event does, and request creation alone is not + completion. - The audited `EnterPlatformAdminScope(reason)` from [Phase 02a Packet 7](phase-02a-kernel-tenancy.md) is the only path that reads across tenants during either flow, and every use of it is MUST-class audited. @@ -660,7 +663,7 @@ renderer/Studio expansion and the - Tenant-scoped data-request surface: request an export, request an erasure, view status. Global account closure is deliberately absent from this surface. - Self-service data requests/status for a learner without admin permissions, plus - the separate person-authorized global closure surface under G13/G15/G16. + the separate person-authorized global closure surface under G15/G16. - Identity-backed admission for existing Tenancy locale/branding commands is named explicitly in the packet package; no new route is implied by a permission registration. Full tenant-setting/branding editors remain Phase 06. Generic @@ -840,7 +843,7 @@ Test-only endpoints, fake grants or empty scans do not establish shipped behavio | C15 | Dashboard/recovery remain absent until admitted. Positive and denied routes, stale fences, producer-versus-subscriber replay, unchanged sibling inboxes and job quiescence/reservations prove only the accepted transition/grants; MUST result audit and runbooks are usable. | P03-9 | | C16 | Tenant-admin organization create/read/update/archive succeeds under Tenancy contracts; foreign tenant/org, inactive/archived org and default/last-org controls match G3/G5. No cross-module Organization FK/join or write-hatch shortcut exists. The identity-backed settings slice exposes only its named supported commands/fields. | P03-3 | | C17 | A subject export excludes another person in the same tenant as well as foreign tenants/orgs and disallowed notes. Org-admin cannot request another branch; self-service works without admin rights. Eligibility/holds, purpose/recipient and post-erasure status access match G15. | P03-10 | -| C18 | Export reaches a usable authorized artifact with decided expiry/revocation/cleanup. Tenant erasure removes authorized memberships/profiles and transforms behavior per Data Protection while the other tenant's real login works. Global closure cannot be resurrected by pending invites/new memberships/delayed mirrors. Crash-after-platform-commit redelivery finds the existing result audit; immutable facts, replay floors and uncertain reservations survive with truthful retained-copy status. | P03-10 | +| C18 | Export reaches a usable authorized artifact with decided expiry/revocation/cleanup. Tenant erasure removes authorized memberships/profiles and transforms behavior per Data Protection while the other tenant's real login works. Global closure cannot be resurrected by pending invites/new memberships/delayed mirrors. A re-run after the platform commit finds the existing result audit (one platform transaction, no inbox); immutable facts, replay floors and uncertain reservations survive with truthful retained-copy status. | P03-10 | | C19 | MUST mutations/results commit with business state; forced audit failure rolls back success or refuses otherwise-successful sensitive disclosure. Real HTTP/application denials have exactly their decided evidence and preserve 403/404 on audit fault. Trusted actor/membership/role/source/platform/operator/route context cannot be forged. Applicable locators are registered; no Identity-owned audit table exists. | P03-2, P03-6, P03-9–10 | | C20 | New screens demonstrate enabled locales, safe tenant themes, keyboard/focus/form/error/reflow/contrast, empty/loading/conflict and expiry/outage/429/503 recovery. Scope and destructive effect are clear; no internal token/secret/identifier debugging enters product copy. | Each UI packet | | C21 | All applicable canonical catalogue obligations have actual subjects and dirty/clean controls, complete required CI populations and zero skips. LS0001/LS0002 are Error, absent from WarningsNotAsErrors, and the solution builds clean. Gateway scaffold uses explicit v1 paths/priorities, no Hub-secret dependency and disabled OIDC; full public-route allowlist/lint/activation remain Phase 11. | P03-11 | diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 4a06ab70..166a066d 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -5055,7 +5055,16 @@ EXCLUSIVE mode and establishes the total invariant. A shared nonadmin Membership write cannot enter an incomplete tenant. Later closure/ status writers take the same target User fence first and every affected exclusive tenant key next, in stable order, retaining them through the status change and -completion. P03-10 owns and proves that production workflow. They cannot make +completion. P03-10 owns and proves that production workflow. + +> **Erratum (2026-11-22, [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7 +> and [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) Amendment 8).** +> "Through the status change and completion" means through the transaction that makes the +> User nonadmitting; the per-group erasure that follows runs as the application role and +> does not retain the keys. A tenant that does not allow ordinary work is an explicit, +> named exception to the final-administrator check, and its data is reported as an +> unserved group. + They cannot make the final administrator ineligible without a separately accepted recovery/termination contract; closure and Archived status are not implicit exceptions. From 492f7f9e73fc252f8ff7a004c0b925b7d9964ea4 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 06:05:49 +0300 Subject: [PATCH 04/61] feat(identity): add data request storage, aggregates and ports P03-10 Step 1, unit 1: the request, artifact, ticket and chunk tables with the canonical row policy, the status-machine and lifecycle guards and the exact ADR-0107 grants; the DataSubjectRequest, DataExportArtifact and DataExportTicket aggregates; and the SharedKernel participant, eligibility, hold-source and artifact-store ports with their closed vocabularies. ADR: 0106, 0107 Module: Identity, SharedKernel, Application Co-Authored-By: Claude Sonnet 5.5 --- .../PersistenceCompositionExtensions.cs | 4 + .../UserDataParticipantRegistry.cs | 66 + .../UserDataProtectionRegistration.cs | 36 + .../DataProtection/ClosedCodeTable.cs | 82 + .../DataProtection/DataRequestLimits.cs | 80 + .../DataProtection/DataRequestScopeGroup.cs | 48 + .../DataProtection/DataRequestVocabulary.cs | 173 ++ .../IDataExportArtifactStore.cs | 144 ++ .../DataProtection/IDataRequestEligibility.cs | 127 ++ .../DataProtection/IDataRequestHoldSource.cs | 66 + .../DataProtection/IUserDataParticipant.cs | 196 ++ .../DataExportArtifact.cs | 122 ++ .../DataExportTicket.cs | 102 + .../DataRequestDocuments.cs | 170 ++ .../DataSubjectRequest.cs | 322 +++ .../Identifiers.cs | 9 + .../IdentityFailures.cs | 4 +- .../Persistence/DataRequestConfigurations.cs | 241 +++ .../Persistence/DataRequestStorageDdl.cs | 445 +++++ .../Persistence/IdentityDbContext.cs | 3 + ...3001_add_data_subject_requests.Designer.cs | 1762 +++++++++++++++++ ...0261122013001_add_data_subject_requests.cs | 216 ++ .../IdentityDbContextModelSnapshot.cs | 484 +++++ .../GlobalIdentityModelTests.cs | 2 +- .../PersistenceConventionTests.cs | 8 + .../Database/DataRequestSchemaSeed.cs | 121 ++ .../DataRequestStorageControlTests.cs | 262 +++ .../Database/DataRequestStorageTests.cs | 643 ++++++ ...tionStructureTests.DataRequestRelations.cs | 61 + .../EducationStructureTests.Detectors.cs | 19 +- ...ucationStructureTests.InvitationUpgrade.cs | 4 +- .../GlobalIdentitySchemaTests.Controls.cs | 6 +- .../Database/GlobalIdentitySchemaTests.cs | 8 +- .../Database/IdentityMembershipFixture.cs | 1 + .../IdentityMembershipTests.Isolation.cs | 16 +- .../Database/MigrationRollbackTests.cs | 14 +- .../Database/OrgScopeSchemaTests.cs | 7 +- .../Database/SchemaFixture.cs | 7 + .../Database/SchemaTableClasses.cs | 5 +- .../Database/TenancySchemaTests.cs | 9 +- .../Identity/DataExportArtifactDomainTests.cs | 143 ++ .../Identity/DataSubjectRequestDomainTests.cs | 411 ++++ .../DataProtection/DataRequestPortTests.cs | 150 ++ docs/architecture/23-data-protection.md | 4 + scripts/ci-test-shards-plan.json | 2 + 45 files changed, 6783 insertions(+), 22 deletions(-) create mode 100644 backend/src/LearnStack.Application/DataProtection/UserDataParticipantRegistry.cs create mode 100644 backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/DataRequestScopeGroup.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/DataRequestVocabulary.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestHoldSource.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportTicket.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataSubjectRequest.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestSchemaSeed.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageControlTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.DataRequestRelations.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataExportArtifactDomainTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataSubjectRequestDomainTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/DataRequestPortTests.cs diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index d2526831..2e19143e 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -6,6 +6,7 @@ using LearnStack.Modules.Identity.Application.CustomFields; using LearnStack.Modules.Tenancy.Application.FieldConsents; using LearnStack.Infrastructure.Jobs; +using LearnStack.Application.DataProtection; using LearnStack.Modules.Customization.Infrastructure; using LearnStack.Modules.Customization.Application.Contracts.Definitions; using LearnStack.Modules.Customization.Application.Contracts.CustomFields; @@ -188,6 +189,9 @@ public static IServiceCollection AddLearnStackPersistence( PlatformAdminScope.PlatformDataSourceKey, (_, _) => new PrivilegedDataSource(() => BuildPlatformDataSource(platformConnectionString))); services.AddLearnStackBackgroundJobContracts(); + // ADR-0107 § 1: the participant collection and the hold-source default. No participant + // is registered yet; each module adds its own from its registration. + services.AddLearnStackUserDataProtection(); services.AddInvitationEmailDelivery(configuration); // The scope is a stateless singleton. Admission is not its concern any more: the diff --git a/backend/src/LearnStack.Application/DataProtection/UserDataParticipantRegistry.cs b/backend/src/LearnStack.Application/DataProtection/UserDataParticipantRegistry.cs new file mode 100644 index 00000000..c8b90c26 --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/UserDataParticipantRegistry.cs @@ -0,0 +1,66 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Application.DataProtection; + +/// +/// The composition root's closed collection of every registered +/// (ADR-0107 § 1). +/// +/// +/// +/// Built from the container's registrations, the way the audit catalogue and the operation policy +/// catalogue are, and refused when a key is malformed or registered twice: two participants writing +/// the same progress-record key would make a resumed job skip work it never did. +/// +/// +/// Ordered ordinally by key, so the order a job runs participants in, and records them in, does not +/// depend on registration order. An empty registry is valid; no module registers a participant +/// until its first writer ships. +/// +/// +public sealed class UserDataParticipantRegistry : IUserDataParticipantRegistry +{ + private readonly FrozenDictionary _byKey; + + /// A participant is missing, malformed or duplicated. + public UserDataParticipantRegistry(IEnumerable participants) + { + ArgumentNullException.ThrowIfNull(participants); + var byKey = new Dictionary(StringComparer.Ordinal); + foreach (var participant in participants) + { + if (participant is null || !DataRequestLimits.IsParticipantKey(participant.Key) + || !byKey.TryAdd(participant.Key, participant)) + { + throw new InvalidOperationException("User data participant registrations are missing, malformed or conflicting."); + } + } + + if (byKey.Count > DataRequestLimits.MaximumParticipants) + { + throw new InvalidOperationException("User data participant registrations exceed the progress record's bound."); + } + + _byKey = byKey.ToFrozenDictionary(StringComparer.Ordinal); + Participants = [.. byKey.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => pair.Value)]; + } + + /// + public IReadOnlyList Participants { get; } + + /// + public bool TryGet(string key, [NotNullWhen(true)] out IUserDataParticipant? participant) + { + if (key is not null && _byKey.TryGetValue(key, out var found)) + { + participant = found; + return true; + } + + participant = null; + return false; + } +} diff --git a/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs b/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs new file mode 100644 index 00000000..399f4ba7 --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs @@ -0,0 +1,36 @@ +using LearnStack.SharedKernel.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Application.DataProtection; + +/// +/// The composition-root seam for subject data requests: the participant collection and the +/// demand-gated hold source default. +/// +/// +/// +/// A module registers its participant with +/// services.TryAddEnumerable(ServiceDescriptor.Scoped<IUserDataParticipant, TParticipant>()) +/// from its own registration, as a module registers its IAuditCatalogSource; the registry is +/// scoped because a participant reads through the request's module contexts +/// (ADR-0107 § 1). +/// No participant is registered here. +/// +/// +/// is the working default of +/// (ADR-0106 § 7: owner Phase 09, trigger the first aggregate that can carry a hold); a real +/// source replaces it by registering first. +/// +/// +public static class UserDataProtectionRegistration +{ + public static IServiceCollection AddLearnStackUserDataProtection(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddScoped(provider => + new UserDataParticipantRegistry(provider.GetServices())); + services.TryAddSingleton(); + return services; + } +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs b/backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs new file mode 100644 index 00000000..40b1a352 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs @@ -0,0 +1,82 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// One closed, bidirectional spelling table for an enum whose stored and wire spelling is a +/// lower snake_case code. +/// +/// +/// +/// The data-request vocabularies of +/// ADR-0106 +/// and ADR-0107 +/// are written as codes (awaiting_privileged_step, audit_actor_reference), and those +/// codes are what the database CHECKs, the receipts and the platform-side SQL name. The table +/// is written out pair by pair rather than derived from member names, so renaming a member cannot +/// silently rename a stored value. +/// +/// +/// Construction refuses an incomplete or ambiguous table: every defined member exactly once and +/// every code unique and well formed. A table that is wrong fails at type initialisation, not at +/// the first row that happens to carry the missing member. +/// +/// +public sealed class ClosedCodeTable + where TEnum : struct, Enum +{ + private readonly FrozenDictionary _codes; + private readonly FrozenDictionary _values; + + internal ClosedCodeTable(params (TEnum Value, string Code)[] pairs) + { + ArgumentNullException.ThrowIfNull(pairs); + var defined = Enum.GetValues(); + if (pairs.Length != defined.Length + || pairs.Select(pair => pair.Value).Distinct().Count() != pairs.Length + || !defined.All(value => pairs.Any(pair => EqualityComparer.Default.Equals(pair.Value, value))) + || pairs.Select(pair => pair.Code).Distinct(StringComparer.Ordinal).Count() != pairs.Length + || !pairs.All(pair => IsWellFormed(pair.Code))) + { + throw new InvalidOperationException("A closed code table must name every member exactly once with a unique code."); + } + + _codes = pairs.ToFrozenDictionary(pair => pair.Value, pair => pair.Code); + _values = pairs.ToFrozenDictionary(pair => pair.Code, pair => pair.Value, StringComparer.Ordinal); + Codes = [.. pairs.Select(pair => pair.Code)]; + } + + /// Every code, in declaration order. + public ImmutableArray Codes { get; } + + /// The code of a defined member. + /// The value is not a defined member. + public string ToCode(TEnum value) => _codes.TryGetValue(value, out var code) + ? code + : throw new ArgumentOutOfRangeException(nameof(value), "The value is not a member of the closed vocabulary."); + + /// Reads a code ordinally; no case folding and no member-name fallback. + public bool TryParse(string? code, out TEnum value) + { + if (code is not null && _values.TryGetValue(code, out value)) + { + return true; + } + + value = default; + return false; + } + + /// Reads a stored code; an unknown code is corrupt storage, not input. + /// The code is not in the closed vocabulary. + public TEnum Parse(string code) => TryParse(code, out var value) + ? value + : throw new FormatException("The stored code is not a member of the closed vocabulary."); + + private static bool IsWellFormed(string code) => + code is { Length: > 0 and <= 64 } + && code[0] is >= 'a' and <= 'z' + && code[^1] is >= 'a' and <= 'z' + && code.All(character => character is (>= 'a' and <= 'z') or '_'); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs new file mode 100644 index 00000000..b1b08ea6 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs @@ -0,0 +1,80 @@ +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// The fixed bounds of subject data requests, each owned by the ADR section named beside it. +/// The database CHECKs and guards repeat the same numbers; a change here is a migration. +/// +public static class DataRequestLimits +{ + /// The cancellable window before an erasure or closure executes (ADR-0106 § 11). + public static readonly TimeSpan CancellationWindow = TimeSpan.FromHours(24); + + /// How long a completed export artifact stays readable (ADR-0107 § 4). + public static readonly TimeSpan ArtifactLifetime = TimeSpan.FromDays(7); + + /// How long a download ticket authorizes chunk reads (ADR-0107 § 4). + public static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(15); + + /// The most plaintext one encrypted chunk holds (ADR-0107 § 4: 128 KiB). + public const int ChunkPlaintextBytes = 128 * 1024; + + /// AES-256-GCM nonce length; a fresh nonce per chunk (ADR-0107 § 4). + public const int NonceBytes = 12; + + /// AES-256-GCM authentication tag length. + public const int TagBytes = 16; + + /// The key length of every key in the export key ring. + public const int KeyBytes = 32; + + /// The most keys the export key ring may hold (ADR-0107 § 4: one to four). + public const int MaximumKeyVersions = 4; + + /// The longest key-version label, as the invitation envelope ring spells it. + public const int MaximumKeyVersionLength = 32; + + /// The default bundle ceiling, DataExport:MaxBytes (ADR-0107 § 4). + public const long DefaultMaximumBundleBytes = 16L * 1024 * 1024; + + /// The largest bundle ceiling the setting may name (ADR-0107 § 4: 64 MiB). + public const long MaximumBundleBytes = 64L * 1024 * 1024; + + /// The most chunks an artifact can have at the largest ceiling. + public const int MaximumChunkCount = (int)(MaximumBundleBytes / ChunkPlaintextBytes); + + /// The audit section's cap inside one bundle (ADR-0107 § 3: 8 MiB). + public const long AuditSectionBytes = 8L * 1024 * 1024; + + /// The most Memberships one request's frozen snapshot may name. + /// + /// A person holds at most one current Membership per group; the rest are Revoked tombstones + /// of earlier admissions. The bound keeps the snapshot a bounded row, not a list that grows + /// without limit. + /// + public const int MaximumSnapshotMemberships = 256; + + /// The most participants one request's progress record may name. + public const int MaximumParticipants = 32; + + /// The longest participant key. + public const int MaximumParticipantKeyLength = 32; + + /// The number of chunks a bundle of plaintext bytes occupies. + /// The bundle is empty or above the largest ceiling. + public static int ChunkCountFor(long byteCount) => + byteCount is < 1 or > MaximumBundleBytes + ? throw new ArgumentOutOfRangeException(nameof(byteCount), "The bundle size is outside the supported range.") + : (int)((byteCount + ChunkPlaintextBytes - 1) / ChunkPlaintextBytes); + + /// Whether a participant key is a closed lower snake_case token of the bounded length. + public static bool IsParticipantKey(string? key) => + key is { Length: > 0 and <= MaximumParticipantKeyLength } + && key[0] is >= 'a' and <= 'z' + && key.All(character => character is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'); + + /// Whether a key-version label matches the export ring's spelling. + public static bool IsKeyVersion(string? version) => + version is { Length: > 0 and <= MaximumKeyVersionLength } + && version.All(character => character is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') + or (>= '0' and <= '9') or '_' or '-'); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestScopeGroup.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestScopeGroup.cs new file mode 100644 index 00000000..0170319f --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestScopeGroup.cs @@ -0,0 +1,48 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// The unit every tenant data request is bound to: one tenant and either one organization or +/// none (ADR-0106 § 2). +/// +/// +/// +/// The group is the context the request was filed in, and every write the request causes runs +/// under that same announcement: the organization row policies admit a write of an +/// organization-bound row only under that organization, so a request that spanned groups would +/// need an RLS exception. A person with Memberships in several organizations files one request +/// per group. +/// +/// +/// A closure is global, but its row still lives in its originating group (ADR-0107 § 7). +/// +/// +public sealed record DataRequestScopeGroup +{ + /// Builds a group, refusing the nil and platform-sentinel tenants and a nil organization. + /// A member is unassigned or names no real scope. + public DataRequestScopeGroup(TenantId tenantId, OrganizationId? organizationId) + { + if (!StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel) + { + throw new ArgumentException("A data request group needs a real tenant.", nameof(tenantId)); + } + + if (organizationId is { } organization && !StronglyTypedId.IsAssigned(organization)) + { + throw new ArgumentException("A data request group's organization must be assigned.", nameof(organizationId)); + } + + TenantId = tenantId; + OrganizationId = organizationId; + } + + public TenantId TenantId { get; } + + /// The group's organization; is the tenant-wide group. + public OrganizationId? OrganizationId { get; } + + /// Whether this is the tenant-wide group. + public bool IsTenantWide => OrganizationId is null; +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestVocabulary.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestVocabulary.cs new file mode 100644 index 00000000..4b87ce7d --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestVocabulary.cs @@ -0,0 +1,173 @@ +using System.Collections.Frozen; + +namespace LearnStack.SharedKernel.DataProtection; + +/// The three data-request kinds (ADR-0106 § 1). +/// Zero is deliberately undefined, so an unassigned field is never a valid kind. +public enum DataRequestKind +{ + Export = 1, + Erasure = 2, + Closure = 3, +} + +/// The closed request statuses of ADR-0106 § 8; the transitions live on the request aggregate. +public enum DataRequestStatus +{ + Requested = 1, + Scheduled = 2, + Fulfilling = 3, + AwaitingPrivilegedStep = 4, + Completed = 5, + Blocked = 6, + Failed = 7, + Cancelled = 8, +} + +/// Who filed a request (ADR-0106 § 3, ADR-0107 § 7). +/// +/// is the per-group erasure a closure's Begin creates; its business +/// actor is the system actor and it has no requester. +/// +public enum DataRequestOrigin +{ + Self = 1, + Administrator = 2, + ClosureFanout = 3, +} + +/// +/// The closed refusal codes a request can record in last_refusal (ADR-0106 § 7, +/// ADR-0107 § 7). +/// +/// +/// A refusal at creation is a response and writes no request; a refusal that leaves a scheduled +/// request in place is recorded, and a re-check refusal at execution ends the request +/// with its code. is a closure +/// Begin attempted before the execution time; it never blocks a request. +/// +public enum DataRequestRefusal +{ + BlockedWindow = 1, + BlockedHold = 2, + BlockedLastAdministrator = 3, +} + +/// The closed reasons a request ends . +/// +/// is ADR-0107 § 4's bundle ceiling. records +/// a job that ended without a business outcome (ADR-0106 § 8 reads failed from the job phase). +/// +public enum DataRequestFailureReason +{ + ExportTooLarge = 1, + ExecutionFailed = 2, +} + +/// +/// The closed retained-reference kinds a receipt reports (ADR-0107 § 6); the receipt carries the +/// kind and a count, never a row identifier. +/// +public enum RetainedReferenceKind +{ + ConsentEvidence = 1, + InvitationRecord = 2, + InvitationEnvelope = 3, + AuditActorReference = 4, + AuditEntityReference = 5, + AuditMetadataReference = 6, + UnscopedAuditRows = 7, + TransportEvidence = 8, + ExecutionEvidence = 9, + ProviderEventRecord = 10, + IdempotencyCache = 11, + AttributionReference = 12, + FederationActorReference = 13, + RequestReceipt = 14, + ExternalCopy = 15, + UnservedGroup = 16, +} + +/// The lifecycle of an export artifact (ADR-0107 § 4). +/// +/// and hold no chunk; may still hold +/// chunks until the purge job runs, and is unreadable either way because expiry is a time check. +/// +public enum DataExportArtifactStatus +{ + Available = 1, + Revoked = 2, + Expired = 3, + Purged = 4, +} + +/// The stored and wire spelling of every data-request vocabulary. +public static class DataRequestCodes +{ + public static ClosedCodeTable Kinds { get; } = new( + (DataRequestKind.Export, "export"), + (DataRequestKind.Erasure, "erasure"), + (DataRequestKind.Closure, "closure")); + + public static ClosedCodeTable Statuses { get; } = new( + (DataRequestStatus.Requested, "requested"), + (DataRequestStatus.Scheduled, "scheduled"), + (DataRequestStatus.Fulfilling, "fulfilling"), + (DataRequestStatus.AwaitingPrivilegedStep, "awaiting_privileged_step"), + (DataRequestStatus.Completed, "completed"), + (DataRequestStatus.Blocked, "blocked"), + (DataRequestStatus.Failed, "failed"), + (DataRequestStatus.Cancelled, "cancelled")); + + public static ClosedCodeTable Origins { get; } = new( + (DataRequestOrigin.Self, "self"), + (DataRequestOrigin.Administrator, "administrator"), + (DataRequestOrigin.ClosureFanout, "closure_fanout")); + + public static ClosedCodeTable Refusals { get; } = new( + (DataRequestRefusal.BlockedWindow, "blocked_window"), + (DataRequestRefusal.BlockedHold, "blocked_hold"), + (DataRequestRefusal.BlockedLastAdministrator, "blocked_last_administrator")); + + public static ClosedCodeTable FailureReasons { get; } = new( + (DataRequestFailureReason.ExportTooLarge, "export_too_large"), + (DataRequestFailureReason.ExecutionFailed, "execution_failed")); + + public static ClosedCodeTable RetainedKinds { get; } = new( + (RetainedReferenceKind.ConsentEvidence, "consent_evidence"), + (RetainedReferenceKind.InvitationRecord, "invitation_record"), + (RetainedReferenceKind.InvitationEnvelope, "invitation_envelope"), + (RetainedReferenceKind.AuditActorReference, "audit_actor_reference"), + (RetainedReferenceKind.AuditEntityReference, "audit_entity_reference"), + (RetainedReferenceKind.AuditMetadataReference, "audit_metadata_reference"), + (RetainedReferenceKind.UnscopedAuditRows, "unscoped_audit_rows"), + (RetainedReferenceKind.TransportEvidence, "transport_evidence"), + (RetainedReferenceKind.ExecutionEvidence, "execution_evidence"), + (RetainedReferenceKind.ProviderEventRecord, "provider_event_record"), + (RetainedReferenceKind.IdempotencyCache, "idempotency_cache"), + (RetainedReferenceKind.AttributionReference, "attribution_reference"), + (RetainedReferenceKind.FederationActorReference, "federation_actor_reference"), + (RetainedReferenceKind.RequestReceipt, "request_receipt"), + (RetainedReferenceKind.ExternalCopy, "external_copy"), + (RetainedReferenceKind.UnservedGroup, "unserved_group")); + + public static ClosedCodeTable ArtifactStatuses { get; } = new( + (DataExportArtifactStatus.Available, "available"), + (DataExportArtifactStatus.Revoked, "revoked"), + (DataExportArtifactStatus.Expired, "expired"), + (DataExportArtifactStatus.Purged, "purged")); + + /// + /// The statuses that hold a group's one active slot (ADR-0106 § 7); every other status is + /// terminal and frees it. + /// + public static FrozenSet NonTerminal { get; } = new[] + { + DataRequestStatus.Requested, DataRequestStatus.Scheduled, + DataRequestStatus.Fulfilling, DataRequestStatus.AwaitingPrivilegedStep, + }.ToFrozenSet(); + + /// Whether a status is one of the four terminal statuses of ADR-0106 § 8. + public static bool IsTerminal(DataRequestStatus status) => + Enum.IsDefined(status) && !NonTerminal.Contains(status); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs new file mode 100644 index 00000000..de5e92f6 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs @@ -0,0 +1,144 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// Custody of an encrypted export artifact: put its chunks, read one chunk, read its metadata, purge +/// it (ADR-0107 § 4). +/// +/// +/// +/// A port with its default adapter still to land. The default is +/// PostgresDataExportArtifactStore in P03-10 Step 1: AES-256-GCM with a fresh 12-byte nonce +/// per chunk, a key ring of one to four 32-byte keys under DataExport:KeyRing in +/// ISecretProvider, associated data binding format and key version, tenant, request, +/// artifact, chunk index and chunk count, at most +/// of plaintext per chunk. An object-storage adapter is owned by +/// Phase 04; its trigger is that +/// phase shipping IStorageProvider, or a measured need to exceed the ceiling. +/// +/// +/// Plaintext never leaves through this port except one chunk at a time, to the subject's own +/// ticketed retrieval; no ciphertext leaves the API and no URL is a bearer credential. Expiry is a +/// time check made by the reader whether or not the purge ran. +/// +/// +/// Every call runs inside the ambient tenant transaction of the artifact's group as +/// learnstack_app; the store opens no connection of its own. +/// +/// +public interface IDataExportArtifactStore +{ + /// + /// Encrypts and stores a completed bundle's chunks and records the artifact, available + /// until after now. + /// + Task PutAsync(DataExportArtifactPut put, + IAsyncEnumerable> plaintextChunks, CancellationToken cancellationToken); + + /// The artifact's metadata, or when the group holds no such artifact. + Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken); + + /// Decrypts one chunk of an available, unexpired artifact. + Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, + CancellationToken cancellationToken); + + /// + /// Deletes every chunk and records the artifact + /// (subject, administrator, newer export or erasure) or + /// (expiry); the metadata row stays as the receipt. + /// + Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, CancellationToken cancellationToken); +} + +/// Names one artifact inside its group. +public sealed record DataExportArtifactLocator +{ + /// The artifact identity is nil. + public DataExportArtifactLocator(Guid artifactId, DataRequestScopeGroup group) + { + ArgumentNullException.ThrowIfNull(group); + if (artifactId == Guid.Empty) + { + throw new ArgumentException("An artifact locator needs the artifact identity.", nameof(artifactId)); + } + + ArtifactId = artifactId; + Group = group; + } + + public Guid ArtifactId { get; } + public DataRequestScopeGroup Group { get; } + + public override string ToString() => nameof(DataExportArtifactLocator); +} + +/// What a put records about the bundle it stores. +public sealed record DataExportArtifactPut +{ + /// A member is unassigned or the size is outside the supported range. + public DataExportArtifactPut(Guid artifactId, Guid requestId, UserId subjectUserId, + DataRequestScopeGroup group, long byteCount) + { + ArgumentNullException.ThrowIfNull(group); + if (artifactId == Guid.Empty || requestId == Guid.Empty) + { + throw new ArgumentException("A put needs the artifact and request identities.", nameof(artifactId)); + } + + if (!StronglyTypedId.IsAssigned(subjectUserId) || subjectUserId == UserId.SystemActor) + { + throw new ArgumentException("A put needs a real subject.", nameof(subjectUserId)); + } + + ChunkCount = DataRequestLimits.ChunkCountFor(byteCount); + ArtifactId = artifactId; + RequestId = requestId; + SubjectUserId = subjectUserId; + Group = group; + ByteCount = byteCount; + } + + public Guid ArtifactId { get; } + public Guid RequestId { get; } + public UserId SubjectUserId { get; } + public DataRequestScopeGroup Group { get; } + + /// The plaintext bundle size. + public long ByteCount { get; } + + /// The chunk count the size implies. + public int ChunkCount { get; } + + public override string ToString() => nameof(DataExportArtifactPut); +} + +/// An artifact's receipt-safe metadata: no plaintext, no ciphertext, no key. +public sealed record DataExportArtifactMetadata(Guid ArtifactId, Guid RequestId, DataExportArtifactStatus Status, + long ByteCount, int ChunkCount, string KeyVersion, DateTimeOffset ExpiresAt, DateTimeOffset? PurgedAt); + +/// One decrypted chunk of a ticketed download. +/// The bytes are the subject's personal data; the type never prints them. +public sealed record DataExportPlaintextChunk +{ + /// The index, count or length is outside the bounds. + public DataExportPlaintextChunk(int index, int count, ReadOnlyMemory bytes) + { + if (count is < 1 or > DataRequestLimits.MaximumChunkCount || index < 0 || index >= count + || bytes.Length is < 1 or > DataRequestLimits.ChunkPlaintextBytes) + { + throw new ArgumentOutOfRangeException(nameof(index), "The chunk is outside the artifact's bounds."); + } + + Index = index; + Count = count; + Bytes = bytes; + } + + public int Index { get; } + public int Count { get; } + [PiiSensitive] + public ReadOnlyMemory Bytes { get; } + + public override string ToString() => nameof(DataExportPlaintextChunk); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs new file mode 100644 index 00000000..74715b20 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs @@ -0,0 +1,127 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// The closed decision whether a data request may be created, or may still execute +/// (ADR-0106 § 7). +/// +/// +/// +/// Asked twice. At a refusal is a response +/// and writes no request; at a refusal ends an +/// erasure blocked with its code, or leaves a closure scheduled with its +/// last_refusal. +/// +/// +/// The default implementation checks structure only, and nothing else: +/// +/// +/// the subject holds a Membership of any status in the group (a Revoked tombstone counts), +/// otherwise ; +/// at creation, no non-terminal request of the same kind, subject and group exists, otherwise +/// — answered 409 +/// business_rule_violation with lockey_request_already_active, and enforced +/// independently by the partial unique index on the non-terminal rows so two concurrent creations +/// cannot both pass; at execution the request being executed is that row and is not counted; +/// an is refused when the subject is the only eligible +/// tenant-wide administrator (); +/// the registered is consulted, and a hold refuses with +/// . +/// +/// +/// The decision is read inside the tenant's ambient context as learnstack_app; it grants no +/// authority and is not the caller's authorization, which the operation policy decides first. +/// +/// +public interface IDataRequestEligibility +{ + Task EvaluateAsync(DataRequestEligibilityQuery query, CancellationToken cancellationToken); +} + +/// When eligibility is asked. +public enum DataRequestEligibilityStage +{ + Creation = 1, + Execution = 2, +} + +/// The closed reasons a request is not eligible. +public enum DataRequestIneligibility +{ + NoMembership = 1, + RequestAlreadyActive = 2, + BlockedLastAdministrator = 3, + BlockedHold = 4, +} + +/// What eligibility is asked about. +public sealed record DataRequestEligibilityQuery +{ + /// A member is undefined or unassigned, or an execution query names no request. + public DataRequestEligibilityQuery(DataRequestKind kind, DataRequestOrigin origin, UserId subjectUserId, + DataRequestScopeGroup group, DataRequestEligibilityStage stage, Guid? requestId = null) + { + ArgumentNullException.ThrowIfNull(group); + if (!Enum.IsDefined(kind) || !Enum.IsDefined(origin) || !Enum.IsDefined(stage)) + { + throw new ArgumentException("An eligibility query needs a defined kind, origin and stage.", nameof(kind)); + } + + if (!StronglyTypedId.IsAssigned(subjectUserId) || subjectUserId == UserId.SystemActor) + { + throw new ArgumentException("An eligibility query needs a real person.", nameof(subjectUserId)); + } + + if ((stage == DataRequestEligibilityStage.Execution) != requestId.HasValue || requestId == Guid.Empty) + { + throw new ArgumentException("An execution query names its request and a creation query names none.", nameof(requestId)); + } + + Kind = kind; + Origin = origin; + SubjectUserId = subjectUserId; + Group = group; + Stage = stage; + RequestId = requestId; + } + + public DataRequestKind Kind { get; } + public DataRequestOrigin Origin { get; } + public UserId SubjectUserId { get; } + public DataRequestScopeGroup Group { get; } + public DataRequestEligibilityStage Stage { get; } + + /// The request being executed; absent at creation. + public Guid? RequestId { get; } + + public override string ToString() => nameof(DataRequestEligibilityQuery); +} + +/// An eligibility answer: eligible, or one closed reason. +public sealed record DataRequestEligibilityDecision +{ + private DataRequestEligibilityDecision(DataRequestIneligibility? reason) => Reason = reason; + + public static DataRequestEligibilityDecision Eligible { get; } = new((DataRequestIneligibility?)null); + + /// The reason is undefined. + public static DataRequestEligibilityDecision Refused(DataRequestIneligibility reason) => Enum.IsDefined(reason) + ? new(reason) + : throw new ArgumentOutOfRangeException(nameof(reason), "The reason is not a member of the closed vocabulary."); + + public DataRequestIneligibility? Reason { get; } + + public bool IsEligible => Reason is null; + + /// + /// The refusal a request records, for the two reasons that are refusals rather than structural + /// answers; otherwise. + /// + public DataRequestRefusal? Refusal => Reason switch + { + DataRequestIneligibility.BlockedHold => DataRequestRefusal.BlockedHold, + DataRequestIneligibility.BlockedLastAdministrator => DataRequestRefusal.BlockedLastAdministrator, + _ => null, + }; +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestHoldSource.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestHoldSource.cs new file mode 100644 index 00000000..55a9a5eb --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestHoldSource.cs @@ -0,0 +1,66 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// Whether something the platform must keep — a payment dispute, a legal hold — stops a subject +/// request (ADR-0106 § 7). +/// +/// +/// +/// A demand-gated port: the working default is , which reports no hold; +/// the owning phase is +/// Phase 09 (payments and +/// disputes), and the trigger is the first aggregate that can carry a hold. The source is consulted +/// by eligibility at creation and at execution, and again at a closure's Begin (ADR-0107 § 7). +/// +/// +/// A hold at creation is the refusal blocked_hold and writes no request. +/// +/// +public interface IDataRequestHoldSource +{ + Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken); +} + +/// The subject, group and kind a hold is asked about. +public sealed record DataRequestHoldQuery +{ + /// A member is undefined or unassigned. + public DataRequestHoldQuery(DataRequestKind kind, UserId subjectUserId, DataRequestScopeGroup group) + { + ArgumentNullException.ThrowIfNull(group); + if (!Enum.IsDefined(kind)) + { + throw new ArgumentException("A hold query needs a defined kind.", nameof(kind)); + } + + if (!StronglyTypedId.IsAssigned(subjectUserId) || subjectUserId == UserId.SystemActor) + { + throw new ArgumentException("A hold query needs a real person.", nameof(subjectUserId)); + } + + Kind = kind; + SubjectUserId = subjectUserId; + Group = group; + } + + public DataRequestKind Kind { get; } + public UserId SubjectUserId { get; } + public DataRequestScopeGroup Group { get; } + + public override string ToString() => nameof(DataRequestHoldQuery); +} + +/// +/// The working default of : no aggregate can carry a hold yet, +/// so none is reported (ADR-0106 § 7; owner Phase 09, trigger the first hold-bearing aggregate). +/// +public sealed class NoHoldSource : IDataRequestHoldSource +{ + public Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + return Task.FromResult(false); + } +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs new file mode 100644 index 00000000..f12715f6 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs @@ -0,0 +1,196 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// One module's part in subject data requests: export its rows for a subject and group, erase +/// what it may erase, and describe what it must retain +/// (ADR-0107 § 1). +/// +/// +/// +/// A registration, not a module-to-module call. Each applicable module implements this +/// port inside its own boundary and the composition root collects the implementations, as it +/// collects IAuditCatalogSource and IOperationPolicySource; no module references +/// another module's participant type, so the four cross-module mechanisms of ADR-0010 stay four. +/// +/// +/// The subject predicate is the participant's. Every participant selects rows by the +/// subject's and the request's group, inside the tenant's ambient context as +/// learnstack_app. A row naming another person as a different party is included only with +/// that reference replaced by third_party; a field holding another person's data is omitted +/// (ADR-0106 § 5). Personal-data category is never disclosure authority. +/// +/// +/// One transaction per participant. The fulfilling job runs each participant's +/// in its own transaction and records its completion in the request's +/// progress record under before the next, so no transaction writes two modules' +/// tables and a resumed job skips completed participants. +/// +/// +public interface IUserDataParticipant +{ + /// + /// The participant's stable key: a lower snake_case token (), + /// unique across the composition root, used as the progress-record key and the bundle section name. + /// + string Key { get; } + + /// Streams the participant's section of an export bundle into a bounded writer (ADR-0107 § 3). + /// + /// The writer belongs to this participant's section alone. A participant never builds the bundle, + /// encrypts or stores it, and stops appending when the writer reports a cap. + /// + Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken); + + /// Erases what this participant may erase for the subject in the group (ADR-0107 § 5). + /// + /// The default does nothing: a participant whose rows are all retained (consent evidence, + /// attribution, audit) only describes them. An implementation is idempotent, because a resumed + /// job may call it again after a crash before its completion was recorded. + /// + Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) => Task.CompletedTask; + + /// + /// Reports what survives for the subject in the group, as closed kinds and counts + /// (ADR-0107 § 6); never a row identifier. + /// + Task> DescribeRetainedAsync( + UserDataSubject subject, CancellationToken cancellationToken); +} + +/// What one participant call concerns: the request's immutable subject and group snapshot. +/// +/// Built from the request row, never from the caller's context, so removing the Membership strands +/// neither pending work nor its scope (ADR-0106 § 8). are the frozen +/// Membership identifiers of the subject in the group, including Revoked tombstones; ADR-0108 § 4 +/// selects audit rows by them. +/// +public sealed record UserDataSubject +{ + /// A member is unassigned, or the snapshot is empty, duplicated or too large. + public UserDataSubject(Guid requestId, DataRequestKind kind, DataRequestOrigin origin, UserId subjectUserId, + DataRequestScopeGroup group, IEnumerable membershipIds) + { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(membershipIds); + if (requestId == Guid.Empty || !Enum.IsDefined(kind) || !Enum.IsDefined(origin)) + { + throw new ArgumentException("A participant subject needs its request identity, kind and origin.", nameof(requestId)); + } + + if (!StronglyTypedId.IsAssigned(subjectUserId) || subjectUserId == UserId.SystemActor) + { + throw new ArgumentException("A participant subject needs a real person.", nameof(subjectUserId)); + } + + var memberships = membershipIds.ToImmutableArray(); + if (memberships.IsEmpty || memberships.Length > DataRequestLimits.MaximumSnapshotMemberships + || memberships.Contains(Guid.Empty) || memberships.Distinct().Count() != memberships.Length) + { + throw new ArgumentException("A participant subject needs its bounded frozen Membership snapshot.", nameof(membershipIds)); + } + + RequestId = requestId; + Kind = kind; + Origin = origin; + SubjectUserId = subjectUserId; + Group = group; + MembershipIds = memberships; + } + + public Guid RequestId { get; } + public DataRequestKind Kind { get; } + public DataRequestOrigin Origin { get; } + public UserId SubjectUserId { get; } + public DataRequestScopeGroup Group { get; } + public ImmutableArray MembershipIds { get; } + + /// Never prints the subject, the group or the snapshot. + public override string ToString() => nameof(UserDataSubject); +} + +/// One closed retained-reference kind and how many references of it survive. +public sealed record RetainedReferenceCount +{ + /// The kind is undefined or the count is negative. + public RetainedReferenceCount(RetainedReferenceKind kind, long count) + { + if (!Enum.IsDefined(kind)) + { + throw new ArgumentOutOfRangeException(nameof(kind), "The retained kind is not a member of the closed vocabulary."); + } + + ArgumentOutOfRangeException.ThrowIfNegative(count); + Kind = kind; + Count = count; + } + + public RetainedReferenceKind Kind { get; } + public long Count { get; } +} + +/// The closed outcome of appending one record to an export section. +public enum UserDataExportAppend +{ + /// The record is in the bundle. + Appended = 1, + + /// + /// The section's own cap is reached (the audit section's 8 MiB, ADR-0107 § 3); the record was not + /// written, and the participant declares the truncation and stops. + /// + SectionCapReached = 2, + + /// + /// The bundle ceiling (DataExport:MaxBytes) is reached; the record was not written and the + /// request ends failed with export_too_large (ADR-0107 § 4). + /// + BundleCeilingReached = 3, +} + +/// +/// The bounded writer of one participant's export section (ADR-0107 § 3). +/// +/// +/// +/// A record is one UTF-8 encoded JSON value appended to a named collection of the section +/// (memberships, invitations, audit, …); collection names follow the participant +/// key's spelling. The writer validates the record, counts its bytes against the section cap and +/// the bundle ceiling, and refuses rather than truncating a record in the middle. +/// +/// +/// The implementation, the bundle envelope (schema version, request identity, generation time) and +/// the encryption belong to the export job and the artifact store; this port is only the bound a +/// participant writes into. +/// +/// +public interface IUserDataExportWriter +{ + /// The bytes this section may still append before either bound is reached. + long RemainingBytes { get; } + + /// Appends one record; never partially. + ValueTask AppendAsync(string collection, ReadOnlyMemory utf8JsonRecord, + CancellationToken cancellationToken); + + /// + /// States that a collection stopped at its cap: the bundle and the receipt say truncated + /// with the records included and the records in total (ADR-0107 § 3). + /// + void DeclareTruncated(string collection, long includedRecords, long totalRecords); +} + +/// +/// The composition root's closed collection of every registered participant, ordered ordinally by key. +/// +public interface IUserDataParticipantRegistry +{ + /// Every participant, ordered ordinally by . + IReadOnlyList Participants { get; } + + /// Finds a participant by its exact key. + bool TryGet(string key, [NotNullWhen(true)] out IUserDataParticipant? participant); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs new file mode 100644 index 00000000..bc52f2ce --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs @@ -0,0 +1,122 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Domain; + +/// +/// The receipt-safe metadata of one encrypted export bundle +/// (ADR-0107 § 4). +/// +/// +/// +/// The ciphertext is not here: its chunks are plain storage rows written and read by the artifact +/// store, and never pass through change tracking. This row holds the size, the chunk count, the key +/// version and the lifecycle, and stays as the receipt after its chunks are gone. +/// +/// +/// Lifecycle. available until its expiry; revoked by the subject, the requesting +/// administrator, a newer export or an erasure, which purges the chunks at once; expired once +/// observed past its expiry; purged by the delayed purge job. Expiry is a time check, so an +/// unpurged expired artifact is already unreadable. +/// +/// +/// The group and subject mirror the request's: a subject has at most one available artifact +/// per group, which a partial unique index enforces. +/// +/// +[TenantOwned] +[OrganizationScoped] +public sealed class DataExportArtifact : AuditableEntity, IAggregateRoot, IOrganizationScoped +{ + private DataExportArtifact() { } + + public TenantId TenantId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + public DataSubjectRequestId RequestId { get; private set; } + public UserId SubjectUserId { get; private set; } + public DataExportArtifactStatus Status { get; private set; } + + /// The plaintext bundle size. + public long ByteCount { get; private set; } + + public int ChunkCount { get; private set; } + + /// The key-ring version the chunks were sealed under; a label, never key material. + public string KeyVersion { get; private set; } = string.Empty; + + public DateTimeOffset ExpiresAt { get; private set; } + + /// When the chunks were deleted, by revocation or by the purge. + public DateTimeOffset? PurgedAt { get; private set; } + + /// + /// Records the artifact of an export that is fulfilling: the group and subject come from the request, + /// never from the caller. + /// + public static Result Create(DataExportArtifactId id, DataSubjectRequest request, long byteCount, + string keyVersion, DateTimeOffset at, UserId actor) + { + ArgumentNullException.ThrowIfNull(request); + if (!StronglyTypedId.IsAssigned(id) || id.Value.Version != 7 + || request.Kind != DataRequestKind.Export || request.Status != DataRequestStatus.Fulfilling || request.IsDeleted + || byteCount is < 1 or > DataRequestLimits.MaximumBundleBytes || !DataRequestLimits.IsKeyVersion(keyVersion) + || !StronglyTypedId.IsAssigned(actor) || at == default || at.Offset != TimeSpan.Zero + || at < (request.UpdatedAt ?? request.CreatedAt) || at > DateTimeOffset.MaxValue - DataRequestLimits.ArtifactLifetime) + { + return Result.Fail(IdentityFailures.BusinessRuleError()); + } + + var artifact = new DataExportArtifact + { + Id = id, + TenantId = request.TenantId, + OrganizationId = request.OrganizationId, + RequestId = request.Id, + SubjectUserId = request.SubjectUserId, + Status = DataExportArtifactStatus.Available, + ByteCount = byteCount, + ChunkCount = DataRequestLimits.ChunkCountFor(byteCount), + KeyVersion = keyVersion, + ExpiresAt = at + DataRequestLimits.ArtifactLifetime, + }; + artifact.MarkCreated(at, actor); + return Result.Ok(artifact); + } + + /// Whether a chunk may be read at : available and unexpired. + public bool IsReadable(DateTimeOffset now) => Status == DataExportArtifactStatus.Available && now < ExpiresAt; + + /// available → revoked before expiry; the caller deletes the chunks in the same transaction. + public Result Revoke(DateTimeOffset at, UserId actor) => + Transition(Status == DataExportArtifactStatus.Available && at < ExpiresAt, DataExportArtifactStatus.Revoked, purged: true, at, actor); + + /// available → expired, once its expiry has passed and before the purge. + public Result Expire(DateTimeOffset at, UserId actor) => + Transition(Status == DataExportArtifactStatus.Available && at >= ExpiresAt, DataExportArtifactStatus.Expired, purged: false, at, actor); + + /// available or expired → purged after expiry; the caller deletes the chunks in the same transaction. + public Result Purge(DateTimeOffset at, UserId actor) => + Transition(Status is DataExportArtifactStatus.Available or DataExportArtifactStatus.Expired && at >= ExpiresAt, + DataExportArtifactStatus.Purged, purged: true, at, actor); + + private Result Transition(bool admitted, DataExportArtifactStatus next, bool purged, DateTimeOffset at, UserId actor) + { + if (!admitted || IsDeleted || Version == long.MaxValue || !StronglyTypedId.IsAssigned(actor) + || at == default || at.Offset != TimeSpan.Zero || at < (UpdatedAt ?? CreatedAt)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + Status = next; + if (purged) + { + PurgedAt = at; + } + + return Result.Ok(None.Value); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportTicket.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportTicket.cs new file mode 100644 index 00000000..779e2d9c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportTicket.cs @@ -0,0 +1,102 @@ +using System.Security.Cryptography; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Domain; + +/// +/// One download cursor over an export artifact, bound to the subject's session and stored only as a +/// digest (ADR-0107 § 4). +/// +/// +/// +/// A CSRF-protected POST mints it for fifteen minutes; it authorizes the sequential chunk reads of one +/// download and is marked consumed when the final chunk is served. A resumed or repeated download mints +/// a new ticket. Neither digest is a bearer credential on its own: the ticket also binds the session. +/// +/// +/// Append-only but for one write-once marker, so it derives rather than +/// AuditableEntity: it carries no update stamps or row version, and the application role's only +/// update privilege is the consumed marker. +/// +/// +[TenantOwned] +[OrganizationScoped] +public sealed class DataExportTicket : Entity, IAggregateRoot, IOrganizationScoped +{ + private DataExportTicket() { } + + public TenantId TenantId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + public DataExportArtifactId ArtifactId { get; private set; } + + /// The SHA-256 digest of the ticket value, lower-case hex; the value itself is never stored. + [PiiSensitive] + public string Digest { get; private set; } = string.Empty; + + /// The SHA-256 digest binding the ticket to the minting session, lower-case hex. + [PiiSensitive] + public string SessionBindingDigest { get; private set; } = string.Empty; + + public DateTimeOffset CreatedAt { get; private set; } + + /// The subject who minted it; only the subject retrieves an export. + public UserId CreatedBy { get; private set; } + + public DateTimeOffset ExpiresAt { get; private set; } + public DateTimeOffset? ConsumedAt { get; private set; } + + /// Mints a ticket for the artifact's own subject while the artifact is readable. + public static Result Mint(DataExportTicketId id, DataExportArtifact artifact, string digest, + string sessionBindingDigest, DateTimeOffset at, UserId subject) + { + ArgumentNullException.ThrowIfNull(artifact); + if (!StronglyTypedId.IsAssigned(id) || id.Value.Version != 7 || !ValidDigest(digest) || !ValidDigest(sessionBindingDigest) + || at == default || at.Offset != TimeSpan.Zero || at > DateTimeOffset.MaxValue - DataRequestLimits.TicketLifetime + || !artifact.IsReadable(at) || at < artifact.CreatedAt || subject != artifact.SubjectUserId + || !StronglyTypedId.IsAssigned(subject) || subject == UserId.SystemActor) + { + return Result.Fail(IdentityFailures.BusinessRuleError()); + } + + return Result.Ok(new DataExportTicket + { + Id = id, + TenantId = artifact.TenantId, + OrganizationId = artifact.OrganizationId, + ArtifactId = artifact.Id, + Digest = digest, + SessionBindingDigest = sessionBindingDigest, + CreatedAt = at, + CreatedBy = subject, + ExpiresAt = at + DataRequestLimits.TicketLifetime, + }); + } + + /// Whether the ticket still authorizes a chunk read at . + public bool IsUsable(DateTimeOffset now) => ConsumedAt is null && now >= CreatedAt && now < ExpiresAt; + + /// Compares a presented ticket digest and session binding in fixed time. + public bool Matches(string digest, string sessionBindingDigest) => + SameDigest(Digest, digest) & SameDigest(SessionBindingDigest, sessionBindingDigest); + + /// Marks the download finished when its final chunk is served; a ticket is consumed once. + public Result Consume(DateTimeOffset at) + { + if (!IsUsable(at) || at.Offset != TimeSpan.Zero) + { + return IdentityFailures.BusinessRule(); + } + + ConsumedAt = at; + return Result.Ok(None.Value); + } + + private static bool ValidDigest(string? value) => value is { Length: 64 } && value.All(char.IsAsciiHexDigitLower); + + private static bool SameDigest(string actual, string? supplied) => ValidDigest(actual) && ValidDigest(supplied) + && CryptographicOperations.FixedTimeEquals(Convert.FromHexString(actual), Convert.FromHexString(supplied!)); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs new file mode 100644 index 00000000..da54ff2c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs @@ -0,0 +1,170 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Globalization; +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Identity.Domain; + +/// +/// The canonical JSON of a request's three bounded documents: the frozen Membership snapshot, the +/// participant progress record and the closed retained-reference report. +/// +/// +/// +/// Written in one canonical form (sorted, lower case, fixed instant format) so that the stored value +/// is a function of its content, and read strictly: a stored document the CHECKs would not admit is +/// corrupt storage and throws, never a partially read value. The CHECKs on +/// data_subject_requests repeat these shapes, because jsonb is otherwise unbounded. +/// +/// +/// None holds a name, an address or any content: the snapshot holds pseudonymous Membership +/// identifiers, the progress record participant keys and instants, the report closed kinds and counts +/// (ADR-0106 § 9). +/// +/// +public static class DataRequestDocuments +{ + /// The fixed UTC instant format of a progress entry, at the precision of a .NET tick. + public const string InstantFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'"; + + public const string EmptyObject = "{}"; + + /// Writes a non-empty, duplicate-free, bounded set of Membership identifiers, sorted. + /// when the set is empty, duplicated, unassigned or too large. + public static string? WriteMemberships(IReadOnlyCollection memberships) + { + ArgumentNullException.ThrowIfNull(memberships); + if (memberships.Count is < 1 or > DataRequestLimits.MaximumSnapshotMemberships + || memberships.Any(member => !member.IsInitialized() || member.Value == Guid.Empty || member.Value.Version != 7) + || memberships.Distinct().Count() != memberships.Count) + { + return null; + } + + return JsonSerializer.Serialize(memberships.Select(member => member.Value.ToString("D")) + .Order(StringComparer.Ordinal).ToArray()); + } + + /// The stored snapshot is not a canonical bounded set. + public static ImmutableArray ReadMemberships(string json) + { + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Array) + { + throw Corrupt(); + } + + var memberships = document.RootElement.EnumerateArray().Select(element => + element.ValueKind == JsonValueKind.String && Guid.TryParseExact(element.GetString(), "D", out var id) + && id.Version == 7 && string.Equals(element.GetString(), id.ToString("D"), StringComparison.Ordinal) + ? MembershipId.From(id) + : throw Corrupt()).ToImmutableArray(); + return WriteMemberships(memberships) is null ? throw Corrupt() : memberships; + } + catch (JsonException) + { + throw Corrupt(); + } + } + + /// Writes a progress record: participant key to its completion instant, sorted by key. + /// when a key is malformed, an instant is not UTC or the record is too large. + public static string? WriteProgress(IReadOnlyDictionary progress) + { + ArgumentNullException.ThrowIfNull(progress); + if (progress.Count > DataRequestLimits.MaximumParticipants + || progress.Any(entry => !DataRequestLimits.IsParticipantKey(entry.Key) + || entry.Value == default || entry.Value.Offset != TimeSpan.Zero)) + { + return null; + } + + var ordered = progress.OrderBy(entry => entry.Key, StringComparer.Ordinal) + .ToDictionary(entry => entry.Key, entry => entry.Value.UtcDateTime.ToString(InstantFormat, CultureInfo.InvariantCulture), + StringComparer.Ordinal); + return JsonSerializer.Serialize(ordered); + } + + /// The stored record is malformed. + public static FrozenDictionary ReadProgress(string json) + { + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + throw Corrupt(); + } + + var progress = new Dictionary(StringComparer.Ordinal); + foreach (var entry in document.RootElement.EnumerateObject()) + { + if (entry.Value.ValueKind != JsonValueKind.String + || !DateTime.TryParseExact(entry.Value.GetString(), InstantFormat, CultureInfo.InvariantCulture, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var instant) + || !progress.TryAdd(entry.Name, new DateTimeOffset(instant, TimeSpan.Zero))) + { + throw Corrupt(); + } + } + + return WriteProgress(progress) is null ? throw Corrupt() : progress.ToFrozenDictionary(StringComparer.Ordinal); + } + catch (JsonException) + { + throw Corrupt(); + } + } + + /// Writes a closed retained-reference report: kind code to count, sorted by code. + /// when a kind repeats or a count is negative. + public static string? WriteResult(IReadOnlyCollection retained) + { + ArgumentNullException.ThrowIfNull(retained); + if (retained.Any(entry => entry is null) || retained.Select(entry => entry.Kind).Distinct().Count() != retained.Count) + { + return null; + } + + var ordered = retained.ToDictionary(entry => DataRequestCodes.RetainedKinds.ToCode(entry.Kind), entry => entry.Count, + StringComparer.Ordinal) + .OrderBy(entry => entry.Key, StringComparer.Ordinal) + .ToDictionary(entry => entry.Key, entry => entry.Value, StringComparer.Ordinal); + return JsonSerializer.Serialize(ordered); + } + + /// The stored report is malformed. + public static FrozenDictionary ReadResult(string json) + { + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + throw Corrupt(); + } + + var result = new Dictionary(); + foreach (var entry in document.RootElement.EnumerateObject()) + { + if (!DataRequestCodes.RetainedKinds.TryParse(entry.Name, out var kind) + || entry.Value.ValueKind != JsonValueKind.Number || !entry.Value.TryGetInt64(out var count) + || count < 0 || !result.TryAdd(kind, count)) + { + throw Corrupt(); + } + } + + return result.ToFrozenDictionary(); + } + catch (JsonException) + { + throw Corrupt(); + } + } + + private static InvalidOperationException Corrupt() => new("A stored data request document is malformed."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataSubjectRequest.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataSubjectRequest.cs new file mode 100644 index 00000000..6a160292 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataSubjectRequest.cs @@ -0,0 +1,322 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Domain; + +/// +/// One subject data request — an export, an erasure or a global account closure — bound to one scope +/// group, with the closed status machine of +/// ADR-0106 § 8. +/// +/// +/// +/// An immutable snapshot. The kind, origin, subject, requester, group, frozen Membership +/// identifiers and execution time are set by a factory and never change, so removing the Membership +/// strands neither pending work nor its status. The database guard refuses the same changes. +/// +/// +/// The transitions are the only mutators. Each is one of ADR-0106 § 8's arrows and returns a +/// business_rule_violation for any other; nothing here throws for an expected refusal. Who may +/// take a transition — the requester, the subject, a job, an operator — is the calling operation's +/// authorization, not this aggregate's. The privileged arrows (an erasure's +/// awaiting_privileged_step → completed, a closure's Begin and Finalize) are modelled here and +/// executed by the operator acts of ADR-0107 § 7 and § 8, which own their database witnesses. +/// +/// +/// Every terminal status frees the group's one active slot, which the partial unique index on +/// the non-terminal rows enforces; a terminal request accepts no further change. +/// +/// +[TenantOwned] +[OrganizationScoped] +public sealed class DataSubjectRequest : AuditableEntity, IAggregateRoot, IOrganizationScoped +{ + private DataSubjectRequest() { } + + public TenantId TenantId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + public DataRequestKind Kind { get; private set; } + public DataRequestOrigin Origin { get; private set; } + public UserId SubjectUserId { get; private set; } + + /// The person who filed the request; for a closure's fan-out erasure. + public UserId? RequesterUserId { get; private set; } + + public DataRequestStatus Status { get; private set; } + + /// The frozen Membership identifiers of the subject in the group, as canonical JSON. + public string MembershipSnapshotJson { get; private set; } = "[]"; + + /// When a scheduled erasure or closure may execute; the end of its cancellable window. + public DateTimeOffset? ExecuteAt { get; private set; } + + /// Participant key to completion instant, as canonical JSON (ADR-0107 § 1). + public string ProgressJson { get; private set; } = DataRequestDocuments.EmptyObject; + + /// Retained-reference kind to count, as canonical JSON (ADR-0107 § 6). + public string ResultJson { get; private set; } = DataRequestDocuments.EmptyObject; + + /// The latest refusal recorded against the request, shown on its receipt. + public DataRequestRefusal? LastRefusal { get; private set; } + + public DataRequestFailureReason? FailureReason { get; private set; } + + /// When the request completed; completed means every step, the privileged one included. + public DateTimeOffset? CompletedAt { get; private set; } + + public DataRequestScopeGroup Group => new(TenantId, OrganizationId); + + public ImmutableArray SnapshotMembershipIds => DataRequestDocuments.ReadMemberships(MembershipSnapshotJson); + + public FrozenDictionary Progress => DataRequestDocuments.ReadProgress(ProgressJson); + + public FrozenDictionary RetainedReport => DataRequestDocuments.ReadResult(ResultJson); + + public bool IsTerminal => DataRequestCodes.IsTerminal(Status); + + /// The person files a request for themselves: an export, an erasure or a closure (ADR-0106 § 3). + public static Result FileForSelf(DataSubjectRequestId id, DataRequestKind kind, UserId subject, + DataRequestScopeGroup group, IReadOnlyCollection memberships, DateTimeOffset at) => + Create(id, kind, DataRequestOrigin.Self, subject, subject, group, memberships, at, subject); + + /// + /// A holder of identity.membership.admin files an export or an erasure for a subject in the + /// group; an administrator never creates a closure (ADR-0106 § 3). + /// + public static Result FileForSubject(DataSubjectRequestId id, DataRequestKind kind, UserId administrator, + UserId subject, DataRequestScopeGroup group, IReadOnlyCollection memberships, DateTimeOffset at) => + kind == DataRequestKind.Closure || administrator == subject + ? Result.Fail(IdentityFailures.BusinessRuleError()) + : Create(id, kind, DataRequestOrigin.Administrator, subject, administrator, group, memberships, at, administrator); + + /// + /// A closure's Begin creates one group's erasure: fulfilling at once, with no window and no + /// cancellation, attributed to the system actor (ADR-0107 § 7). + /// + public static Result FanOutErasure(DataSubjectRequestId id, UserId subject, + DataRequestScopeGroup group, IReadOnlyCollection memberships, DateTimeOffset at) => + Create(id, DataRequestKind.Erasure, DataRequestOrigin.ClosureFanout, subject, null, group, memberships, at, UserId.SystemActor); + + /// requested → fulfilling for an export; scheduled → fulfilling for an erasure or a closure once its window has passed. + public Result StartFulfilling(DateTimeOffset at, UserId actor) + { + var admitted = (Kind, Status) switch + { + (DataRequestKind.Export, DataRequestStatus.Requested) => true, + (DataRequestKind.Erasure or DataRequestKind.Closure, DataRequestStatus.Scheduled) => ExecuteAt is { } due && at >= due, + _ => false, + }; + return Transition(admitted, DataRequestStatus.Fulfilling, at, actor); + } + + /// fulfilling → awaiting_privileged_step: the tenant-side erasure is done and an operator owes the redaction. + public Result AwaitPrivilegedStep(DateTimeOffset at, UserId actor) => Transition( + Kind == DataRequestKind.Erasure && Status == DataRequestStatus.Fulfilling, DataRequestStatus.AwaitingPrivilegedStep, at, actor); + + /// + /// fulfilling → completed for an export or a closure, awaiting_privileged_step → completed for an + /// erasure; records the complete retained report. + /// + public Result Complete(IReadOnlyCollection retained, DateTimeOffset at, UserId actor) + { + ArgumentNullException.ThrowIfNull(retained); + var report = DataRequestDocuments.WriteResult(retained); + var admitted = report is not null && (Kind, Status) switch + { + (DataRequestKind.Export or DataRequestKind.Closure, DataRequestStatus.Fulfilling) => true, + (DataRequestKind.Erasure, DataRequestStatus.AwaitingPrivilegedStep) => true, + _ => false, + }; + if (!ValidChange(admitted, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + Status = DataRequestStatus.Completed; + CompletedAt = at; + ResultJson = report!; + return Result.Ok(None.Value); + } + + /// fulfilling → failed for an export or an erasure, with its closed reason. + public Result Fail(DataRequestFailureReason reason, DateTimeOffset at, UserId actor) + { + var admitted = Enum.IsDefined(reason) && Status == DataRequestStatus.Fulfilling + && (Kind == DataRequestKind.Export + || (Kind == DataRequestKind.Erasure && reason != DataRequestFailureReason.ExportTooLarge)); + if (!ValidChange(admitted, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + Status = DataRequestStatus.Failed; + FailureReason = reason; + return Result.Ok(None.Value); + } + + /// fulfilling → blocked: an erasure failed its re-check at execution (ADR-0106 § 7). + public Result Block(DataRequestRefusal refusal, DateTimeOffset at, UserId actor) + { + var admitted = Kind == DataRequestKind.Erasure && Status == DataRequestStatus.Fulfilling + && refusal is DataRequestRefusal.BlockedHold or DataRequestRefusal.BlockedLastAdministrator; + if (!ValidChange(admitted, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + Status = DataRequestStatus.Blocked; + LastRefusal = refusal; + return Result.Ok(None.Value); + } + + /// + /// requested → cancelled for an export; scheduled → cancelled for an erasure before its + /// execution time and for a closure until its Begin commits (ADR-0106 § 11). + /// + public Result Cancel(DateTimeOffset at, UserId actor) + { + var admitted = (Kind, Status) switch + { + (DataRequestKind.Export, DataRequestStatus.Requested) => true, + (DataRequestKind.Erasure, DataRequestStatus.Scheduled) => ExecuteAt is { } due && at < due, + (DataRequestKind.Closure, DataRequestStatus.Scheduled) => true, + _ => false, + }; + return Transition(admitted, DataRequestStatus.Cancelled, at, actor); + } + + /// + /// Records a refusal that leaves a scheduled request in place, so the receipt shows the person + /// what to act on (ADR-0106 § 7); repeating the same refusal changes nothing. + /// + public Result RecordRefusal(DataRequestRefusal refusal, DateTimeOffset at, UserId actor) + { + if (Enum.IsDefined(refusal) && Status == DataRequestStatus.Scheduled && LastRefusal == refusal) + { + return Result.Ok(None.Value); + } + + if (!ValidChange(Enum.IsDefined(refusal) && Status == DataRequestStatus.Scheduled, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + LastRefusal = refusal; + return Result.Ok(None.Value); + } + + /// + /// Records that one participant finished, so a resumed job skips it (ADR-0107 § 1); recording a + /// participant again changes nothing. + /// + public Result RecordParticipantCompleted(string participantKey, DateTimeOffset at, UserId actor) + { + if (Status != DataRequestStatus.Fulfilling || !DataRequestLimits.IsParticipantKey(participantKey)) + { + return IdentityFailures.BusinessRule(); + } + + var progress = Progress; + if (progress.ContainsKey(participantKey)) + { + return Result.Ok(None.Value); + } + + var recorded = DataRequestDocuments.WriteProgress( + new Dictionary(progress, StringComparer.Ordinal) { [participantKey] = at }); + if (!ValidChange(recorded is not null, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + ProgressJson = recorded!; + return Result.Ok(None.Value); + } + + /// + /// Records the tenant side's retained report while the request is fulfilling, before the privileged + /// step adds what it retains (ADR-0107 § 6, ADR-0108 § 6). + /// + public Result RecordRetained(IReadOnlyCollection retained, DateTimeOffset at, UserId actor) + { + ArgumentNullException.ThrowIfNull(retained); + var report = DataRequestDocuments.WriteResult(retained); + if (!ValidChange(report is not null && Status == DataRequestStatus.Fulfilling, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + if (string.Equals(report, ResultJson, StringComparison.Ordinal)) + { + return Result.Ok(None.Value); + } + + MarkUpdated(at, actor); + ResultJson = report!; + return Result.Ok(None.Value); + } + + private static Result Create(DataSubjectRequestId id, DataRequestKind kind, DataRequestOrigin origin, + UserId subject, UserId? requester, DataRequestScopeGroup group, IReadOnlyCollection memberships, + DateTimeOffset at, UserId actor) + { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(memberships); + var snapshot = DataRequestDocuments.WriteMemberships(memberships); + if (!StronglyTypedId.IsAssigned(id) || id.Value.Version != 7 || !Enum.IsDefined(kind) + || !ValidPerson(subject) || requester is { } person && !ValidPerson(person) + || snapshot is null || !ValidInstant(at) || at > DateTimeOffset.MaxValue - DataRequestLimits.CancellationWindow) + { + return Result.Fail(IdentityFailures.BusinessRuleError()); + } + + var scheduled = kind != DataRequestKind.Export && origin != DataRequestOrigin.ClosureFanout; + var request = new DataSubjectRequest + { + Id = id, + TenantId = group.TenantId, + OrganizationId = group.OrganizationId, + Kind = kind, + Origin = origin, + SubjectUserId = subject, + RequesterUserId = requester, + MembershipSnapshotJson = snapshot, + Status = kind == DataRequestKind.Export ? DataRequestStatus.Requested + : scheduled ? DataRequestStatus.Scheduled : DataRequestStatus.Fulfilling, + ExecuteAt = scheduled ? at + DataRequestLimits.CancellationWindow : null, + }; + request.MarkCreated(at, actor); + return Result.Ok(request); + } + + private Result Transition(bool admitted, DataRequestStatus next, DateTimeOffset at, UserId actor) + { + if (!ValidChange(admitted, at, actor)) + { + return IdentityFailures.BusinessRule(); + } + + MarkUpdated(at, actor); + Status = next; + return Result.Ok(None.Value); + } + + private bool ValidChange(bool admitted, DateTimeOffset at, UserId actor) => + admitted && !IsTerminal && !IsDeleted && Version != long.MaxValue + && StronglyTypedId.IsAssigned(actor) && ValidInstant(at) && at >= (UpdatedAt ?? CreatedAt); + + private static bool ValidPerson(UserId user) => + StronglyTypedId.IsAssigned(user) && user.Value.Version == 7 && user != UserId.SystemActor; + + private static bool ValidInstant(DateTimeOffset at) => at != default && at.Offset == TimeSpan.Zero; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs index 27a695d3..b1e4dd87 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs @@ -27,3 +27,12 @@ namespace LearnStack.Modules.Identity.Domain; [ValueObject(LearnStackVogenDefaults.IdMask)] public readonly partial record struct FederationTestAttemptId : IStronglyTypedId; + +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct DataSubjectRequestId : IStronglyTypedId; + +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct DataExportArtifactId : IStronglyTypedId; + +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct DataExportTicketId : IStronglyTypedId; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs index 36680822..0ad8e189 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs @@ -6,6 +6,6 @@ namespace LearnStack.Modules.Identity.Domain; public static class IdentityFailures { public static Error Refused() => new(LocalizedMessage.Of("lockey_identity_foundation_refused")); - internal static Result BusinessRule() => Result.Fail( - new Error(LocalizedMessage.Of("lockey_business_rule_violation"))); + internal static Result BusinessRule() => Result.Fail(BusinessRuleError()); + internal static Error BusinessRuleError() => new(LocalizedMessage.Of("lockey_business_rule_violation")); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs new file mode 100644 index 00000000..fccff560 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs @@ -0,0 +1,241 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// Stores a closed vocabulary as its ADR spelling, never as a member name or a number. +internal sealed class ClosedCodeConverter : ValueConverter + where TEnum : struct, Enum +{ + public ClosedCodeConverter(ClosedCodeTable table) + : base(value => table.ToCode(value), code => table.Parse(code)) + { + } +} + +/// +/// data_subject_requests (ADR-0106 § 8, ADR-0107 § 8). The CHECKs bound every closed column and +/// both documents; adds the row policy, the grants and the guard. +/// +internal sealed class DataSubjectRequestConfiguration : IEntityTypeConfiguration +{ + internal const string Table = "data_subject_requests"; + + /// The non-terminal statuses, the predicate of the one-active-slot index (ADR-0106 § 7). + internal const string ActiveFilter = "status IN ('requested','scheduled','fulfilling','awaiting_privileged_step')"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable(Table, table => + { + table.HasCheckConstraint("ck_data_subject_requests_identifiers", + "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid AND (requester_user_id IS NULL OR (uuid_extract_version(requester_user_id)=7 AND requester_user_id <> '00000000-0000-7000-8000-000000000001'::uuid))) IS TRUE"); + table.HasCheckConstraint("ck_data_subject_requests_tenant", + "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.HasCheckConstraint("ck_data_subject_requests_kind", "kind IN ('export','erasure','closure')"); + table.HasCheckConstraint("ck_data_subject_requests_origin", + "((kind IN ('export','erasure') AND origin IN ('self','administrator')) OR (kind = 'erasure' AND origin = 'closure_fanout') OR (kind = 'closure' AND origin = 'self')) IS TRUE"); + table.HasCheckConstraint("ck_data_subject_requests_requester", + "((origin = 'self' AND requester_user_id = subject_user_id) OR (origin = 'administrator' AND requester_user_id IS NOT NULL AND requester_user_id <> subject_user_id) OR (origin = 'closure_fanout' AND requester_user_id IS NULL)) IS TRUE"); + table.HasCheckConstraint("ck_data_subject_requests_status", """ + ((kind = 'export' AND status IN ('requested','fulfilling','completed','failed','cancelled')) + OR (kind = 'erasure' AND status IN ('scheduled','fulfilling','awaiting_privileged_step','completed','blocked','failed','cancelled')) + OR (kind = 'closure' AND status IN ('scheduled','fulfilling','completed','cancelled'))) IS TRUE + """); + table.HasCheckConstraint("ck_data_subject_requests_window", + "((kind IN ('erasure','closure') AND origin <> 'closure_fanout' AND execute_at = created_at + interval '24 hours') OR ((kind = 'export' OR origin = 'closure_fanout') AND execute_at IS NULL)) IS TRUE"); + table.HasCheckConstraint("ck_data_subject_requests_snapshot", """ + CASE WHEN jsonb_typeof(membership_snapshot) = 'array' + THEN jsonb_array_length(membership_snapshot) BETWEEN 1 AND 256 + AND NOT jsonb_path_exists(membership_snapshot, + '$[*] ? (@.type() != "string" || !(@ like_regex "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"))') + ELSE false END + """); + table.HasCheckConstraint("ck_data_subject_requests_progress", """ + CASE WHEN jsonb_typeof(progress) = 'object' + THEN jsonb_array_length(jsonb_path_query_array(progress, '$.keyvalue()')) <= 32 + AND NOT jsonb_path_exists(progress, + '$.keyvalue() ? (!(@.key like_regex "^[a-z][a-z0-9_]{0,31}$") || @.value.type() != "string" || !(@.value like_regex "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{7}Z$"))') + ELSE false END + """); + table.HasCheckConstraint("ck_data_subject_requests_result", """ + CASE WHEN jsonb_typeof(result) = 'object' + THEN NOT jsonb_path_exists(result, + '$.keyvalue() ? (!(@.key like_regex "^(consent_evidence|invitation_record|invitation_envelope|audit_actor_reference|audit_entity_reference|audit_metadata_reference|unscoped_audit_rows|transport_evidence|execution_evidence|provider_event_record|idempotency_cache|attribution_reference|federation_actor_reference|request_receipt|external_copy|unserved_group)$") || @.value.type() != "number" || @.value < 0 || @.value > 9007199254740991 || @.value.floor() != @.value)') + ELSE false END + """); + table.HasCheckConstraint("ck_data_subject_requests_outcome", """ + ((status = 'completed') = (completed_at IS NOT NULL) + AND (completed_at IS NULL OR (isfinite(completed_at) AND completed_at >= created_at)) + AND ((status = 'failed' AND failure_reason IN ('export_too_large','execution_failed') + AND (failure_reason <> 'export_too_large' OR kind = 'export')) + OR (status <> 'failed' AND failure_reason IS NULL)) + AND (last_refusal IS NULL OR last_refusal IN ('blocked_window','blocked_hold','blocked_last_administrator')) + AND (status <> 'blocked' OR last_refusal IN ('blocked_hold','blocked_last_administrator'))) IS TRUE + """); + table.HasCheckConstraint("ck_data_subject_requests_times", + "(isfinite(created_at) AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at)) AND (execute_at IS NULL OR isfinite(execute_at))) IS TRUE"); + table.HasCheckConstraint("ck_data_subject_requests_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + }); + builder.HasKey(entity => entity.Id).HasName("pk_data_subject_requests"); + builder.Property(entity => entity.Id) + .HasConversion().ValueGeneratedNever(); + builder.Scope(Table); + builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id }).HasName("ux_data_subject_requests_tenant_id_id"); + builder.Property(entity => entity.Kind).HasConversion(new ClosedCodeConverter(DataRequestCodes.Kinds)) + .HasColumnType("text"); + builder.Property(entity => entity.Origin).HasConversion(new ClosedCodeConverter(DataRequestCodes.Origins)) + .HasColumnType("text"); + builder.Property(entity => entity.Status).HasConversion(new ClosedCodeConverter(DataRequestCodes.Statuses)) + .HasColumnType("text"); + builder.Property(entity => entity.LastRefusal) + .HasConversion(new ClosedCodeConverter(DataRequestCodes.Refusals)).HasColumnType("text"); + builder.Property(entity => entity.FailureReason) + .HasConversion(new ClosedCodeConverter(DataRequestCodes.FailureReasons)).HasColumnType("text"); + builder.Property(entity => entity.SubjectUserId).HasConversion(); + builder.Property(entity => entity.RequesterUserId).HasConversion(); + builder.Property(entity => entity.MembershipSnapshotJson).HasColumnName("membership_snapshot").HasColumnType("jsonb").IsRequired(); + builder.Property(entity => entity.ProgressJson).HasColumnName("progress").HasColumnType("jsonb") + .HasDefaultValue(DataRequestDocuments.EmptyObject).IsRequired(); + builder.Property(entity => entity.ResultJson).HasColumnName("result").HasColumnType("jsonb") + .HasDefaultValue(DataRequestDocuments.EmptyObject).IsRequired(); + builder.Ignore(entity => entity.Group); + builder.Ignore(entity => entity.SnapshotMembershipIds); + builder.Ignore(entity => entity.Progress); + builder.Ignore(entity => entity.RetainedReport); + builder.Ignore(entity => entity.IsTerminal); + builder.HasOne().WithMany().HasForeignKey(entity => entity.SubjectUserId) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_data_subject_requests_subject"); + builder.HasIndex(entity => entity.SubjectUserId).HasDatabaseName("ix_data_subject_requests_subject_user_id"); + builder.HasOne().WithMany().HasForeignKey(entity => entity.RequesterUserId) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_data_subject_requests_requester"); + builder.HasIndex(entity => entity.RequesterUserId).HasDatabaseName("ix_data_subject_requests_requester_user_id"); + // ADR-0106 § 7: one non-terminal request per kind, subject and group, so two concurrent creations + // cannot both pass; every terminal status frees the slot. + builder.HasIndex(entity => new { entity.TenantId, entity.OrganizationId, entity.SubjectUserId, entity.Kind }) + .IsUnique().AreNullsDistinct(false).HasFilter(ActiveFilter).HasDatabaseName("ux_data_subject_requests_active"); + builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage.", + nameof(DataSubjectRequest.Id), nameof(DataSubjectRequest.TenantId), nameof(DataSubjectRequest.OrganizationId), + nameof(DataSubjectRequest.SubjectUserId), nameof(DataSubjectRequest.RequesterUserId), + nameof(DataSubjectRequest.MembershipSnapshotJson)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts.", + nameof(DataSubjectRequest.Kind), nameof(DataSubjectRequest.Origin), nameof(DataSubjectRequest.Status), + nameof(DataSubjectRequest.ExecuteAt), nameof(DataSubjectRequest.ProgressJson), nameof(DataSubjectRequest.ResultJson), + nameof(DataSubjectRequest.LastRefusal), nameof(DataSubjectRequest.FailureReason), nameof(DataSubjectRequest.CompletedAt)); + } +} + +/// +/// data_export_artifacts (ADR-0107 § 4): receipt-safe metadata of an encrypted bundle, mirroring +/// its request's group and subject. +/// +internal sealed class DataExportArtifactConfiguration : IEntityTypeConfiguration +{ + internal const string Table = "data_export_artifacts"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable(Table, table => + { + table.HasCheckConstraint("ck_data_export_artifacts_identifiers", + "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + table.HasCheckConstraint("ck_data_export_artifacts_tenant", + "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.HasCheckConstraint("ck_data_export_artifacts_status", "status IN ('available','revoked','expired','purged')"); + table.HasCheckConstraint("ck_data_export_artifacts_size", + "byte_count BETWEEN 1 AND 67108864 AND chunk_count BETWEEN 1 AND 512 AND chunk_count = (byte_count + 131071) / 131072"); + table.HasCheckConstraint("ck_data_export_artifacts_key_version", "key_version COLLATE \"C\" ~ '^[A-Za-z0-9_-]{1,32}$'"); + table.HasCheckConstraint("ck_data_export_artifacts_times", + "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + table.HasCheckConstraint("ck_data_export_artifacts_lifecycle", + "((status IN ('revoked','purged')) = (purged_at IS NOT NULL) AND (purged_at IS NULL OR (isfinite(purged_at) AND purged_at >= created_at))) IS TRUE"); + table.HasCheckConstraint("ck_data_export_artifacts_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + }); + builder.HasKey(entity => entity.Id).HasName("pk_data_export_artifacts"); + builder.Property(entity => entity.Id) + .HasConversion().ValueGeneratedNever(); + builder.Scope(Table); + builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id }).HasName("ux_data_export_artifacts_tenant_id_id"); + builder.Property(entity => entity.RequestId) + .HasConversion(); + builder.Property(entity => entity.SubjectUserId).HasConversion(); + builder.Property(entity => entity.Status) + .HasConversion(new ClosedCodeConverter(DataRequestCodes.ArtifactStatuses)).HasColumnType("text"); + builder.Property(entity => entity.KeyVersion).HasMaxLength(DataRequestLimits.MaximumKeyVersionLength).UseCollation("C"); + builder.HasOne().WithMany().HasForeignKey(entity => new { entity.TenantId, entity.RequestId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_data_export_artifacts_request"); + // One artifact per export request; the index also supports the request foreign key. + builder.HasIndex(entity => new { entity.TenantId, entity.RequestId }).IsUnique().HasDatabaseName("ux_data_export_artifacts_request"); + // ADR-0107 § 4: a subject has at most one available artifact per group. + builder.HasIndex(entity => new { entity.TenantId, entity.OrganizationId, entity.SubjectUserId }) + .IsUnique().AreNullsDistinct(false).HasFilter("status = 'available'").HasDatabaseName("ux_data_export_artifacts_available"); + builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "A person's export receipt: the group, the request and the subject it was generated for.", + nameof(DataExportArtifact.Id), nameof(DataExportArtifact.TenantId), nameof(DataExportArtifact.OrganizationId), + nameof(DataExportArtifact.RequestId), nameof(DataExportArtifact.SubjectUserId)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key.", + nameof(DataExportArtifact.Status), nameof(DataExportArtifact.ByteCount), nameof(DataExportArtifact.ChunkCount), + nameof(DataExportArtifact.KeyVersion), nameof(DataExportArtifact.ExpiresAt), nameof(DataExportArtifact.PurgedAt)); + } +} + +/// +/// data_export_tickets (ADR-0107 § 4): digest-only download cursors bound to a session; the +/// application role may set only the consumed marker. +/// +internal sealed class DataExportTicketConfiguration : IEntityTypeConfiguration +{ + internal const string Table = "data_export_tickets"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable(Table, table => + { + table.HasCheckConstraint("ck_data_export_tickets_identifiers", + "(uuid_extract_version(id)=7 AND uuid_extract_version(created_by)=7 AND created_by <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + table.HasCheckConstraint("ck_data_export_tickets_tenant", + "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.HasCheckConstraint("ck_data_export_tickets_digests", "octet_length(digest) = 32 AND octet_length(session_binding_digest) = 32"); + table.HasCheckConstraint("ck_data_export_tickets_times", + "(isfinite(created_at) AND expires_at = created_at + interval '15 minutes' AND (consumed_at IS NULL OR (consumed_at >= created_at AND consumed_at < expires_at))) IS TRUE"); + }); + builder.HasKey(entity => entity.Id).HasName("pk_data_export_tickets"); + builder.Property(entity => entity.Id) + .HasConversion().ValueGeneratedNever(); + builder.Scope(Table); + builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id }).HasName("ux_data_export_tickets_tenant_id_id"); + builder.Property(entity => entity.ArtifactId) + .HasConversion(); + builder.Property(entity => entity.CreatedBy).HasConversion(); + foreach (var digest in new[] { nameof(DataExportTicket.Digest), nameof(DataExportTicket.SessionBindingDigest) }) + builder.Property(digest).HasConversion( + value => Convert.FromHexString(value), + value => Convert.ToHexStringLower(value)).HasColumnType("bytea"); + builder.HasOne().WithMany().HasForeignKey(entity => new { entity.TenantId, entity.ArtifactId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_data_export_tickets_artifact"); + builder.HasIndex(entity => new { entity.TenantId, entity.ArtifactId }).HasDatabaseName("ix_data_export_tickets_tenant_id_artifact_id"); + builder.HasIndex(entity => new { entity.TenantId, entity.Digest }).IsUnique().HasDatabaseName("ux_data_export_tickets_digest"); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests.", + nameof(DataExportTicket.Id), nameof(DataExportTicket.TenantId), nameof(DataExportTicket.OrganizationId), + nameof(DataExportTicket.ArtifactId), nameof(DataExportTicket.CreatedBy), nameof(DataExportTicket.Digest), + nameof(DataExportTicket.SessionBindingDigest)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, "Record when the ticket was minted.", nameof(DataExportTicket.CreatedAt)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "The ticket's fixed expiry and the instant its download finished.", + nameof(DataExportTicket.ExpiresAt), nameof(DataExportTicket.ConsumedAt)); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs new file mode 100644 index 00000000..2d365293 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs @@ -0,0 +1,445 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// P03-10 Step 1 storage for subject data requests: the SQL-only chunk table, the canonical +/// organization-scoped row policy on all four tables, the exact grants of ADR-0107 § 8, the +/// organization immutability and parent-scope triggers, and the guards that hold the request status +/// machine of ADR-0106 § 8 and the artifact, ticket and chunk lifecycles of ADR-0107 § 4. +/// +/// +/// +/// The row policy is Database Standards' canonical organization-scoped template, one AND-ed +/// permissive policy with an explicit WITH CHECK and the two restrictive write guards, written once +/// per table by the loop below; it carries no owner arm. The retained own-scope function of +/// ADR-0106 § 9 adds its owner arm with its own migration. +/// +/// +/// Writers. Every guard admits only the application role. learnstack_platform holds the +/// closed-column SELECT and the status, row-version, completion and result UPDATE on +/// data_subject_requests that ADR-0107 § 8 lists and nothing on the other three tables; the +/// request guard still refuses its writes until the operator acts that own them (Step 2's +/// complete_erasure, Step 3's closure Begin and Finalize) add their arm with their witnesses. +/// +/// +/// Fences. A request write holds the Identity tenant fence (shared at least), and its creation +/// also holds the subject's exclusive User fence, under which Membership admission runs, so the frozen +/// Membership snapshot is exactly the subject's Memberships in the group when the row commits. +/// +/// +internal static class DataRequestStorageDdl +{ + internal static readonly string[] Tables = + ["data_subject_requests", "data_export_artifacts", "data_export_tickets", "data_export_chunks"]; + + internal static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(ChunkTable); + foreach (var table in Tables) + { + migration.Sql($""" + ALTER TABLE public.{table} ENABLE ROW LEVEL SECURITY; + ALTER TABLE public.{table} FORCE ROW LEVEL SECURITY; + CREATE POLICY {table}_isolation ON public.{table} + USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid + AND (organization_id IS NULL + OR organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid + OR NULLIF(current_setting('app.scope', true), '') = 'tenant')) + 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)); + CREATE POLICY {table}_org_write_guard ON public.{table} AS RESTRICTIVE FOR UPDATE + USING ((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); + CREATE POLICY {table}_org_delete_guard ON public.{table} AS RESTRICTIVE FOR DELETE + USING ((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); + CREATE TRIGGER tg_{table}_organization_id_immutable BEFORE UPDATE ON public.{table} + FOR EACH ROW EXECUTE FUNCTION public.fn_organization_id_immutable(); + """); + } + + migration.Sql(Grants); + migration.Sql(ArtifactParentScope); + migration.Sql(TicketParentScope); + migration.Sql(ChunkParentScope); + migration.Sql(RequestGuard); + migration.Sql(ArtifactGuard); + migration.Sql(TicketGuard); + migration.Sql(ChunkGuard); + migration.Sql(Completeness); + } + + /// + /// The ciphertext rows: SQL-only, never tracked by EF (so never captured into an audit snapshot), and + /// bounded by ADR-0107 § 4's 12-byte nonce, 16-byte tag and 128 KiB chunk. + /// + private const string ChunkTable = """ + CREATE TABLE public.data_export_chunks ( + tenant_id uuid NOT NULL, + organization_id uuid NULL, + artifact_id uuid NOT NULL, + chunk_index integer NOT NULL, + nonce bytea NOT NULL, + ciphertext bytea NOT NULL, + tag bytea NOT NULL, + CONSTRAINT pk_data_export_chunks PRIMARY KEY (tenant_id, artifact_id, chunk_index), + CONSTRAINT fk_data_export_chunks_artifact FOREIGN KEY (tenant_id, artifact_id) + REFERENCES public.data_export_artifacts (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT ck_data_export_chunks_tenant + CHECK (tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)), + CONSTRAINT ck_data_export_chunks_index CHECK (chunk_index >= 0 AND chunk_index < 512), + CONSTRAINT ck_data_export_chunks_nonce CHECK (octet_length(nonce) = 12), + CONSTRAINT ck_data_export_chunks_tag CHECK (octet_length(tag) = 16), + CONSTRAINT ck_data_export_chunks_ciphertext CHECK (octet_length(ciphertext) BETWEEN 1 AND 131072) + ); + -- AES-GCM ciphertext does not compress; store it out of line without trying. + ALTER TABLE public.data_export_chunks ALTER COLUMN ciphertext SET STORAGE EXTERNAL; + CREATE INDEX ix_data_export_chunks_tenant_id_organization_id ON public.data_export_chunks (tenant_id, organization_id); + """; + + /// ADR-0107 § 8, exactly. Column-limited UPDATE grants are invisible to table-privilege views. + private const string Grants = """ + REVOKE ALL ON public.data_subject_requests, public.data_export_artifacts, public.data_export_tickets, public.data_export_chunks + FROM PUBLIC, learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress, learnstack_identity_rebind; + GRANT SELECT, INSERT ON public.data_subject_requests TO learnstack_app; + GRANT UPDATE (status, row_version, progress, result, last_refusal, failure_reason, completed_at, updated_at, updated_by) + ON public.data_subject_requests TO learnstack_app; + GRANT SELECT, INSERT ON public.data_export_artifacts TO learnstack_app; + GRANT UPDATE (status, purged_at, row_version, updated_at, updated_by) ON public.data_export_artifacts TO learnstack_app; + GRANT SELECT, INSERT ON public.data_export_tickets TO learnstack_app; + GRANT UPDATE (consumed_at) ON public.data_export_tickets TO learnstack_app; + GRANT SELECT, INSERT, DELETE ON public.data_export_chunks TO learnstack_app; + -- learnstack_platform is BYPASSRLS, so these grants are its whole bound: no requester, no actor + -- stamps, nothing on the artifact, ticket or chunk tables. + GRANT SELECT (id, tenant_id, organization_id, kind, origin, subject_user_id, status, membership_snapshot, execute_at, + progress, result, last_refusal, failure_reason, completed_at, created_at, row_version) + ON public.data_subject_requests TO learnstack_platform; + GRANT UPDATE (status, row_version, completed_at, result) ON public.data_subject_requests TO learnstack_platform; + """; + + // Database Standards § Parent organization mirrors, in its canonical form, once per child. Each is a literal: + // a table name composed into a statement is one the audit and entitlement source scans cannot read. + + /// An artifact mirrors its export request's group. + private const string ArtifactParentScope = """ + CREATE FUNCTION public.fn_data_export_artifacts_parent_scope() RETURNS trigger + LANGUAGE plpgsql + SECURITY INVOKER + SET search_path = pg_catalog + AS $$ + DECLARE + parent_organization_id uuid; + BEGIN + SELECT parent.organization_id INTO parent_organization_id + FROM public.data_subject_requests AS parent + WHERE parent.tenant_id = NEW.tenant_id AND parent.id = NEW.request_id + FOR KEY SHARE; + + IF NOT FOUND OR parent_organization_id IS DISTINCT FROM NEW.organization_id THEN + RAISE EXCEPTION 'parent scope is unavailable or mismatched (table %)', TG_TABLE_NAME + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END; + $$; + REVOKE ALL ON FUNCTION public.fn_data_export_artifacts_parent_scope() FROM PUBLIC; + CREATE TRIGGER tg_data_export_artifacts_parent_scope + BEFORE INSERT OR UPDATE ON public.data_export_artifacts + FOR EACH ROW EXECUTE FUNCTION public.fn_data_export_artifacts_parent_scope(); + """; + + /// A ticket mirrors its artifact's group. + private const string TicketParentScope = """ + CREATE FUNCTION public.fn_data_export_tickets_parent_scope() RETURNS trigger + LANGUAGE plpgsql + SECURITY INVOKER + SET search_path = pg_catalog + AS $$ + DECLARE + parent_organization_id uuid; + BEGIN + SELECT parent.organization_id INTO parent_organization_id + FROM public.data_export_artifacts AS parent + WHERE parent.tenant_id = NEW.tenant_id AND parent.id = NEW.artifact_id + FOR KEY SHARE; + + IF NOT FOUND OR parent_organization_id IS DISTINCT FROM NEW.organization_id THEN + RAISE EXCEPTION 'parent scope is unavailable or mismatched (table %)', TG_TABLE_NAME + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END; + $$; + REVOKE ALL ON FUNCTION public.fn_data_export_tickets_parent_scope() FROM PUBLIC; + CREATE TRIGGER tg_data_export_tickets_parent_scope + BEFORE INSERT OR UPDATE ON public.data_export_tickets + FOR EACH ROW EXECUTE FUNCTION public.fn_data_export_tickets_parent_scope(); + """; + + /// A chunk mirrors its artifact's group. + private const string ChunkParentScope = """ + CREATE FUNCTION public.fn_data_export_chunks_parent_scope() RETURNS trigger + LANGUAGE plpgsql + SECURITY INVOKER + SET search_path = pg_catalog + AS $$ + DECLARE + parent_organization_id uuid; + BEGIN + SELECT parent.organization_id INTO parent_organization_id + FROM public.data_export_artifacts AS parent + WHERE parent.tenant_id = NEW.tenant_id AND parent.id = NEW.artifact_id + FOR KEY SHARE; + + IF NOT FOUND OR parent_organization_id IS DISTINCT FROM NEW.organization_id THEN + RAISE EXCEPTION 'parent scope is unavailable or mismatched (table %)', TG_TABLE_NAME + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END; + $$; + REVOKE ALL ON FUNCTION public.fn_data_export_chunks_parent_scope() FROM PUBLIC; + CREATE TRIGGER tg_data_export_chunks_parent_scope + BEFORE INSERT OR UPDATE ON public.data_export_chunks + FOR EACH ROW EXECUTE FUNCTION public.fn_data_export_chunks_parent_scope(); + """; + + /// + /// The request guard: the immutable snapshot, the initial state per kind and origin, and ADR-0106 + /// § 8's application-role transitions. Every refusal is written as (condition) IS NOT FALSE, + /// so a condition that is NULL refuses. + /// + private const string RequestGuard = """ + CREATE FUNCTION public.fn_identity_data_request_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $guard$ + DECLARE snapshot_count integer; snapshot_distinct integer; matched integer; held integer; + BEGIN + IF (session_user <> 'learnstack_app' OR current_user <> 'learnstack_app' + OR TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_subject_requests' + OR TG_OP NOT IN ('INSERT','UPDATE')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request mutation refused.' USING ERRCODE = '23514'; END IF; + PERFORM public.fn_identity_assert_tenant_fence(NEW.tenant_id, false); + IF TG_OP = 'INSERT' THEN + IF public.fn_identity_lock_held('user', NEW.subject_user_id, true) IS NOT TRUE THEN + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301', CONSTRAINT = 'identity_user_fence'; + END IF; + IF (NEW.row_version IS DISTINCT FROM 0 OR NEW.updated_at IS NOT NULL OR NEW.updated_by IS NOT NULL + OR NEW.progress IS DISTINCT FROM '{}'::jsonb OR NEW.result IS DISTINCT FROM '{}'::jsonb + OR NEW.last_refusal IS NOT NULL OR NEW.failure_reason IS NOT NULL OR NEW.completed_at IS NOT NULL + OR NEW.status IS DISTINCT FROM (CASE WHEN NEW.kind = 'export' THEN 'requested' + WHEN NEW.origin = 'closure_fanout' THEN 'fulfilling' ELSE 'scheduled' END) + OR NEW.created_by IS DISTINCT FROM COALESCE(NEW.requester_user_id, '00000000-0000-7000-8000-000000000001'::uuid) + OR NOT isfinite(NEW.created_at) + OR NEW.created_at > transaction_timestamp() + interval '5 minutes' + OR NEW.created_at < transaction_timestamp() - interval '5 minutes') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request initial state refused.' USING ERRCODE = '23514'; END IF; + -- The frozen snapshot is exactly the subject's Memberships of any status in the group. + SELECT count(*), count(DISTINCT element) INTO snapshot_count, snapshot_distinct + FROM jsonb_array_elements_text(NEW.membership_snapshot) AS element; + SELECT count(*) INTO matched FROM public.memberships AS member + WHERE member.tenant_id = NEW.tenant_id AND member.user_id = NEW.subject_user_id + AND member.organization_id IS NOT DISTINCT FROM NEW.organization_id + AND member.id::text IN (SELECT jsonb_array_elements_text(NEW.membership_snapshot)); + SELECT count(*) INTO held FROM public.memberships AS member + WHERE member.tenant_id = NEW.tenant_id AND member.user_id = NEW.subject_user_id + AND member.organization_id IS NOT DISTINCT FROM NEW.organization_id; + IF (snapshot_count < 1 OR snapshot_distinct <> snapshot_count OR matched <> snapshot_count + OR held <> snapshot_count) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request snapshot refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + IF (ROW(NEW.id, NEW.tenant_id, NEW.organization_id, NEW.kind, NEW.origin, NEW.subject_user_id, + NEW.requester_user_id, NEW.membership_snapshot, NEW.execute_at, NEW.created_at, NEW.created_by, + NEW.deleted_at, NEW.deleted_by) + IS DISTINCT FROM ROW(OLD.id, OLD.tenant_id, OLD.organization_id, OLD.kind, OLD.origin, OLD.subject_user_id, + OLD.requester_user_id, OLD.membership_snapshot, OLD.execute_at, OLD.created_at, OLD.created_by, + OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 + OR NEW.updated_at IS NULL OR NEW.updated_by IS NULL OR NOT isfinite(NEW.updated_at) + OR NEW.updated_at < COALESCE(OLD.updated_at, OLD.created_at) + OR NEW.updated_at > transaction_timestamp() + interval '5 minutes') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request immutable state refused.' USING ERRCODE = '23514'; END IF; + IF (OLD.status IN ('completed','blocked','failed','cancelled')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request is terminal.' USING ERRCODE = '23514'; END IF; + -- Progress only grows, and only while the request is fulfilling (ADR-0107 § 1). + IF (NEW.progress IS DISTINCT FROM OLD.progress + AND NOT (OLD.status = 'fulfilling' AND NEW.progress @> OLD.progress)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request progress refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.result IS DISTINCT FROM OLD.result AND OLD.status <> 'fulfilling') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.last_refusal IS DISTINCT FROM OLD.last_refusal + AND NOT ((OLD.status = 'scheduled' AND NEW.status = 'scheduled') + OR (OLD.status = 'fulfilling' AND NEW.status = 'blocked'))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.failure_reason IS DISTINCT FROM OLD.failure_reason + AND NOT (OLD.status = 'fulfilling' AND NEW.status = 'failed')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request failure record refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at + AND NOT (NEW.status = 'completed' AND NEW.completed_at = NEW.updated_at)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + -- ADR-0106 § 8, the application role's arrows. An erasure's awaiting_privileged_step -> completed and a + -- closure's Begin and Finalize are operator acts; they are refused here until their steps add them. + IF (NEW.status IS DISTINCT FROM OLD.status AND NOT ( + (OLD.kind = 'export' AND ((OLD.status = 'requested' AND NEW.status IN ('fulfilling','cancelled')) + OR (OLD.status = 'fulfilling' AND NEW.status IN ('completed','failed')))) + OR (OLD.kind = 'erasure' AND ((OLD.status = 'scheduled' AND NEW.status = 'fulfilling' + AND clock_timestamp() >= OLD.execute_at) + OR (OLD.status = 'scheduled' AND NEW.status = 'cancelled' AND clock_timestamp() < OLD.execute_at) + OR (OLD.status = 'fulfilling' AND NEW.status IN ('awaiting_privileged_step','blocked','failed')))) + OR (OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'cancelled'))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END $guard$; + REVOKE ALL ON FUNCTION public.fn_identity_data_request_guard() FROM PUBLIC; + CREATE TRIGGER tg_data_subject_requests_mutation_guard BEFORE INSERT OR UPDATE OR DELETE ON public.data_subject_requests + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_request_guard(); + """; + + private const string ArtifactGuard = """ + CREATE FUNCTION public.fn_identity_data_export_artifact_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $guard$ + DECLARE request_kind text; request_subject uuid; request_status text; request_fresh boolean; + BEGIN + IF (session_user <> 'learnstack_app' OR current_user <> 'learnstack_app' + OR TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_export_artifacts' + OR TG_OP NOT IN ('INSERT','UPDATE')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact mutation refused.' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF (NEW.status IS DISTINCT FROM 'available' OR NEW.row_version IS DISTINCT FROM 0 + OR NEW.updated_at IS NOT NULL OR NEW.updated_by IS NOT NULL OR NEW.purged_at IS NOT NULL + OR NOT isfinite(NEW.created_at) + OR NEW.created_at > transaction_timestamp() + interval '5 minutes' + OR NEW.created_at < transaction_timestamp() - interval '5 minutes') IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact initial state refused.' USING ERRCODE = '23514'; END IF; + -- The artifact of an export that is fulfilling, or that this transaction is completing. + SELECT request.kind, request.subject_user_id, request.status, request.xmin = pg_current_xact_id()::text::xid + INTO request_kind, request_subject, request_status, request_fresh + FROM public.data_subject_requests AS request + WHERE request.tenant_id = NEW.tenant_id AND request.id = NEW.request_id; + IF (NOT FOUND OR request_kind <> 'export' OR request_subject IS DISTINCT FROM NEW.subject_user_id + OR NOT (request_status = 'fulfilling' OR (request_status = 'completed' AND request_fresh))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact request refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + IF (ROW(NEW.id, NEW.tenant_id, NEW.organization_id, NEW.request_id, NEW.subject_user_id, NEW.byte_count, + NEW.chunk_count, NEW.key_version, NEW.expires_at, NEW.created_at, NEW.created_by, NEW.deleted_at, NEW.deleted_by) + IS DISTINCT FROM ROW(OLD.id, OLD.tenant_id, OLD.organization_id, OLD.request_id, OLD.subject_user_id, OLD.byte_count, + OLD.chunk_count, OLD.key_version, OLD.expires_at, OLD.created_at, OLD.created_by, OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 + OR NEW.updated_at IS NULL OR NEW.updated_by IS NULL OR NOT isfinite(NEW.updated_at) + OR NEW.updated_at < COALESCE(OLD.updated_at, OLD.created_at) + OR NEW.updated_at > transaction_timestamp() + interval '5 minutes') IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact immutable state refused.' USING ERRCODE = '23514'; END IF; + -- ADR-0107 § 4: revoke an unexpired artifact; expire or purge only after its expiry. + IF (NOT ((OLD.status = 'available' AND NEW.status = 'revoked' AND clock_timestamp() < OLD.expires_at + AND NEW.purged_at = NEW.updated_at) + OR (OLD.status = 'available' AND NEW.status = 'expired' AND clock_timestamp() >= OLD.expires_at + AND NEW.purged_at IS NULL) + OR (OLD.status IN ('available','expired') AND NEW.status = 'purged' AND clock_timestamp() >= OLD.expires_at + AND NEW.purged_at = NEW.updated_at))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact transition refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END $guard$; + REVOKE ALL ON FUNCTION public.fn_identity_data_export_artifact_guard() FROM PUBLIC; + CREATE TRIGGER tg_data_export_artifacts_mutation_guard BEFORE INSERT OR UPDATE OR DELETE ON public.data_export_artifacts + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_export_artifact_guard(); + """; + + private const string TicketGuard = """ + CREATE FUNCTION public.fn_identity_data_export_ticket_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $guard$ + DECLARE artifact_subject uuid; artifact_status text; artifact_expires timestamptz; + BEGIN + IF (session_user <> 'learnstack_app' OR current_user <> 'learnstack_app' + OR TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_export_tickets' + OR TG_OP NOT IN ('INSERT','UPDATE')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export ticket mutation refused.' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF (NEW.consumed_at IS NOT NULL OR NOT isfinite(NEW.created_at) + OR NEW.created_at > transaction_timestamp() + interval '5 minutes' + OR NEW.created_at < transaction_timestamp() - interval '5 minutes') IS NOT FALSE + THEN RAISE EXCEPTION 'Data export ticket initial state refused.' USING ERRCODE = '23514'; END IF; + -- Subject-only retrieval of a readable artifact (ADR-0107 § 4). + SELECT artifact.subject_user_id, artifact.status, artifact.expires_at + INTO artifact_subject, artifact_status, artifact_expires + FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = NEW.tenant_id AND artifact.id = NEW.artifact_id; + IF (NOT FOUND OR artifact_status <> 'available' OR clock_timestamp() >= artifact_expires + OR artifact_subject IS DISTINCT FROM NEW.created_by) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export ticket artifact refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + IF (ROW(NEW.id, NEW.tenant_id, NEW.organization_id, NEW.artifact_id, NEW.digest, NEW.session_binding_digest, + NEW.created_at, NEW.created_by, NEW.expires_at) + IS DISTINCT FROM ROW(OLD.id, OLD.tenant_id, OLD.organization_id, OLD.artifact_id, OLD.digest, + OLD.session_binding_digest, OLD.created_at, OLD.created_by, OLD.expires_at) + OR OLD.consumed_at IS NOT NULL OR NEW.consumed_at IS NULL + OR NEW.consumed_at < OLD.created_at OR NEW.consumed_at >= OLD.expires_at + OR NEW.consumed_at > transaction_timestamp() + interval '5 minutes' + OR clock_timestamp() >= OLD.expires_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export ticket consumption refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END $guard$; + REVOKE ALL ON FUNCTION public.fn_identity_data_export_ticket_guard() FROM PUBLIC; + CREATE TRIGGER tg_data_export_tickets_mutation_guard BEFORE INSERT OR UPDATE OR DELETE ON public.data_export_tickets + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_export_ticket_guard(); + """; + + private const string ChunkGuard = """ + CREATE FUNCTION public.fn_identity_data_export_chunk_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $guard$ + DECLARE artifact_status text; artifact_chunks integer; + BEGIN + IF (session_user <> 'learnstack_app' OR current_user <> 'learnstack_app' + OR TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_export_chunks' + OR TG_OP NOT IN ('INSERT','DELETE')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export chunk mutation refused.' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + SELECT artifact.status, artifact.chunk_count INTO artifact_status, artifact_chunks + FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = NEW.tenant_id AND artifact.id = NEW.artifact_id; + IF (NOT FOUND OR artifact_status <> 'available' OR NEW.chunk_index >= artifact_chunks) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export chunk refused.' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END $guard$; + REVOKE ALL ON FUNCTION public.fn_identity_data_export_chunk_guard() FROM PUBLIC; + CREATE TRIGGER tg_data_export_chunks_mutation_guard BEFORE INSERT OR UPDATE OR DELETE ON public.data_export_chunks + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_export_chunk_guard(); + """; + + /// + /// At commit, an available artifact holds exactly its chunk count and a revoked or purged one holds + /// none: a bundle is never half-stored and a revocation never leaves ciphertext behind. + /// + private const string Completeness = """ + CREATE FUNCTION public.fn_identity_data_export_completeness() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $complete$ + DECLARE target_tenant uuid; target_artifact uuid; artifact_status text; artifact_chunks integer; stored bigint; + BEGIN + IF TG_TABLE_NAME = 'data_export_artifacts' THEN + target_tenant := NEW.tenant_id; target_artifact := NEW.id; + ELSE + target_tenant := OLD.tenant_id; target_artifact := OLD.artifact_id; + END IF; + SELECT artifact.status, artifact.chunk_count INTO artifact_status, artifact_chunks + FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = target_tenant AND artifact.id = target_artifact; + SELECT count(*) INTO stored FROM public.data_export_chunks AS chunk + WHERE chunk.tenant_id = target_tenant AND chunk.artifact_id = target_artifact; + IF (artifact_status IS NULL + OR (artifact_status = 'available' AND stored <> artifact_chunks) + OR (artifact_status IN ('revoked','purged') AND stored <> 0)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact chunks are inconsistent.' + USING ERRCODE = '23514', CONSTRAINT = 'data_export_artifact_chunks'; END IF; + RETURN NULL; + END $complete$; + REVOKE ALL ON FUNCTION public.fn_identity_data_export_completeness() FROM PUBLIC; + CREATE CONSTRAINT TRIGGER tg_data_export_artifacts_complete AFTER INSERT OR UPDATE ON public.data_export_artifacts + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_export_completeness(); + CREATE CONSTRAINT TRIGGER tg_data_export_chunks_complete AFTER DELETE ON public.data_export_chunks + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.fn_identity_data_export_completeness(); + """; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContext.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContext.cs index f66e4899..25d81dd4 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContext.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContext.cs @@ -24,6 +24,9 @@ public sealed class IdentityDbContext(DbContextOptions option public DbSet Invitations => Set(); public DbSet ProviderEventTargets => Set(); public DbSet FederationConnections => Set(); + public DbSet DataSubjectRequests => Set(); + public DbSet DataExportArtifacts => Set(); + public DbSet DataExportTickets => Set(); public IdentityAuthorityId CurrentIdentityAuthorityId => identityScope.Current is { } current && current.Generation > 0 diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs new file mode 100644 index 00000000..bce89d68 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs @@ -0,0 +1,1762 @@ +// +using System; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +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.Modules.Identity.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(IdentityDbContext))] + [Migration("20261122013001_add_data_subject_requests")] + partial class add_data_subject_requests + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("LearnStack:PersonalData:Validated", true) + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportArtifact", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("ByteCount") + .HasColumnType("bigint") + .HasColumnName("byte_count") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("ChunkCount") + .HasColumnType("integer") + .HasColumnName("chunk_count") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("KeyVersion") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("key_version") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("PurgedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("purged_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("RequestId") + .HasColumnType("uuid") + .HasColumnName("request_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("SubjectUserId") + .HasColumnType("uuid") + .HasColumnName("subject_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_data_export_artifacts"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_export_artifacts_tenant_id_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_export_artifacts_tenant_id_organization_id"); + + b.HasIndex("TenantId", "RequestId") + .IsUnique() + .HasDatabaseName("ux_data_export_artifacts_request"); + + b.HasIndex("TenantId", "OrganizationId", "SubjectUserId") + .IsUnique() + .HasDatabaseName("ux_data_export_artifacts_available") + .HasFilter("status = 'available'"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "OrganizationId", "SubjectUserId"), false); + + b.ToTable("data_export_artifacts", null, t => + { + t.HasCheckConstraint("ck_data_export_artifacts_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_key_version", "key_version COLLATE \"C\" ~ '^[A-Za-z0-9_-]{1,32}$'"); + + t.HasCheckConstraint("ck_data_export_artifacts_lifecycle", "((status IN ('revoked','purged')) = (purged_at IS NOT NULL) AND (purged_at IS NULL OR (isfinite(purged_at) AND purged_at >= created_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_data_export_artifacts_size", "byte_count BETWEEN 1 AND 67108864 AND chunk_count BETWEEN 1 AND 512 AND chunk_count = (byte_count + 131071) / 131072"); + + t.HasCheckConstraint("ck_data_export_artifacts_status", "status IN ('available','revoked','expired','purged')"); + + t.HasCheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportTicket", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ArtifactId") + .HasColumnType("uuid") + .HasColumnName("artifact_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ConsumedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("consumed_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "The ticket's fixed expiry and the instant its download finished."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the ticket was minted."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("Digest") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "The ticket's fixed expiry and the instant its download finished."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("SessionBindingDigest") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("session_binding_digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.HasKey("Id") + .HasName("pk_data_export_tickets"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_export_tickets_tenant_id_id"); + + b.HasIndex("TenantId", "ArtifactId") + .HasDatabaseName("ix_data_export_tickets_tenant_id_artifact_id"); + + b.HasIndex("TenantId", "Digest") + .IsUnique() + .HasDatabaseName("ux_data_export_tickets_digest"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_export_tickets_tenant_id_organization_id"); + + b.ToTable("data_export_tickets", null, t => + { + t.HasCheckConstraint("ck_data_export_tickets_digests", "octet_length(digest) = 32 AND octet_length(session_binding_digest) = 32"); + + t.HasCheckConstraint("ck_data_export_tickets_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(created_by)=7 AND created_by <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_tickets_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_export_tickets_times", "(isfinite(created_at) AND expires_at = created_at + interval '15 minutes' AND (consumed_at IS NULL OR (consumed_at >= created_at AND consumed_at < expires_at))) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataSubjectRequest", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("ExecuteAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("execute_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("FailureReason") + .HasColumnType("text") + .HasColumnName("failure_reason") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text") + .HasColumnName("kind") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("LastRefusal") + .HasColumnType("text") + .HasColumnName("last_refusal") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("MembershipSnapshotJson") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("membership_snapshot") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("Origin") + .IsRequired() + .HasColumnType("text") + .HasColumnName("origin") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("ProgressJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("progress") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("RequesterUserId") + .HasColumnType("uuid") + .HasColumnName("requester_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("ResultJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("result") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("SubjectUserId") + .HasColumnType("uuid") + .HasColumnName("subject_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_data_subject_requests"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_subject_requests_tenant_id_id"); + + b.HasIndex("RequesterUserId") + .HasDatabaseName("ix_data_subject_requests_requester_user_id"); + + b.HasIndex("SubjectUserId") + .HasDatabaseName("ix_data_subject_requests_subject_user_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_subject_requests_tenant_id_organization_id"); + + b.HasIndex("TenantId", "OrganizationId", "SubjectUserId", "Kind") + .IsUnique() + .HasDatabaseName("ux_data_subject_requests_active") + .HasFilter("status IN ('requested','scheduled','fulfilling','awaiting_privileged_step')"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "OrganizationId", "SubjectUserId", "Kind"), false); + + b.ToTable("data_subject_requests", null, t => + { + t.HasCheckConstraint("ck_data_subject_requests_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid AND (requester_user_id IS NULL OR (uuid_extract_version(requester_user_id)=7 AND requester_user_id <> '00000000-0000-7000-8000-000000000001'::uuid))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_kind", "kind IN ('export','erasure','closure')"); + + t.HasCheckConstraint("ck_data_subject_requests_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_data_subject_requests_origin", "((kind IN ('export','erasure') AND origin IN ('self','administrator')) OR (kind = 'erasure' AND origin = 'closure_fanout') OR (kind = 'closure' AND origin = 'self')) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_outcome", "((status = 'completed') = (completed_at IS NOT NULL)\n AND (completed_at IS NULL OR (isfinite(completed_at) AND completed_at >= created_at))\n AND ((status = 'failed' AND failure_reason IN ('export_too_large','execution_failed')\n AND (failure_reason <> 'export_too_large' OR kind = 'export'))\n OR (status <> 'failed' AND failure_reason IS NULL))\n AND (last_refusal IS NULL OR last_refusal IN ('blocked_window','blocked_hold','blocked_last_administrator'))\n AND (status <> 'blocked' OR last_refusal IN ('blocked_hold','blocked_last_administrator'))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_progress", "CASE WHEN jsonb_typeof(progress) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(progress, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(progress,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"string\" || !(@.value like_regex \"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{7}Z$\"))')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_requester", "((origin = 'self' AND requester_user_id = subject_user_id) OR (origin = 'administrator' AND requester_user_id IS NOT NULL AND requester_user_id <> subject_user_id) OR (origin = 'closure_fanout' AND requester_user_id IS NULL)) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_result", "CASE WHEN jsonb_typeof(result) = 'object'\n THEN NOT jsonb_path_exists(result,\n '$.keyvalue() ? (!(@.key like_regex \"^(consent_evidence|invitation_record|invitation_envelope|audit_actor_reference|audit_entity_reference|audit_metadata_reference|unscoped_audit_rows|transport_evidence|execution_evidence|provider_event_record|idempotency_cache|attribution_reference|federation_actor_reference|request_receipt|external_copy|unserved_group)$\") || @.value.type() != \"number\" || @.value < 0 || @.value > 9007199254740991 || @.value.floor() != @.value)')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_snapshot", "CASE WHEN jsonb_typeof(membership_snapshot) = 'array'\n THEN jsonb_array_length(membership_snapshot) BETWEEN 1 AND 256\n AND NOT jsonb_path_exists(membership_snapshot,\n '$[*] ? (@.type() != \"string\" || !(@ like_regex \"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\"))')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_status", "((kind = 'export' AND status IN ('requested','fulfilling','completed','failed','cancelled'))\nOR (kind = 'erasure' AND status IN ('scheduled','fulfilling','awaiting_privileged_step','completed','blocked','failed','cancelled'))\nOR (kind = 'closure' AND status IN ('scheduled','fulfilling','completed','cancelled'))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_subject_requests_times", "(isfinite(created_at) AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at)) AND (execute_at IS NULL OR isfinite(execute_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_window", "((kind IN ('erasure','closure') AND origin <> 'closure_fanout' AND execute_at = created_at + interval '24 hours') OR ((kind = 'export' OR origin = 'closure_fanout') AND execute_at IS NULL)) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.FederationConnection", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("Alias") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)") + .HasColumnName("alias") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("ClientId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("client_id") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("ConfigurationDigest") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("configuration_digest") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("ConfigurationRevision") + .HasColumnType("bigint") + .HasColumnName("configuration_revision") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("DesiredDigest") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("desired_digest") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)") + .HasColumnName("display_name") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("IssuerOrEntityId") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)") + .HasColumnName("issuer_or_entity_id") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("LastProviderDigest") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("last_provider_digest") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("PendingActor") + .HasColumnType("uuid") + .HasColumnName("pending_actor") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Pseudonymous actor identifiers attributing a pending provider write or a test attempt."); + + b.Property("PendingDesiredDigest") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("pending_desired_digest") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("PendingOperationId") + .HasColumnType("uuid") + .HasColumnName("pending_operation_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("PendingOperationKind") + .HasColumnType("text") + .HasColumnName("pending_operation_kind") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("PendingQuietUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("pending_quiet_until") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("PendingStartedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("pending_started_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("Protocol") + .IsRequired() + .HasColumnType("text") + .HasColumnName("protocol") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("SourceKind") + .IsRequired() + .HasColumnType("text") + .HasColumnName("source_kind") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("State") + .IsRequired() + .HasColumnType("text") + .HasColumnName("state") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TestActor") + .HasColumnType("uuid") + .HasColumnName("test_actor") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Pseudonymous actor identifiers attributing a pending provider write or a test attempt."); + + b.Property("TestAttemptId") + .HasColumnType("uuid") + .HasColumnName("test_attempt_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TestExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("test_expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TestPassedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("test_passed_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TestResult") + .HasColumnType("text") + .HasColumnName("test_result") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("TestRevision") + .HasColumnType("bigint") + .HasColumnName("test_revision") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned federation configuration: protocol, derived alias, public IdP identifiers, nonsecret digests and lifecycle."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_federation_connections"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_federation_connections_tenant_id_id"); + + b.HasIndex("TenantId") + .IsUnique() + .HasDatabaseName("ux_federation_connections_tenant_live") + .HasFilter("deleted_at IS NULL"); + + b.ToTable("federation_connections", null, t => + { + t.HasCheckConstraint("ck_federation_connections_actors", "(uuid_extract_version(created_by)=7 AND created_by <> '00000000-0000-7000-8000-000000000001'::uuid AND (updated_by IS NULL OR (uuid_extract_version(updated_by)=7 AND updated_by <> '00000000-0000-7000-8000-000000000001'::uuid)) AND (pending_actor IS NULL OR (uuid_extract_version(pending_actor)=7 AND pending_actor <> '00000000-0000-7000-8000-000000000001'::uuid)) AND (test_actor IS NULL OR (uuid_extract_version(test_actor)=7 AND test_actor <> '00000000-0000-7000-8000-000000000001'::uuid)) AND (deleted_by IS NULL OR (uuid_extract_version(deleted_by)=7 AND deleted_by <> '00000000-0000-7000-8000-000000000001'::uuid))) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_alias", "alias = 'lsf-' || replace(id::text, '-', '')"); + + t.HasCheckConstraint("ck_federation_connections_client", "((protocol <> 'Oidc' OR (client_id IS NOT NULL AND octet_length(client_id) BETWEEN 1 AND 255 AND client_id ~ '^[!-~]+$')) AND (protocol <> 'Saml' OR client_id IS NULL)) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_digests", "(configuration_digest ~ '^[0-9a-f]{64}$' AND desired_digest ~ '^[0-9a-f]{64}$' AND (last_provider_digest IS NULL OR last_provider_digest ~ '^[0-9a-f]{64}$') AND (pending_desired_digest IS NULL OR pending_desired_digest ~ '^[0-9a-f]{64}$')) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_display_name", "char_length(display_name) BETWEEN 1 AND 80 AND display_name = btrim(display_name, ' ') AND display_name IS NFC NORMALIZED AND display_name !~ '[\\u0001-\\u001f\\u007f-\\u00a0\\u00ad\\u0600-\\u0605\\u061c\\u06dd\\u070f\\u0890\\u0891\\u08e2\\u1680\\u180e\\u2000-\\u200f\\u2028-\\u202f\\u205f-\\u206f\\u3000\\ufeff\\ue000-\\uf8ff\\ufff9-\\ufffb\\U000110bd\\U000110cd\\U00013430-\\U0001343f\\U0001bca0-\\U0001bca3\\U0001d173-\\U0001d17a\\U000e0001\\U000e0020-\\U000e007f\\U000f0000-\\U0010ffff\\u115f\\u1160\\u2800\\u3164\\uffa0]' AND display_name !~ '^[\\u0300-\\u036f\\u0483-\\u0489\\u1ab0-\\u1aff\\u1dc0-\\u1dff\\u20d0-\\u20ff\\u302a-\\u302f\\u3099\\u309a\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\U000e0100-\\U000e01ef]'"); + + t.HasCheckConstraint("ck_federation_connections_identifiers", "(uuid_extract_version(id)=7 AND (pending_operation_id IS NULL OR uuid_extract_version(pending_operation_id)=7) AND (test_attempt_id IS NULL OR uuid_extract_version(test_attempt_id)=7)) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_issuer", "octet_length(issuer_or_entity_id) BETWEEN 1 AND 2048 AND issuer_or_entity_id ~ '^[!-~]+$' AND (protocol <> 'Oidc' OR (issuer_or_entity_id !~ '[?#]' AND issuer_or_entity_id !~ '^[^/]*//[^/]*@'))"); + + t.HasCheckConstraint("ck_federation_connections_pending", "((pending_operation_kind IS NULL AND pending_operation_id IS NULL AND pending_actor IS NULL AND pending_started_at IS NULL\n AND pending_quiet_until IS NULL AND pending_desired_digest IS NULL)\nOR (pending_operation_kind IN ('Configure','RotateSecret','Rename','TestStart','Disable','Delete')\n AND pending_operation_id IS NOT NULL AND pending_actor IS NOT NULL AND pending_started_at IS NOT NULL\n AND pending_quiet_until IS NOT NULL AND pending_desired_digest IS NOT NULL\n AND isfinite(pending_started_at) AND pending_quiet_until = pending_started_at + interval '90 seconds'\n AND state <> 'Deleted')) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_protocol", "protocol IN ('Oidc','Saml')"); + + t.HasCheckConstraint("ck_federation_connections_revision", "configuration_revision >= 1"); + + t.HasCheckConstraint("ck_federation_connections_source_kind", "source_kind IN ('MetadataUrl','DiscoveryUrl','Manual')"); + + t.HasCheckConstraint("ck_federation_connections_state", "state IN ('Draft','TestOpen','TestPassed','Active','Disabled','Deleted')"); + + t.HasCheckConstraint("ck_federation_connections_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_federation_connections_test", "((state IN ('TestOpen','TestPassed') AND test_attempt_id IS NOT NULL AND test_actor IS NOT NULL AND test_revision IS NOT NULL\n AND test_revision = configuration_revision AND test_expires_at IS NOT NULL AND isfinite(test_expires_at)\n AND ((state='TestOpen' AND test_result='Pending' AND test_passed_at IS NULL)\n OR (state='TestPassed' AND test_result='Passed' AND test_passed_at IS NOT NULL\n AND test_expires_at = test_passed_at + interval '10 minutes')))\nOR (state NOT IN ('TestOpen','TestPassed') AND test_attempt_id IS NULL AND test_actor IS NULL AND test_revision IS NULL\n AND test_expires_at IS NULL AND test_result IS NULL AND test_passed_at IS NULL)) IS TRUE"); + + t.HasCheckConstraint("ck_federation_connections_tombstone", "((state='Deleted' AND deleted_at IS NOT NULL AND deleted_by IS NOT NULL) OR (state<>'Deleted' AND deleted_at IS NULL AND deleted_by IS NULL)) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.IdentityAuthority", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Deployment authority registration: one stable authority UUID and exact configured issuer address, without person fields."); + + b.Property("AuthorityId") + .HasColumnType("uuid") + .HasColumnName("authority_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Deployment authority registration: one stable authority UUID and exact configured issuer address, without person fields."); + + b.Property("Issuer") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)") + .HasColumnName("issuer") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Deployment authority registration: one stable authority UUID and exact configured issuer address, without person fields."); + + b.HasKey("Id") + .HasName("pk_identity_authority"); + + b.HasAlternateKey("AuthorityId") + .HasName("ux_identity_authority_authority_id"); + + b.ToTable("identity_authority", null, t => + { + t.HasCheckConstraint("ck_identity_authority_assigned", "authority_id <> '00000000-0000-0000-0000-000000000000'::uuid"); + + t.HasCheckConstraint("ck_identity_authority_singleton", "id = 1"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Invitation", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("AcceptanceDisposition") + .HasColumnType("text") + .HasColumnName("acceptance_disposition") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("AcceptedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("accepted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("AcceptedBy") + .HasColumnType("uuid") + .HasColumnName("accepted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("ConsumedVerifierDigest") + .HasColumnType("bytea") + .HasColumnName("consumed_verifier_digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("CurrentDeliveryJobId") + .HasColumnType("uuid") + .HasColumnName("current_delivery_job_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("EntryLocale") + .IsRequired() + .HasMaxLength(35) + .HasColumnType("character varying(35)") + .HasColumnName("entry_locale") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("EntryOrigin") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasColumnName("entry_origin") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("Generation") + .HasColumnType("bigint") + .HasColumnName("generation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("GenerationCreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("generation_created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("GenerationId") + .HasColumnType("uuid") + .HasColumnName("generation_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("InviterUserId") + .HasColumnType("uuid") + .HasColumnName("inviter_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("PinnedRoleVersion") + .HasColumnType("bigint") + .HasColumnName("pinned_role_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("RecipientEmail") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("character varying(254)") + .HasColumnName("recipient_email") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("ResultMembershipId") + .HasColumnType("uuid") + .HasColumnName("result_membership_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("RoleId") + .HasColumnType("uuid") + .HasColumnName("role_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("SubmissionReceiptId") + .HasColumnType("uuid") + .HasColumnName("submission_receipt_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("SubmissionStatus") + .IsRequired() + .HasColumnType("text") + .HasColumnName("submission_status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("VerifierDigest") + .HasColumnType("bytea") + .HasColumnName("verifier_digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Scoped membership offer, recipient, credential verifiers, inviter and immutable acceptance/delivery linkage."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_invitations"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_invitations_tenant_id_id"); + + b.HasIndex("AcceptedBy") + .HasDatabaseName("ix_invitations_accepted_by"); + + b.HasIndex("InviterUserId") + .HasDatabaseName("ix_invitations_inviter_user_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_invitations_tenant_id_organization_id"); + + b.HasIndex("TenantId", "ResultMembershipId") + .HasDatabaseName("ix_invitations_tenant_id_result_membership_id"); + + b.HasIndex("TenantId", "RoleId") + .HasDatabaseName("ix_invitations_tenant_id_role_id"); + + b.HasIndex("TenantId", "OrganizationId", "RecipientEmail") + .IsUnique() + .HasDatabaseName("ux_invitations_pending_recipient") + .HasFilter("status = 'Pending' AND deleted_at IS NULL"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "OrganizationId", "RecipientEmail"), false); + + b.ToTable("invitations", null, t => + { + t.HasCheckConstraint("ck_invitations_generation", "generation > 0 AND pinned_role_version >= 0"); + + t.HasCheckConstraint("ck_invitations_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(generation_id)=7 AND uuid_extract_version(current_delivery_job_id)=7) IS TRUE"); + + t.HasCheckConstraint("ck_invitations_lifecycle", "((status='Pending' AND octet_length(verifier_digest)=32 AND consumed_verifier_digest IS NULL\n AND accepted_by IS NULL AND result_membership_id IS NULL AND acceptance_disposition IS NULL AND accepted_at IS NULL)\nOR (status='Accepted' AND verifier_digest IS NULL AND octet_length(consumed_verifier_digest)=32\n AND accepted_by IS NOT NULL AND result_membership_id IS NOT NULL\n AND acceptance_disposition IN ('Created','AlreadyMember') AND accepted_at IS NOT NULL\n AND isfinite(accepted_at) AND accepted_at >= generation_created_at AND accepted_at < expires_at)\nOR (status='Revoked' AND verifier_digest IS NULL AND consumed_verifier_digest IS NULL\n AND accepted_by IS NULL AND result_membership_id IS NULL AND acceptance_disposition IS NULL AND accepted_at IS NULL)) IS TRUE"); + + t.HasCheckConstraint("ck_invitations_mailbox", "octet_length(recipient_email) BETWEEN 3 AND 254 AND recipient_email=lower(recipient_email COLLATE \"C\") AND recipient_email ~ '^[!-~]+@[!-~]+$'"); + + t.HasCheckConstraint("ck_invitations_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_invitations_submission", "((submission_status IN ('Queued','Failed') AND submission_receipt_id IS NULL) OR (submission_status IN ('SubmissionAccepted','Failed') AND submission_receipt_id IS NOT NULL AND submission_receipt_id <> '00000000-0000-0000-0000-000000000000'::uuid)) IS TRUE"); + + t.HasCheckConstraint("ck_invitations_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_invitations_times", "isfinite(created_at) AND isfinite(generation_created_at) AND isfinite(expires_at) AND generation_created_at >= created_at AND expires_at >= generation_created_at + interval '1 day' AND expires_at <= generation_created_at + interval '30 days'"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Membership", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contextual person membership, immutable scope and admission lifecycle."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contextual person membership, immutable scope and admission lifecycle."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contextual person membership, immutable scope and admission lifecycle."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contextual person membership, immutable scope and admission lifecycle."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contextual person membership, immutable scope and admission lifecycle."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_memberships"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_memberships_tenant_id_id"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_memberships_user_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_memberships_tenant_id_organization_id"); + + b.HasIndex("UserId", "Id") + .HasDatabaseName("ix_memberships_self_active_user_id_id") + .HasFilter("status = 'Active' AND deleted_at IS NULL"); + + b.HasIndex("TenantId", "UserId", "OrganizationId") + .IsUnique() + .HasDatabaseName("ux_memberships_current_scope") + .HasFilter("deleted_at IS NULL"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "UserId", "OrganizationId"), false); + + b.ToTable("memberships", null, t => + { + t.HasCheckConstraint("ck_memberships_lifecycle", "(status IN ('Active','Suspended') AND deleted_at IS NULL AND deleted_by IS NULL) OR (status = 'Revoked' AND deleted_at IS NOT NULL AND deleted_by IS NOT NULL)"); + + t.HasCheckConstraint("ck_memberships_status", "status IN ('Active','Suspended','Revoked')"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.MembershipProfile", b => + { + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained contextual profile identity, scope and optional personal display and locale preferences."); + + b.Property("MembershipId") + .HasColumnType("uuid") + .HasColumnName("membership_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained contextual profile identity, scope and optional personal display and locale preferences."); + + b.Property("CustomFieldsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("[]") + .HasColumnName("custom_fields") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Sensitive) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained revision-pinned personal values and original consent linkage; always excluded from diagnostics."); + + b.Property("DisplayName") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("display_name") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained contextual profile identity, scope and optional personal display and locale preferences."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained contextual profile identity, scope and optional personal display and locale preferences."); + + b.Property("PreferredLocale") + .HasMaxLength(35) + .HasColumnType("character varying(35)") + .HasColumnName("preferred_locale") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained contextual profile identity, scope and optional personal display and locale preferences."); + + b.HasKey("TenantId", "MembershipId") + .HasName("pk_membership_profiles"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_membership_profiles_tenant_id_organization_id"); + + b.ToTable("membership_profiles", null, t => + { + t.HasCheckConstraint("ck_membership_profiles_custom_fields_shape", "CASE WHEN jsonb_typeof(custom_fields) = 'array' THEN jsonb_array_length(custom_fields) <= 20 ELSE false END"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.MembershipRoleAssignment", b => + { + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained person's contextual role assignment and exact Membership scope."); + + b.Property("MembershipId") + .HasColumnType("uuid") + .HasColumnName("membership_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained person's contextual role assignment and exact Membership scope."); + + b.Property("RoleId") + .HasColumnType("uuid") + .HasColumnName("role_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained person's contextual role assignment and exact Membership scope."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained person's contextual role assignment and exact Membership scope."); + + b.HasKey("TenantId", "MembershipId", "RoleId") + .HasName("pk_membership_role_assignments"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_membership_role_assignments_tenant_id_organization_id"); + + b.HasIndex("TenantId", "RoleId") + .HasDatabaseName("ix_membership_role_assignments_tenant_id_role_id"); + + b.ToTable("membership_role_assignments", (string)null); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.ProviderEventTarget", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("AffectedUserId") + .HasColumnType("uuid") + .HasColumnName("affected_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("Attempts") + .HasColumnType("integer") + .HasColumnName("attempts") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Internal lease and enqueue progress; no subject content."); + + b.Property("AuthorityId") + .HasColumnType("uuid") + .HasColumnName("authority_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("ClaimToken") + .HasColumnType("uuid") + .HasColumnName("claim_token") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Internal lease and enqueue progress; no subject content."); + + b.Property("ClaimUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("claim_until") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Internal lease and enqueue progress; no subject content."); + + b.Property("EnqueuedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("enqueued_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Internal lease and enqueue progress; no subject content."); + + b.Property("EventId") + .HasColumnType("uuid") + .HasColumnName("event_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("ProviderEventId") + .HasColumnType("uuid") + .HasColumnName("provider_event_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("RealmId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("realm_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("ReceiptId") + .HasColumnType("uuid") + .HasColumnName("receipt_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("received_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("SourceKind") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)") + .HasColumnName("source_kind") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("SourceOccurredAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("source_occurred_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("SubjectKey") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("subject_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Minimized provider-history target and stable delivery linkage; retained until coordinated transport/Audit retirement."); + + b.HasKey("Id") + .HasName("pk_identity_provider_event_targets"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("ux_identity_provider_event_targets_event"); + + b.HasIndex("AffectedUserId", "Id") + .HasDatabaseName("ix_identity_provider_event_targets_subject_id"); + + b.HasIndex("ReceivedAt", "Id") + .HasDatabaseName("ix_identity_provider_event_targets_pending") + .HasFilter("enqueued_at IS NULL"); + + b.HasIndex("SubjectKey", "Id") + .HasDatabaseName("ix_identity_provider_event_targets_subject_key"); + + b.HasIndex("TenantId", "Id") + .HasDatabaseName("ix_identity_provider_event_targets_tenant_id"); + + b.HasIndex("AuthorityId", "RealmId", "ProviderEventId", "TenantId") + .IsUnique() + .HasDatabaseName("ux_identity_provider_event_targets_source_tenant"); + + b.ToTable("identity_provider_event_targets", null, t => + { + t.HasCheckConstraint("ck_identity_provider_event_targets_claim", "(claim_token IS NULL)=(claim_until IS NULL) AND attempts >= 0"); + + t.HasCheckConstraint("ck_identity_provider_event_targets_ids", "(uuid_extract_version(id)=7 AND uuid_extract_version(event_id)=7 AND uuid_extract_version(receipt_id)=7) IS TRUE"); + + t.HasCheckConstraint("ck_identity_provider_event_targets_subject", "octet_length(subject_key)=32 AND affected_user_id <> '00000000-0000-7000-8000-000000000001'::uuid"); + + t.HasCheckConstraint("ck_identity_provider_event_targets_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_identity_provider_event_targets_time", "isfinite(received_at) AND isfinite(source_occurred_at) AND (claim_until IS NULL OR isfinite(claim_until)) AND (enqueued_at IS NULL OR isfinite(enqueued_at))"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Role", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("AdoptedReleaseFingerprint") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasDefaultValue("ba16d2c21f2547f3dc7f9dce24e25a18f30103186739ea00a33e9edf43834794") + .HasColumnName("adopted_release_fingerprint") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("AdoptedReleaseVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("adopted_release_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("BuiltInKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("built_in_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("PermissionScope") + .IsRequired() + .HasColumnType("text") + .HasColumnName("permission_scope") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-owned built-in authorization template identity and capability scope, without person fields."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_roles"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_roles_tenant_id_id"); + + b.HasIndex("TenantId", "PermissionScope", "BuiltInKey") + .IsUnique() + .HasDatabaseName("ux_roles_current_builtin_scope") + .HasFilter("deleted_at IS NULL"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.RolePermissionGrant", b => + { + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained finite template capability grant, without a person assignment."); + + b.Property("RoleId") + .HasColumnType("uuid") + .HasColumnName("role_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained finite template capability grant, without a person assignment."); + + b.Property("PermissionScope") + .HasColumnType("text") + .HasColumnName("permission_scope") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained finite template capability grant, without a person assignment."); + + b.Property("PermissionKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("permission_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Contained finite template capability grant, without a person assignment."); + + b.HasKey("TenantId", "RoleId", "PermissionScope", "PermissionKey") + .HasName("pk_role_permission_grants"); + + b.ToTable("role_permission_grants", (string)null); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.User", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("AuthorityId") + .HasColumnType("uuid") + .HasColumnName("authority_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("CreationAuditId") + .HasColumnType("uuid") + .HasColumnName("creation_audit_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("CreationAuditTimestamp") + .HasColumnType("timestamp with time zone") + .HasColumnName("creation_audit_timestamp") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("ProviderSubject") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("provider_subject") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Admission lifecycle of the bound person; no tenant membership or profile is implied."); + + b.Property("SubjectKey") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("subject_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("AuthorityId", "SubjectKey") + .IsUnique() + .HasDatabaseName("ux_users_authority_id_subject_key"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_actor", "uuid_extract_version(id) = 7 AND id <> '00000000-0000-7000-8000-000000000001'::uuid"); + + t.HasCheckConstraint("ck_users_no_soft_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_users_status", "status IN ('Active', 'Closing', 'Closed')"); + + t.HasCheckConstraint("ck_users_subject_digest", "provider_subject IS NULL OR subject_key = sha256(int4send(octet_length(convert_to('learnstack.identity.subject.v1','UTF8'))) || convert_to('learnstack.identity.subject.v1','UTF8') || int4send(16) || uuid_send(authority_id) || int4send(octet_length(convert_to(provider_subject,'UTF8'))) || convert_to(provider_subject,'UTF8'))"); + + t.HasCheckConstraint("ck_users_subject_key", "octet_length(subject_key) = 32"); + + t.HasCheckConstraint("ck_users_subject_lifecycle", "(status = 'Active' AND provider_subject IS NOT NULL AND length(provider_subject) BETWEEN 1 AND 255) OR (status = 'Closing' AND (provider_subject IS NULL OR length(provider_subject) BETWEEN 1 AND 255)) OR (status = 'Closed' AND provider_subject IS NULL)"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportArtifact", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.DataSubjectRequest", null) + .WithMany() + .HasForeignKey("TenantId", "RequestId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_export_artifacts_request"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportTicket", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.DataExportArtifact", null) + .WithMany() + .HasForeignKey("TenantId", "ArtifactId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_export_tickets_artifact"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataSubjectRequest", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("RequesterUserId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_data_subject_requests_requester"); + + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("SubjectUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_subject_requests_subject"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Invitation", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("AcceptedBy") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_invitations_acceptor"); + + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("InviterUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_invitations_inviter"); + + b.HasOne("LearnStack.Modules.Identity.Domain.Membership", null) + .WithMany() + .HasForeignKey("TenantId", "ResultMembershipId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_invitations_result_membership"); + + b.HasOne("LearnStack.Modules.Identity.Domain.Role", null) + .WithMany() + .HasForeignKey("TenantId", "RoleId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_invitations_role"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Membership", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_memberships_user"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.MembershipProfile", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.Membership", "Membership") + .WithOne("Profile") + .HasForeignKey("LearnStack.Modules.Identity.Domain.MembershipProfile", "TenantId", "MembershipId") + .HasPrincipalKey("LearnStack.Modules.Identity.Domain.Membership", "TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_membership_profiles_membership"); + + b.Navigation("Membership"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.MembershipRoleAssignment", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.Membership", "Membership") + .WithMany("RoleAssignments") + .HasForeignKey("TenantId", "MembershipId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_membership_role_assignments_membership"); + + b.HasOne("LearnStack.Modules.Identity.Domain.Role", null) + .WithMany() + .HasForeignKey("TenantId", "RoleId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_membership_role_assignments_role"); + + b.Navigation("Membership"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.RolePermissionGrant", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.Role", "Role") + .WithMany("Grants") + .HasForeignKey("TenantId", "RoleId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_role_permission_grants_role"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.User", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.IdentityAuthority", null) + .WithMany() + .HasForeignKey("AuthorityId") + .HasPrincipalKey("AuthorityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_users_identity_authority"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Membership", b => + { + b.Navigation("Profile") + .IsRequired(); + + b.Navigation("RoleAssignments"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Role", b => + { + b.Navigation("Grants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs new file mode 100644 index 00000000..6c451998 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs @@ -0,0 +1,216 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class add_data_subject_requests : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "data_subject_requests", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + tenant_id = table.Column(type: "uuid", nullable: false), + organization_id = table.Column(type: "uuid", nullable: true), + kind = table.Column(type: "text", nullable: false), + origin = table.Column(type: "text", nullable: false), + subject_user_id = table.Column(type: "uuid", nullable: false), + requester_user_id = table.Column(type: "uuid", nullable: true), + status = table.Column(type: "text", nullable: false), + membership_snapshot = table.Column(type: "jsonb", nullable: false), + execute_at = table.Column(type: "timestamp with time zone", nullable: true), + progress = table.Column(type: "jsonb", nullable: false, defaultValue: "{}"), + result = table.Column(type: "jsonb", nullable: false, defaultValue: "{}"), + last_refusal = table.Column(type: "text", nullable: true), + failure_reason = table.Column(type: "text", nullable: true), + completed_at = table.Column(type: "timestamp with time zone", nullable: true), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + created_by = table.Column(type: "uuid", nullable: false), + updated_at = table.Column(type: "timestamp with time zone", nullable: true), + updated_by = table.Column(type: "uuid", nullable: true), + deleted_at = table.Column(type: "timestamp with time zone", nullable: true), + deleted_by = table.Column(type: "uuid", nullable: true), + row_version = table.Column(type: "bigint", nullable: false, defaultValue: 0L) + }, + constraints: table => + { + table.PrimaryKey("pk_data_subject_requests", x => x.id); + table.UniqueConstraint("ux_data_subject_requests_tenant_id_id", x => new { x.tenant_id, x.id }); + table.CheckConstraint("ck_data_subject_requests_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid AND (requester_user_id IS NULL OR (uuid_extract_version(requester_user_id)=7 AND requester_user_id <> '00000000-0000-7000-8000-000000000001'::uuid))) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_kind", "kind IN ('export','erasure','closure')"); + table.CheckConstraint("ck_data_subject_requests_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + table.CheckConstraint("ck_data_subject_requests_origin", "((kind IN ('export','erasure') AND origin IN ('self','administrator')) OR (kind = 'erasure' AND origin = 'closure_fanout') OR (kind = 'closure' AND origin = 'self')) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_outcome", "((status = 'completed') = (completed_at IS NOT NULL)\n AND (completed_at IS NULL OR (isfinite(completed_at) AND completed_at >= created_at))\n AND ((status = 'failed' AND failure_reason IN ('export_too_large','execution_failed')\n AND (failure_reason <> 'export_too_large' OR kind = 'export'))\n OR (status <> 'failed' AND failure_reason IS NULL))\n AND (last_refusal IS NULL OR last_refusal IN ('blocked_window','blocked_hold','blocked_last_administrator'))\n AND (status <> 'blocked' OR last_refusal IN ('blocked_hold','blocked_last_administrator'))) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_progress", "CASE WHEN jsonb_typeof(progress) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(progress, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(progress,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"string\" || !(@.value like_regex \"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{7}Z$\"))')\n ELSE false END"); + table.CheckConstraint("ck_data_subject_requests_requester", "((origin = 'self' AND requester_user_id = subject_user_id) OR (origin = 'administrator' AND requester_user_id IS NOT NULL AND requester_user_id <> subject_user_id) OR (origin = 'closure_fanout' AND requester_user_id IS NULL)) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_result", "CASE WHEN jsonb_typeof(result) = 'object'\n THEN NOT jsonb_path_exists(result,\n '$.keyvalue() ? (!(@.key like_regex \"^(consent_evidence|invitation_record|invitation_envelope|audit_actor_reference|audit_entity_reference|audit_metadata_reference|unscoped_audit_rows|transport_evidence|execution_evidence|provider_event_record|idempotency_cache|attribution_reference|federation_actor_reference|request_receipt|external_copy|unserved_group)$\") || @.value.type() != \"number\" || @.value < 0 || @.value > 9007199254740991 || @.value.floor() != @.value)')\n ELSE false END"); + table.CheckConstraint("ck_data_subject_requests_snapshot", "CASE WHEN jsonb_typeof(membership_snapshot) = 'array'\n THEN jsonb_array_length(membership_snapshot) BETWEEN 1 AND 256\n AND NOT jsonb_path_exists(membership_snapshot,\n '$[*] ? (@.type() != \"string\" || !(@ like_regex \"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\"))')\n ELSE false END"); + table.CheckConstraint("ck_data_subject_requests_status", "((kind = 'export' AND status IN ('requested','fulfilling','completed','failed','cancelled'))\nOR (kind = 'erasure' AND status IN ('scheduled','fulfilling','awaiting_privileged_step','completed','blocked','failed','cancelled'))\nOR (kind = 'closure' AND status IN ('scheduled','fulfilling','completed','cancelled'))) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.CheckConstraint("ck_data_subject_requests_times", "(isfinite(created_at) AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at)) AND (execute_at IS NULL OR isfinite(execute_at))) IS TRUE"); + table.CheckConstraint("ck_data_subject_requests_window", "((kind IN ('erasure','closure') AND origin <> 'closure_fanout' AND execute_at = created_at + interval '24 hours') OR ((kind = 'export' OR origin = 'closure_fanout') AND execute_at IS NULL)) IS TRUE"); + table.ForeignKey( + name: "fk_data_subject_requests_requester", + column: x => x.requester_user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "fk_data_subject_requests_subject", + column: x => x.subject_user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "data_export_artifacts", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + tenant_id = table.Column(type: "uuid", nullable: false), + organization_id = table.Column(type: "uuid", nullable: true), + request_id = table.Column(type: "uuid", nullable: false), + subject_user_id = table.Column(type: "uuid", nullable: false), + status = table.Column(type: "text", nullable: false), + byte_count = table.Column(type: "bigint", nullable: false), + chunk_count = table.Column(type: "integer", nullable: false), + key_version = table.Column(type: "character varying(32)", maxLength: 32, nullable: false, collation: "C"), + expires_at = table.Column(type: "timestamp with time zone", nullable: false), + purged_at = table.Column(type: "timestamp with time zone", nullable: true), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + created_by = table.Column(type: "uuid", nullable: false), + updated_at = table.Column(type: "timestamp with time zone", nullable: true), + updated_by = table.Column(type: "uuid", nullable: true), + deleted_at = table.Column(type: "timestamp with time zone", nullable: true), + deleted_by = table.Column(type: "uuid", nullable: true), + row_version = table.Column(type: "bigint", nullable: false, defaultValue: 0L) + }, + constraints: table => + { + table.PrimaryKey("pk_data_export_artifacts", x => x.id); + table.UniqueConstraint("ux_data_export_artifacts_tenant_id_id", x => new { x.tenant_id, x.id }); + table.CheckConstraint("ck_data_export_artifacts_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + table.CheckConstraint("ck_data_export_artifacts_key_version", "key_version COLLATE \"C\" ~ '^[A-Za-z0-9_-]{1,32}$'"); + table.CheckConstraint("ck_data_export_artifacts_lifecycle", "((status IN ('revoked','purged')) = (purged_at IS NOT NULL) AND (purged_at IS NULL OR (isfinite(purged_at) AND purged_at >= created_at))) IS TRUE"); + table.CheckConstraint("ck_data_export_artifacts_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + table.CheckConstraint("ck_data_export_artifacts_size", "byte_count BETWEEN 1 AND 67108864 AND chunk_count BETWEEN 1 AND 512 AND chunk_count = (byte_count + 131071) / 131072"); + table.CheckConstraint("ck_data_export_artifacts_status", "status IN ('available','revoked','expired','purged')"); + table.CheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.CheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + table.ForeignKey( + name: "fk_data_export_artifacts_request", + columns: x => new { x.tenant_id, x.request_id }, + principalTable: "data_subject_requests", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "data_export_tickets", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + tenant_id = table.Column(type: "uuid", nullable: false), + organization_id = table.Column(type: "uuid", nullable: true), + artifact_id = table.Column(type: "uuid", nullable: false), + digest = table.Column(type: "bytea", nullable: false), + session_binding_digest = table.Column(type: "bytea", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + created_by = table.Column(type: "uuid", nullable: false), + expires_at = table.Column(type: "timestamp with time zone", nullable: false), + consumed_at = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_data_export_tickets", x => x.id); + table.UniqueConstraint("ux_data_export_tickets_tenant_id_id", x => new { x.tenant_id, x.id }); + table.CheckConstraint("ck_data_export_tickets_digests", "octet_length(digest) = 32 AND octet_length(session_binding_digest) = 32"); + table.CheckConstraint("ck_data_export_tickets_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(created_by)=7 AND created_by <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + table.CheckConstraint("ck_data_export_tickets_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + table.CheckConstraint("ck_data_export_tickets_times", "(isfinite(created_at) AND expires_at = created_at + interval '15 minutes' AND (consumed_at IS NULL OR (consumed_at >= created_at AND consumed_at < expires_at))) IS TRUE"); + table.ForeignKey( + name: "fk_data_export_tickets_artifact", + columns: x => new { x.tenant_id, x.artifact_id }, + principalTable: "data_export_artifacts", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "ix_data_export_artifacts_tenant_id_organization_id", + table: "data_export_artifacts", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ux_data_export_artifacts_available", + table: "data_export_artifacts", + columns: new[] { "tenant_id", "organization_id", "subject_user_id" }, + unique: true, + filter: "status = 'available'") + .Annotation("Npgsql:NullsDistinct", false); + + migrationBuilder.CreateIndex( + name: "ux_data_export_artifacts_request", + table: "data_export_artifacts", + columns: new[] { "tenant_id", "request_id" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_data_export_tickets_tenant_id_artifact_id", + table: "data_export_tickets", + columns: new[] { "tenant_id", "artifact_id" }); + + migrationBuilder.CreateIndex( + name: "ix_data_export_tickets_tenant_id_organization_id", + table: "data_export_tickets", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ux_data_export_tickets_digest", + table: "data_export_tickets", + columns: new[] { "tenant_id", "digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_data_subject_requests_requester_user_id", + table: "data_subject_requests", + column: "requester_user_id"); + + migrationBuilder.CreateIndex( + name: "ix_data_subject_requests_subject_user_id", + table: "data_subject_requests", + column: "subject_user_id"); + + migrationBuilder.CreateIndex( + name: "ix_data_subject_requests_tenant_id_organization_id", + table: "data_subject_requests", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ux_data_subject_requests_active", + table: "data_subject_requests", + columns: new[] { "tenant_id", "organization_id", "subject_user_id", "kind" }, + unique: true, + filter: "status IN ('requested','scheduled','fulfilling','awaiting_privileged_step')") + .Annotation("Npgsql:NullsDistinct", false); + + DataRequestStorageDdl.Install(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Forward-only (ADR-0107 § 6): requests, artifacts and tickets are retained receipts + // (`request_receipt`) whose retention and purge belong to Phase 11, so a reversal cannot + // silently drop the evidence that a person asked and what was done. + throw new NotSupportedException("Data request storage requires a reviewed forward migration."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs index f330f295..8e2bf30f 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs @@ -24,6 +24,452 @@ protected override void BuildModel(ModelBuilder modelBuilder) NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportArtifact", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("ByteCount") + .HasColumnType("bigint") + .HasColumnName("byte_count") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("ChunkCount") + .HasColumnType("integer") + .HasColumnName("chunk_count") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("KeyVersion") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("key_version") + .UseCollation("C") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("PurgedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("purged_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("RequestId") + .HasColumnType("uuid") + .HasColumnName("request_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + + b.Property("SubjectUserId") + .HasColumnType("uuid") + .HasColumnName("subject_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_data_export_artifacts"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_export_artifacts_tenant_id_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_export_artifacts_tenant_id_organization_id"); + + b.HasIndex("TenantId", "RequestId") + .IsUnique() + .HasDatabaseName("ux_data_export_artifacts_request"); + + b.HasIndex("TenantId", "OrganizationId", "SubjectUserId") + .IsUnique() + .HasDatabaseName("ux_data_export_artifacts_available") + .HasFilter("status = 'available'"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "OrganizationId", "SubjectUserId"), false); + + b.ToTable("data_export_artifacts", null, t => + { + t.HasCheckConstraint("ck_data_export_artifacts_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_key_version", "key_version COLLATE \"C\" ~ '^[A-Za-z0-9_-]{1,32}$'"); + + t.HasCheckConstraint("ck_data_export_artifacts_lifecycle", "((status IN ('revoked','purged')) = (purged_at IS NOT NULL) AND (purged_at IS NULL OR (isfinite(purged_at) AND purged_at >= created_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_data_export_artifacts_size", "byte_count BETWEEN 1 AND 67108864 AND chunk_count BETWEEN 1 AND 512 AND chunk_count = (byte_count + 131071) / 131072"); + + t.HasCheckConstraint("ck_data_export_artifacts_status", "status IN ('available','revoked','expired','purged')"); + + t.HasCheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportTicket", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ArtifactId") + .HasColumnType("uuid") + .HasColumnName("artifact_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ConsumedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("consumed_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "The ticket's fixed expiry and the instant its download finished."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the ticket was minted."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("Digest") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "The ticket's fixed expiry and the instant its download finished."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("SessionBindingDigest") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("session_binding_digest") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's download cursor: the group, the artifact, the minting subject and its session-bound credential digests."); + + b.HasKey("Id") + .HasName("pk_data_export_tickets"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_export_tickets_tenant_id_id"); + + b.HasIndex("TenantId", "ArtifactId") + .HasDatabaseName("ix_data_export_tickets_tenant_id_artifact_id"); + + b.HasIndex("TenantId", "Digest") + .IsUnique() + .HasDatabaseName("ux_data_export_tickets_digest"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_export_tickets_tenant_id_organization_id"); + + b.ToTable("data_export_tickets", null, t => + { + t.HasCheckConstraint("ck_data_export_tickets_digests", "octet_length(digest) = 32 AND octet_length(session_binding_digest) = 32"); + + t.HasCheckConstraint("ck_data_export_tickets_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(created_by)=7 AND created_by <> '00000000-0000-7000-8000-000000000001'::uuid) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_tickets_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_export_tickets_times", "(isfinite(created_at) AND expires_at = created_at + interval '15 minutes' AND (consumed_at IS NULL OR (consumed_at >= created_at AND consumed_at < expires_at))) IS TRUE"); + }); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataSubjectRequest", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was created."); + + b.Property("CreatedBy") + .HasColumnType("uuid") + .HasColumnName("created_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate creation to its actor."); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was soft-deleted."); + + b.Property("DeletedBy") + .HasColumnType("uuid") + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); + + b.Property("ExecuteAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("execute_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("FailureReason") + .HasColumnType("text") + .HasColumnName("failure_reason") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text") + .HasColumnName("kind") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("LastRefusal") + .HasColumnType("text") + .HasColumnName("last_refusal") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("MembershipSnapshotJson") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("membership_snapshot") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("Origin") + .IsRequired() + .HasColumnType("text") + .HasColumnName("origin") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("ProgressJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("progress") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("RequesterUserId") + .HasColumnType("uuid") + .HasColumnName("requester_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("ResultJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("result") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("Status") + .IsRequired() + .HasColumnType("text") + .HasColumnName("status") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed request kind, origin, status, window, refusal and failure codes, participant progress and retained-kind counts."); + + b.Property("SubjectUserId") + .HasColumnType("uuid") + .HasColumnName("subject_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's request in one scope group: subject and requester, the group and the frozen Membership linkage."); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Record when the aggregate was last updated."); + + b.Property("UpdatedBy") + .HasColumnType("uuid") + .HasColumnName("updated_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute the latest aggregate update to its actor."); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("row_version") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Detect concurrent writes to this aggregate revision."); + + b.HasKey("Id") + .HasName("pk_data_subject_requests"); + + b.HasAlternateKey("TenantId", "Id") + .HasName("ux_data_subject_requests_tenant_id_id"); + + b.HasIndex("RequesterUserId") + .HasDatabaseName("ix_data_subject_requests_requester_user_id"); + + b.HasIndex("SubjectUserId") + .HasDatabaseName("ix_data_subject_requests_subject_user_id"); + + b.HasIndex("TenantId", "OrganizationId") + .HasDatabaseName("ix_data_subject_requests_tenant_id_organization_id"); + + b.HasIndex("TenantId", "OrganizationId", "SubjectUserId", "Kind") + .IsUnique() + .HasDatabaseName("ux_data_subject_requests_active") + .HasFilter("status IN ('requested','scheduled','fulfilling','awaiting_privileged_step')"); + + NpgsqlIndexBuilderExtensions.AreNullsDistinct(b.HasIndex("TenantId", "OrganizationId", "SubjectUserId", "Kind"), false); + + b.ToTable("data_subject_requests", null, t => + { + t.HasCheckConstraint("ck_data_subject_requests_identifiers", "(uuid_extract_version(id)=7 AND uuid_extract_version(subject_user_id)=7 AND subject_user_id <> '00000000-0000-7000-8000-000000000001'::uuid AND (requester_user_id IS NULL OR (uuid_extract_version(requester_user_id)=7 AND requester_user_id <> '00000000-0000-7000-8000-000000000001'::uuid))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_kind", "kind IN ('export','erasure','closure')"); + + t.HasCheckConstraint("ck_data_subject_requests_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + + t.HasCheckConstraint("ck_data_subject_requests_origin", "((kind IN ('export','erasure') AND origin IN ('self','administrator')) OR (kind = 'erasure' AND origin = 'closure_fanout') OR (kind = 'closure' AND origin = 'self')) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_outcome", "((status = 'completed') = (completed_at IS NOT NULL)\n AND (completed_at IS NULL OR (isfinite(completed_at) AND completed_at >= created_at))\n AND ((status = 'failed' AND failure_reason IN ('export_too_large','execution_failed')\n AND (failure_reason <> 'export_too_large' OR kind = 'export'))\n OR (status <> 'failed' AND failure_reason IS NULL))\n AND (last_refusal IS NULL OR last_refusal IN ('blocked_window','blocked_hold','blocked_last_administrator'))\n AND (status <> 'blocked' OR last_refusal IN ('blocked_hold','blocked_last_administrator'))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_progress", "CASE WHEN jsonb_typeof(progress) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(progress, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(progress,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"string\" || !(@.value like_regex \"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{7}Z$\"))')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_requester", "((origin = 'self' AND requester_user_id = subject_user_id) OR (origin = 'administrator' AND requester_user_id IS NOT NULL AND requester_user_id <> subject_user_id) OR (origin = 'closure_fanout' AND requester_user_id IS NULL)) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_result", "CASE WHEN jsonb_typeof(result) = 'object'\n THEN NOT jsonb_path_exists(result,\n '$.keyvalue() ? (!(@.key like_regex \"^(consent_evidence|invitation_record|invitation_envelope|audit_actor_reference|audit_entity_reference|audit_metadata_reference|unscoped_audit_rows|transport_evidence|execution_evidence|provider_event_record|idempotency_cache|attribution_reference|federation_actor_reference|request_receipt|external_copy|unserved_group)$\") || @.value.type() != \"number\" || @.value < 0 || @.value > 9007199254740991 || @.value.floor() != @.value)')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_snapshot", "CASE WHEN jsonb_typeof(membership_snapshot) = 'array'\n THEN jsonb_array_length(membership_snapshot) BETWEEN 1 AND 256\n AND NOT jsonb_path_exists(membership_snapshot,\n '$[*] ? (@.type() != \"string\" || !(@ like_regex \"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\"))')\n ELSE false END"); + + t.HasCheckConstraint("ck_data_subject_requests_status", "((kind = 'export' AND status IN ('requested','fulfilling','completed','failed','cancelled'))\nOR (kind = 'erasure' AND status IN ('scheduled','fulfilling','awaiting_privileged_step','completed','blocked','failed','cancelled'))\nOR (kind = 'closure' AND status IN ('scheduled','fulfilling','completed','cancelled'))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); + + t.HasCheckConstraint("ck_data_subject_requests_times", "(isfinite(created_at) AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at)) AND (execute_at IS NULL OR isfinite(execute_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_subject_requests_window", "((kind IN ('erasure','closure') AND origin <> 'closure_fanout' AND execute_at = created_at + interval '24 hours') OR ((kind = 'export' OR origin = 'closure_fanout') AND execute_at IS NULL)) IS TRUE"); + }); + }); + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.FederationConnection", b => { b.Property("Id") @@ -1158,6 +1604,44 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportArtifact", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.DataSubjectRequest", null) + .WithMany() + .HasForeignKey("TenantId", "RequestId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_export_artifacts_request"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataExportTicket", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.DataExportArtifact", null) + .WithMany() + .HasForeignKey("TenantId", "ArtifactId") + .HasPrincipalKey("TenantId", "Id") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_export_tickets_artifact"); + }); + + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.DataSubjectRequest", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("RequesterUserId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_data_subject_requests_requester"); + + b.HasOne("LearnStack.Modules.Identity.Domain.User", null) + .WithMany() + .HasForeignKey("SubjectUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_data_subject_requests_subject"); + }); + modelBuilder.Entity("LearnStack.Modules.Identity.Domain.Invitation", b => { b.HasOne("LearnStack.Modules.Identity.Domain.User", null) diff --git a/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs b/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs index 3f2bc234..64d7abfe 100644 --- a/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs @@ -74,7 +74,7 @@ public void User_Aggregate_Has_No_TenantScoped_Columns() context.Model.GetEntityTypes().Select(entity => entity.GetTableName()) .Should().BeEquivalentTo(["users", "identity_authority", "memberships", "membership_profiles", "membership_role_assignments", "roles", "role_permission_grants", "invitations", "identity_provider_event_targets", - "federation_connections"]); + "federation_connections", "data_subject_requests", "data_export_artifacts", "data_export_tickets"]); var user = context.Model.FindEntityType(typeof(User))!; user.GetProperties().Should().HaveCount(14); user.FindProperty("TenantId").Should().BeNull(); diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs index 743c6291..9be6929e 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs @@ -874,6 +874,14 @@ public void The_Soft_Delete_Index_Sweep_Can_Actually_Fail() "ADR-0095 permanently reserves every definition revision, including discarded Drafts", ["MembershipFieldConsent.ux_membership_field_consents_tuple_sequence"] = "ADR-0095 retains immutable consent history and its exact tuple sequence; no soft-delete writer exists", + // ADR-0106/0107 request receipts: ck_*_no_delete refuses deleted_at outright, so these indexes are partial on + // their lifecycle, not on a soft delete that cannot happen. + ["DataSubjectRequest.ux_data_subject_requests_active"] = + "ADR-0106 § 7 holds one non-terminal request per kind, subject and group; requests are never soft-deleted", + ["DataExportArtifact.ux_data_export_artifacts_request"] = + "ADR-0107 § 4: one artifact per export request, kept as the receipt; artifacts are never soft-deleted", + ["DataExportArtifact.ux_data_export_artifacts_available"] = + "ADR-0107 § 4: at most one available artifact per subject and group; artifacts are never soft-deleted", }; private static bool IsSoftDeletable(IReadOnlyEntityType entity) => diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestSchemaSeed.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestSchemaSeed.cs new file mode 100644 index 00000000..2209bcf2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestSchemaSeed.cs @@ -0,0 +1,121 @@ +using Npgsql; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0106/0107 rows for the nonempty isolation census, written by the application role under the +/// canonical fences. Tenant A holds a completed export (artifact, ticket and chunk) in its tenant-wide +/// group and in each of its two organizations; tenant B holds one in its tenant-wide group and a +/// requested export in its organization. +/// +internal static class DataRequestSchemaSeed +{ + internal static readonly Guid SystemActor = Guid.Parse("00000000-0000-7000-8000-000000000001"); + + internal sealed record Row(Guid Tenant, Guid? Organization, Guid Subject, Guid Membership, Guid Request, + Guid? Artifact, Guid? Ticket); + + internal static readonly Row TenantWideA = new(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA, + Guid.Parse("01930000-0000-7000-8000-00000000da01"), Guid.Parse("01930000-0000-7000-8000-00000000db01"), + Guid.Parse("01930000-0000-7000-8000-00000000dc01")); + + internal static readonly Row BranchA1 = new(SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, BranchMembershipA1, + Guid.Parse("01930000-0000-7000-8000-00000000da02"), Guid.Parse("01930000-0000-7000-8000-00000000db02"), + Guid.Parse("01930000-0000-7000-8000-00000000dc02")); + + internal static readonly Row BranchA2 = new(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, BranchMembershipA2, + Guid.Parse("01930000-0000-7000-8000-00000000da03"), Guid.Parse("01930000-0000-7000-8000-00000000db03"), + Guid.Parse("01930000-0000-7000-8000-00000000dc03")); + + internal static readonly Row TenantWideB = new(SchemaFixture.TenantB, null, AdminB, AdminMembershipB, + Guid.Parse("01930000-0000-7000-8000-00000000da11"), Guid.Parse("01930000-0000-7000-8000-00000000db11"), + Guid.Parse("01930000-0000-7000-8000-00000000dc11")); + + internal static readonly Row BranchB = new(SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, BranchMembershipB, + Guid.Parse("01930000-0000-7000-8000-00000000da12"), null, null); + + internal static readonly Row[] Rows = [TenantWideA, BranchA1, BranchA2, TenantWideB, BranchB]; + + internal static async Task SeedAsync(string connectionString) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await SchemaQueries.AssertApplicationRoleAsync(connection); + foreach (var row in Rows) + { + await using var transaction = await connection.BeginTransactionAsync(); + await FenceAsync(connection, transaction, row.Tenant, row.Organization, row.Subject); + await InsertRequestAsync(connection, transaction, row.Request, row.Tenant, row.Organization, row.Subject, [row.Membership]); + if (row.Artifact is { } artifact) + await CompleteExportAsync(connection, transaction, row, artifact, row.Ticket!.Value); + await transaction.CommitAsync(); + } + } + + /// Announces the group, then takes the subject's exclusive User fence and the shared tenant fence. + internal static async Task FenceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, + Guid? organization, Guid? subject) + { + await ScopeAsync(connection, transaction, tenant, organization); + await LockAsync(connection, transaction, tenant, subject, false); + } + + internal static string Snapshot(params Guid[] memberships) => + "[" + string.Join(",", memberships.Select(id => "\"" + id.ToString("D") + "\"")) + "]"; + + /// A self-filed request in its initial state; the clock is the transaction's. + internal static Task InsertRequestAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid id, Guid tenant, + Guid? organization, Guid subject, Guid[] memberships, string kind = "export") => + ExecuteAsync(connection, transaction, """ + INSERT INTO public.data_subject_requests(id,tenant_id,organization_id,kind,origin,subject_user_id,requester_user_id, + status,membership_snapshot,execute_at,created_at,created_by) + VALUES(@id,@tenant,@organization,@kind,'self',@subject,@subject, + CASE WHEN @kind='export' THEN 'requested' ELSE 'scheduled' END,@snapshot::jsonb, + CASE WHEN @kind='export' THEN NULL ELSE now() + interval '24 hours' END,now(),@subject) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("kind", kind), ("subject", subject), + ("snapshot", Snapshot(memberships))); + + /// One status step by the system actor, stamped with the transaction clock. + internal static Task StepAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid id, string set) => + ExecuteAsync(connection, transaction, + $"UPDATE public.data_subject_requests SET {set},row_version=row_version+1,updated_at=now(),updated_by=@system WHERE id=@id", + ("id", id), ("system", SystemActor)); + + /// fulfilling, the artifact and its chunks, completed, then the subject's ticket. + internal static async Task CompleteExportAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Row row, + Guid artifact, Guid ticket) + { + await StepAsync(connection, transaction, row.Request, "status='fulfilling'"); + await InsertArtifactAsync(connection, transaction, artifact, row.Tenant, row.Organization, row.Request, row.Subject, 100); + await InsertChunkAsync(connection, transaction, row.Tenant, row.Organization, artifact, 0); + await StepAsync(connection, transaction, row.Request, "status='completed',completed_at=now()"); + await InsertTicketAsync(connection, transaction, ticket, row.Tenant, row.Organization, artifact, row.Subject); + } + + internal static Task InsertArtifactAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid id, Guid tenant, + Guid? organization, Guid request, Guid subject, long bytes) => + ExecuteAsync(connection, transaction, """ + INSERT INTO public.data_export_artifacts(id,tenant_id,organization_id,request_id,subject_user_id,status,byte_count, + chunk_count,key_version,expires_at,created_at,created_by) + VALUES(@id,@tenant,@organization,@request,@subject,'available',@bytes,(@bytes + 131071) / 131072,'v1', + now() + interval '7 days',now(),@system) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("request", request), ("subject", subject), + ("bytes", bytes), ("system", SystemActor)); + + internal static Task InsertChunkAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, + Guid? organization, Guid artifact, int index, int nonce = 12, int ciphertext = 100, int tag = 16) => + ExecuteAsync(connection, transaction, """ + INSERT INTO public.data_export_chunks(tenant_id,organization_id,artifact_id,chunk_index,nonce,ciphertext,tag) + VALUES(@tenant,@organization,@artifact,@index,@nonce,@ciphertext,@tag) + """, ("tenant", tenant), ("organization", organization), ("artifact", artifact), ("index", index), + ("nonce", new byte[nonce]), ("ciphertext", new byte[ciphertext]), ("tag", new byte[tag])); + + internal static Task InsertTicketAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid id, Guid tenant, + Guid? organization, Guid artifact, Guid subject) => + ExecuteAsync(connection, transaction, """ + INSERT INTO public.data_export_tickets(id,tenant_id,organization_id,artifact_id,digest,session_binding_digest, + created_at,created_by,expires_at) + VALUES(@id,@tenant,@organization,@artifact,sha256(uuid_send(@id)),sha256(uuid_send(@artifact)), + now(),@subject,now() + interval '15 minutes') + """, ("id", id), ("tenant", tenant), ("organization", organization), ("artifact", artifact), ("subject", subject)); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageControlTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageControlTests.cs new file mode 100644 index 00000000..8a828511 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageControlTests.cs @@ -0,0 +1,262 @@ +using FluentAssertions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The data-request storage controls that must commit, or that need one other layer removed to be observed alone: +/// the concurrent-creation race, the guard's snapshot immutability behind a deliberately widened grant, and the +/// 24-hour window and 7-day expiry against backdated rows. Each runs in its own disposable database (Database +/// Standards § Parent organization mirrors: a control removal commits before a separate application connection tests +/// the remaining layer), so the shared schema stays untouched. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataRequestStorageControlTests(SchemaFixture schema) +{ + [Fact] + public async Task Concurrent_creations_for_one_subject_and_group_cannot_both_commit() + { + await using var database = await SeededAsync(); + await using var first = await OpenAppAsync(database); + await using var second = await OpenAppAsync(database); + + // With the guard live: the subject's User fence serializes the two creations and the index refuses the loser. + await using (var winner = await first.BeginTransactionAsync()) + { + await FenceAsync(first, winner, SchemaFixture.TenantA, null, AdminA); + await InsertRequestAsync(first, winner, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + await using var loser = await second.BeginTransactionAsync(); + var contender = Task.Run(async () => + { + await FenceAsync(second, loser, SchemaFixture.TenantA, null, AdminA); + await InsertRequestAsync(second, loser, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + }); + (await Task.WhenAny(contender, Task.Delay(TimeSpan.FromSeconds(1)))).Should().NotBe(contender, + "the contender waits on the subject's fence while the winner is open"); + await winner.CommitAsync(); + var refusal = (await FluentActions.Awaiting(() => contender).Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be(PostgresErrorCodes.UniqueViolation); + refusal.ConstraintName.Should().Be("ux_data_subject_requests_active"); + } + + // With the guard removed, the partial unique index alone still decides an in-flight race. + await using (var owner = await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await SchemaQueries.ExecuteAsync(owner, null, + "ALTER TABLE public.data_subject_requests DISABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await using (var winner = await first.BeginTransactionAsync()) + { + await ScopeAsync(first, winner, SchemaFixture.TenantA); + await InsertRequestAsync(first, winner, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA], "erasure"); + await using var loser = await second.BeginTransactionAsync(); + await ScopeAsync(second, loser, SchemaFixture.TenantA); + var contender = InsertRequestAsync(second, loser, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, + [AdminMembershipA], "erasure"); + (await Task.WhenAny(contender, Task.Delay(TimeSpan.FromSeconds(1)))).Should().NotBe(contender, + "the second insert waits on the first's uncommitted index entry"); + await winner.CommitAsync(); + (await FluentActions.Awaiting(() => contender).Should().ThrowAsync()).Which.ConstraintName + .Should().Be("ux_data_subject_requests_active"); + } + + await using var reader = await OpenAppAsync(database); + await using var read = await reader.BeginTransactionAsync(); + await ScopeAsync(reader, read, SchemaFixture.TenantA); + (await ScalarAsync(reader, read, """ + SELECT string_agg(kind || ':' || count, ',' ORDER BY kind) FROM (SELECT kind, count(*) FROM public.data_subject_requests + WHERE subject_user_id=@subject GROUP BY kind) rows + """, ("subject", AdminA))).Should().Be("erasure:1,export:1", "exactly one creation of each race committed"); + } + + [Fact] + public async Task The_guard_refuses_every_snapshot_change_even_where_a_grant_would_allow_it() + { + await using var database = await SeededAsync(); + await using (var owner = await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await SchemaQueries.ExecuteAsync(owner, null, """ + GRANT UPDATE (organization_id, kind, origin, subject_user_id, requester_user_id, membership_snapshot, execute_at, + created_at, created_by) ON public.data_subject_requests TO learnstack_app + """); + await using var app = await OpenAppAsync(database); + foreach (var set in new[] + { + "kind='erasure'", + "origin='administrator'", + $"subject_user_id='{AdminA}'", + $"requester_user_id='{AdminA}'", + $"membership_snapshot='{Snapshot(LearnerMembershipA, BranchMembershipA1)}'", + "execute_at=now()", + "created_at=created_at - interval '1 second'", + $"created_by='{AdminA}'", + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, null); + var act = () => StepAsync(app, transaction, TenantWideA.Request, set); + var refusal = (await act.Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be("23514", set); + refusal.MessageText.Should().Be("Data request immutable state refused.", set); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1, null); + var act = () => StepAsync(app, transaction, BranchA1.Request, $"organization_id='{SchemaFixture.OrgA2}'"); + (await act.Should().ThrowAsync()).Which.MessageText.Should().Be("Data request immutable state refused.", + "the guard fires before the shared organization immutability trigger, and both refuse the move"); + } + } + + [Fact] + public async Task The_window_and_the_expiry_are_database_clock_checks() + { + await using var database = await SeededAsync(); + var erasure = Guid.CreateVersion7(); + var lateErasure = Guid.CreateVersion7(); + await using (var app = await OpenAppAsync(database)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, null, AdminB); + await InsertRequestAsync(app, transaction, erasure, SchemaFixture.TenantB, null, AdminB, [AdminMembershipB], "erasure"); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonB, false); + await ScopeAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1); + await InsertRequestAsync(app, transaction, lateErasure, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, [BranchMembershipB], "erasure"); + await transaction.CommitAsync(); + } + + // Backdate as the owner with every application guard paused, then restore them: the rows are what a request + // filed 25 hours ago and an artifact completed 8 days ago look like. + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + { + await using var transaction = await owner.BeginTransactionAsync(); + foreach (var table in SchemaTableClasses.IdentityDataRequest.Where(table => table != "data_export_chunks")) + await ExecuteAsync(owner, transaction, $"ALTER TABLE public.{table} DISABLE TRIGGER tg_{table}_mutation_guard"); + foreach (var (tenant, organization, request) in new (Guid, Guid?, Guid)[] + { + (SchemaFixture.TenantB, null, erasure), (SchemaFixture.TenantB, SchemaFixture.OrgB1, lateErasure), + }) + { + await ScopeAsync(owner, transaction, tenant, organization); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_subject_requests SET created_at=created_at - interval '25 hours', + execute_at=execute_at - interval '25 hours' WHERE id=@id + """, ("id", request)); + } + await ScopeAsync(owner, transaction, SchemaFixture.TenantB); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_export_artifacts SET created_at=created_at - interval '8 days', + expires_at=expires_at - interval '8 days' WHERE id=@artifact; + UPDATE public.data_export_tickets SET created_at=created_at - interval '8 days', + expires_at=expires_at - interval '8 days' WHERE id=@ticket; + UPDATE public.data_subject_requests SET created_at=created_at - interval '8 days', + completed_at=completed_at - interval '8 days', updated_at=updated_at - interval '8 days' WHERE id=@request + """, ("artifact", TenantWideB.Artifact!.Value), ("ticket", TenantWideB.Ticket!.Value), ("request", TenantWideB.Request)); + // The artifact's deferred completeness check must run before its table can be altered again. + await ExecuteAsync(owner, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + foreach (var table in SchemaTableClasses.IdentityDataRequest.Where(table => table != "data_export_chunks")) + await ExecuteAsync(owner, transaction, $"ALTER TABLE public.{table} ENABLE TRIGGER tg_{table}_mutation_guard"); + await transaction.CommitAsync(); + } + + await using var connection = await OpenAppAsync(database); + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + var cancel = () => StepAsync(connection, transaction, erasure, "status='cancelled'"); + (await cancel.Should().ThrowAsync()).Which.MessageText.Should().Be("Data request transition refused.", + "the cancellable window has closed"); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + await StepAsync(connection, transaction, erasure, "status='fulfilling'"); + await StepAsync(connection, transaction, erasure, "status='awaiting_privileged_step'"); + var complete = () => StepAsync(connection, transaction, erasure, "status='completed',completed_at=now()"); + (await complete.Should().ThrowAsync()).Which.MessageText.Should().Be("Data request transition refused.", + "only the operator's privileged step completes an erasure"); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + await StepAsync(connection, transaction, lateErasure, "status='fulfilling'"); + await StepAsync(connection, transaction, lateErasure, "status='blocked',last_refusal='blocked_last_administrator'"); + await transaction.RollbackAsync(); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + var artifact = TenantWideB.Artifact!.Value; + var revoke = () => ExecuteAsync(connection, transaction, """ + UPDATE public.data_export_artifacts SET status='revoked',purged_at=now(),row_version=row_version+1, + updated_at=now(),updated_by=@system WHERE id=@id + """, ("id", artifact), ("system", SystemActor)); + (await revoke.Should().ThrowAsync()).Which.MessageText.Should().Be("Data export artifact transition refused.", + "an expired artifact is purged, not revoked"); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + var artifact = TenantWideB.Artifact!.Value; + var mint = () => InsertTicketAsync(connection, transaction, Guid.CreateVersion7(), SchemaFixture.TenantB, null, artifact, AdminB); + (await mint.Should().ThrowAsync()).Which.MessageText.Should().Be("Data export ticket artifact refused.", + "expiry is a time check whether or not the purge ran"); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + var consume = () => ExecuteAsync(connection, transaction, + "UPDATE public.data_export_tickets SET consumed_at=created_at WHERE id=@id", ("id", TenantWideB.Ticket!.Value)); + (await consume.Should().ThrowAsync()).Which.MessageText.Should().Be("Data export ticket consumption refused."); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await FenceAsync(connection, transaction, SchemaFixture.TenantB, null, null); + var artifact = TenantWideB.Artifact!.Value; + await ExecuteAsync(connection, transaction, """ + UPDATE public.data_export_artifacts SET status='expired',row_version=row_version+1,updated_at=now(),updated_by=@system + WHERE id=@id + """, ("id", artifact), ("system", SystemActor)); + await ExecuteAsync(connection, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(connection, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", artifact)); + await ExecuteAsync(connection, transaction, """ + UPDATE public.data_export_artifacts SET status='purged',purged_at=now(),row_version=row_version+1,updated_at=now(), + updated_by=@system WHERE id=@id + """, ("id", artifact), ("system", SystemActor)); + await transaction.CommitAsync(); + } + + await using (var transaction = await connection.BeginTransactionAsync()) + { + await ScopeAsync(connection, transaction, SchemaFixture.TenantB); + (await ScalarAsync(connection, transaction, """ + SELECT a.status || ':' || (a.purged_at IS NOT NULL)::text || ':' + || (SELECT count(*) FROM public.data_export_chunks c WHERE c.artifact_id = a.id)::text + FROM public.data_export_artifacts a WHERE a.id = @id + """, ("id", TenantWideB.Artifact!.Value))).Should().Be("purged:true:0", + "an expired artifact is purged; its metadata row stays as the receipt"); + } + } + + private async Task SeededAsync() + { + var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + return database; + } + + private static async Task OpenAppAsync(DisposableSchemaDatabase database) + { + var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + return app; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs new file mode 100644 index 00000000..a023cb06 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs @@ -0,0 +1,643 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// P03-10 Step 1 storage proof for data_subject_requests, data_export_artifacts, +/// data_export_tickets and data_export_chunks (ADR-0106 § 7–8, ADR-0107 § 4 and § 8), connected as +/// learnstack_app against the nonempty seeded schema. Every case rolls back; the controls that must commit +/// or widen a privilege live in . +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataRequestStorageTests(SchemaFixture schema) +{ + private static readonly string[] AppRequestUpdate = ["status", "row_version", "progress", "result", "last_refusal", + "failure_reason", "completed_at", "updated_at", "updated_by"]; + private static readonly string[] AppArtifactUpdate = ["status", "purged_at", "row_version", "updated_at", "updated_by"]; + private static readonly string[] PlatformRequestSelect = ["id", "tenant_id", "organization_id", "kind", "origin", + "subject_user_id", "status", "membership_snapshot", "execute_at", "progress", "result", "last_refusal", "failure_reason", + "completed_at", "created_at", "row_version"]; + private static readonly string[] PlatformRequestUpdate = ["status", "row_version", "completed_at", "result"]; + private static readonly string[] AppTableGrants = + [ + "data_subject_requests:learnstack_app:INSERT", "data_subject_requests:learnstack_app:SELECT", + "data_export_artifacts:learnstack_app:INSERT", "data_export_artifacts:learnstack_app:SELECT", + "data_export_tickets:learnstack_app:INSERT", "data_export_tickets:learnstack_app:SELECT", + "data_export_chunks:learnstack_app:DELETE", "data_export_chunks:learnstack_app:INSERT", "data_export_chunks:learnstack_app:SELECT", + "data_export_tickets.consumed_at:learnstack_app:UPDATE", + ]; + private static readonly string[] UnreadActors = ["requester_user_id", "created_by", "updated_by", "deleted_by"]; + + public static TheoryData Tables() + { + var data = new TheoryData(); + foreach (var table in SchemaTableClasses.IdentityDataRequest) data.Add(table); + return data; + } + + [Theory] + [MemberData(nameof(Tables))] + public async Task Each_tenant_and_group_reads_only_its_own_rows(string table) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + (await CountAsync(app, transaction, table)).Should().Be(1, "tenant A's tenant-wide group alone, without an organization"); + (await CountAsync(app, transaction, table, $"tenant_id='{SchemaFixture.TenantB}'")).Should().Be(0, + "tenant B's seeded rows exist and are invisible"); + + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + (await CountAsync(app, transaction, table)).Should().Be(2, "the tenant-wide row and organization A1's"); + (await CountAsync(app, transaction, table, $"organization_id='{SchemaFixture.OrgA2}'")).Should().Be(0, + "organization A2's seeded row is invisible to organization A1"); + + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA2); + (await CountAsync(app, transaction, table, $"organization_id='{SchemaFixture.OrgA1}'")).Should().Be(0); + (await CountAsync(app, transaction, table, $"organization_id='{SchemaFixture.OrgA2}'")).Should().Be(1); + + await ScopeAsync(app, transaction, SchemaFixture.TenantB); + (await CountAsync(app, transaction, table)).Should().Be(1); + (await CountAsync(app, transaction, table, $"tenant_id='{SchemaFixture.TenantA}'")).Should().Be(0); + + await ExecuteAsync(app, transaction, "SELECT set_config('app.tenant_id','',true),set_config('app.organization_id','',true)"); + (await CountAsync(app, transaction, table)).Should().Be(0, "no tenant context reads nothing"); + } + + [Theory] + [MemberData(nameof(Tables))] + public async Task The_organization_write_guards_refuse_another_organization_and_the_tenant_wide_row(string table) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await SchemaQueries.SetSettingAsync(app, transaction, "app.scope", "tenant"); + (await CountAsync(app, transaction, table, $"organization_id='{SchemaFixture.OrgA2}'")).Should().Be(1, + "the tenant-scope read hatch shows organization A2's row, so the zero below is the write guard"); + (await CountAsync(app, transaction, table, "organization_id IS NULL")).Should().Be(1); + + var write = table switch + { + "data_subject_requests" => "UPDATE public.data_subject_requests SET row_version=row_version WHERE {0}", + "data_export_artifacts" => "UPDATE public.data_export_artifacts SET row_version=row_version WHERE {0}", + "data_export_tickets" => "UPDATE public.data_export_tickets SET consumed_at=consumed_at WHERE {0}", + _ => "DELETE FROM public.data_export_chunks WHERE {0}", + }; + (await ExecuteCountAsync(app, transaction, string.Format(System.Globalization.CultureInfo.InvariantCulture, write, + $"organization_id='{SchemaFixture.OrgA2}'"))).Should().Be(0, "another organization's row is not writable"); + (await ExecuteCountAsync(app, transaction, string.Format(System.Globalization.CultureInfo.InvariantCulture, write, + "organization_id IS NULL"))).Should().Be(0, "an organization session does not write the tenant-wide row"); + } + + [Fact] + public async Task A_foreign_tenant_row_is_neither_inserted_nor_updated() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, AdminA); + var insert = await RefuseAsync(transaction, () => InsertRequestAsync(app, transaction, Guid.CreateVersion7(), + SchemaFixture.TenantB, null, AdminB, [AdminMembershipB])); + insert.SqlState.Should().Be("P0301", "the BEFORE guard's tenant fence binds the row to the announced tenant first"); + insert.ConstraintName.Should().Be("identity_tenant_fence"); + (await ExecuteCountAsync(app, transaction, "UPDATE public.data_subject_requests SET row_version=row_version WHERE id=@id", + ("id", TenantWideB.Request))).Should().Be(0, "USING hides the foreign row"); + (await ExecuteCountAsync(app, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", + ("id", TenantWideB.Artifact!.Value))).Should().Be(0); + (await ExecuteCountAsync(app, transaction, "UPDATE public.data_export_tickets SET consumed_at=created_at WHERE id=@id", + ("id", TenantWideB.Ticket!.Value))).Should().Be(0); + } + + [Fact] + public async Task One_non_terminal_request_per_kind_subject_and_group_and_a_terminal_one_frees_the_slot() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, AdminA); + var first = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, first, SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + + var duplicate = await RefuseAsync(transaction, () => InsertRequestAsync(app, transaction, Guid.CreateVersion7(), + SchemaFixture.TenantA, null, AdminA, [AdminMembershipA])); + duplicate.SqlState.Should().Be(PostgresErrorCodes.UniqueViolation); + duplicate.ConstraintName.Should().Be("ux_data_subject_requests_active", + "the tenant-wide group's NULL organization is not distinct, so the second export collides"); + + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA], "erasure"); + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA], "closure"); + (await RefuseAsync(transaction, () => InsertRequestAsync(app, transaction, Guid.CreateVersion7(), + SchemaFixture.TenantA, null, AdminA, [AdminMembershipA], "erasure"))).ConstraintName.Should().Be("ux_data_subject_requests_active"); + + await StepAsync(app, transaction, first, "status='cancelled'"); + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + + // PersonA's seeded tenant-wide export is completed, so a new one is admitted in that group. + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + (await CountAsync(app, transaction, "data_subject_requests", + $"subject_user_id='{AdminA}' AND status IN ('requested','scheduled','fulfilling','awaiting_privileged_step')")) + .Should().Be(3, "one active export, erasure and closure"); + } + + public static TheoryData RefusedInserts() => new() + { + { "no-user-fence", "P0301", "identity_user_fence" }, + { "no-tenant-fence", "P0301", "identity_tenant_fence" }, + { "initial-status", "23514", "Data request initial state refused." }, + { "foreign-actor", "23514", "Data request initial state refused." }, + { "nonzero-version", "23514", "Data request initial state refused." }, + { "stale-clock", "23514", "Data request initial state refused." }, + { "tenant-wide-membership", "23514", "Data request snapshot refused." }, + { "other-organization-membership", "23514", "Data request snapshot refused." }, + { "incomplete-snapshot", "23514", "Data request snapshot refused." }, + { "empty-snapshot", "23514", "Data request snapshot refused." }, + { "administrator-closure", "23514", "ck_data_subject_requests_origin" }, + { "self-requester-mismatch", "23514", "ck_data_subject_requests_requester" }, + }; + + [Theory] + [MemberData(nameof(RefusedInserts))] + public async Task The_request_guard_refuses_an_unfenced_malformed_or_inexact_creation(string variant, string sqlState, string reason) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + if (variant != "no-tenant-fence") + await LockAsync(app, transaction, SchemaFixture.TenantA, variant == "no-user-fence" ? null : PersonA, false); + else + await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)))); + if (variant == "incomplete-snapshot") + { + // A Revoked tombstone stays the person's Membership in the group; the snapshot must name it too. + await ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked',deleted_at=clock_timestamp(),deleted_by=@actor, + updated_at=clock_timestamp(),updated_by=@actor,row_version=row_version+1 WHERE id=@member + """, ("member", BranchMembershipA1), ("actor", AdminA)); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1, Guid.CreateVersion7(), PersonA, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Organization)); + } + + var (status, origin, requester, createdBy, version, createdAt, snapshot) = variant switch + { + "initial-status" => ("fulfilling", "self", PersonA, PersonA, 0L, "now()", Snapshot(BranchMembershipA1)), + "foreign-actor" => ("requested", "self", PersonA, AdminA, 0L, "now()", Snapshot(BranchMembershipA1)), + "nonzero-version" => ("requested", "self", PersonA, PersonA, 1L, "now()", Snapshot(BranchMembershipA1)), + "stale-clock" => ("requested", "self", PersonA, PersonA, 0L, "now() - interval '1 hour'", Snapshot(BranchMembershipA1)), + "tenant-wide-membership" => ("requested", "self", PersonA, PersonA, 0L, "now()", Snapshot(LearnerMembershipA)), + "other-organization-membership" => ("requested", "self", PersonA, PersonA, 0L, "now()", Snapshot(BranchMembershipA2)), + "empty-snapshot" => ("requested", "self", PersonA, PersonA, 0L, "now()", "[]"), + "administrator-closure" => ("scheduled", "administrator", AdminA, AdminA, 0L, "now()", Snapshot(BranchMembershipA1)), + "self-requester-mismatch" => ("requested", "self", AdminA, AdminA, 0L, "now()", Snapshot(BranchMembershipA1)), + _ => ("requested", "self", PersonA, PersonA, 0L, "now()", Snapshot(BranchMembershipA1)), + }; + var kind = variant == "administrator-closure" ? "closure" : "export"; + var refusal = await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, $""" + INSERT INTO public.data_subject_requests(id,tenant_id,organization_id,kind,origin,subject_user_id,requester_user_id, + status,membership_snapshot,execute_at,created_at,created_by,row_version) + VALUES(@id,@tenant,@organization,@kind,@origin,@subject,@requester,@status,@snapshot::jsonb, + CASE WHEN @kind='export' THEN NULL ELSE ({createdAt}) + interval '24 hours' END,{createdAt},@created_by,@version) + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), + ("kind", kind), ("origin", origin), ("subject", PersonA), ("requester", requester), ("status", status), + ("snapshot", snapshot), ("created_by", createdBy), ("version", version))); + refusal.SqlState.Should().Be(sqlState); + if (sqlState == "P0301" || reason.StartsWith("ck_", StringComparison.Ordinal)) + refusal.ConstraintName.Should().Be(reason); + else + refusal.MessageText.Should().Be(reason); + } + + public static TheoryData RefusedUpdates() => new() + { + { "requested-to-completed", "status='completed',completed_at=now()", "Data request transition refused." }, + { "requested-to-awaiting", "status='awaiting_privileged_step'", "Data request transition refused." }, + { "requested-to-failed", "status='failed',failure_reason='execution_failed'", "Data request failure record refused." }, + { "progress-outside-fulfilling", "progress='{\"identity\":\"2026-11-22T09:00:00.0000000Z\"}'", "Data request progress refused." }, + { "result-outside-fulfilling", "result='{\"request_receipt\":1}'", "Data request result refused." }, + { "refusal-on-requested", "last_refusal='blocked_hold'", "Data request refusal record refused." }, + { "completion-stamp-alone", "completed_at=now()", "Data request completion refused." }, + }; + + [Theory] + [MemberData(nameof(RefusedUpdates))] + public async Task The_request_guard_refuses_every_application_arrow_outside_ADR_0106_section_8(string variant, string set, string reason) + { + _ = variant; + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + var refusal = await RefuseAsync(transaction, () => StepAsync(app, transaction, BranchB.Request, set)); + refusal.SqlState.Should().Be("23514"); + refusal.MessageText.Should().Be(reason); + } + + [Fact] + public async Task Version_stamps_terminal_states_and_privileged_arrows_are_refused_and_legal_arrows_admitted() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantB, null, null); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_subject_requests SET status='cancelled',updated_at=now(),updated_by=@system WHERE id=@id", + ("id", TenantWideB.Request), ("system", SystemActor)))).MessageText.Should().Be("Data request immutable state refused.", + "every update advances the row version by one"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, TenantWideB.Request, "status='cancelled'"))) + .MessageText.Should().Be("Data request is terminal."); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "DELETE FROM public.data_subject_requests WHERE id=@id", ("id", TenantWideB.Request)))).SqlState.Should().Be("42501", + "no application DELETE exists: requests are retained receipts"); + + await LockAsync(app, transaction, SchemaFixture.TenantB, AdminB, false); + var erasure = Guid.CreateVersion7(); + var closure = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, erasure, SchemaFixture.TenantB, null, AdminB, [AdminMembershipB], "erasure"); + await InsertRequestAsync(app, transaction, closure, SchemaFixture.TenantB, null, AdminB, [AdminMembershipB], "closure"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, erasure, "status='fulfilling'"))) + .MessageText.Should().Be("Data request transition refused.", "an erasure executes only after its 24-hour window"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, closure, "status='fulfilling'"))) + .MessageText.Should().Be("Data request transition refused.", "a closure's Begin is an operator act, not the application's"); + await StepAsync(app, transaction, closure, "last_refusal='blocked_window'"); + await StepAsync(app, transaction, closure, "status='cancelled'"); + await StepAsync(app, transaction, erasure, "status='cancelled'"); + (await ScalarAsync(app, transaction, "SELECT string_agg(status||':'||row_version,',' ORDER BY kind) FROM public.data_subject_requests WHERE id IN (@a,@b)", + ("a", erasure), ("b", closure))).Should().Be("cancelled:2,cancelled:1"); + + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + await StepAsync(app, transaction, BranchB.Request, "status='fulfilling'"); + await StepAsync(app, transaction, BranchB.Request, "progress='{\"identity\":\"2026-11-22T09:00:00.0000000Z\"}'"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, BranchB.Request, "progress='{}'"))) + .MessageText.Should().Be("Data request progress refused.", "progress only grows"); + await StepAsync(app, transaction, BranchB.Request, "result='{\"request_receipt\":1}'"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, BranchB.Request, "status='failed'"))) + .ConstraintName.Should().Be("ck_data_subject_requests_outcome", "a failure carries its closed reason"); + await StepAsync(app, transaction, BranchB.Request, "status='failed',failure_reason='export_too_large'"); + } + + [Fact] + public async Task The_JSON_documents_are_bounded_by_their_CHECKs() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + await StepAsync(app, transaction, BranchB.Request, "status='fulfilling'"); + foreach (var (set, constraint) in new[] + { + ("progress='{\"Identity\":\"2026-11-22T09:00:00.0000000Z\"}'", "ck_data_subject_requests_progress"), + ("progress='{\"identity\":\"2026-11-22\"}'", "ck_data_subject_requests_progress"), + ("result='{\"anonymous\":1}'", "ck_data_subject_requests_result"), + ("result='{\"consent_evidence\":-1}'", "ck_data_subject_requests_result"), + ("result='{\"consent_evidence\":1.5}'", "ck_data_subject_requests_result"), + ("result='{\"consent_evidence\":\"1\"}'", "ck_data_subject_requests_result"), + }) + (await RefuseAsync(transaction, () => StepAsync(app, transaction, BranchB.Request, set))).ConstraintName.Should().Be(constraint, set); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonB, false); + var closure = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, closure, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, [BranchMembershipB], "closure"); + (await RefuseAsync(transaction, () => StepAsync(app, transaction, closure, "last_refusal='blocked_everything'"))) + .ConstraintName.Should().Be("ck_data_subject_requests_outcome", "a refusal is one of the closed codes"); + (await ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.data_subject_requests WHERE id=@id + AND jsonb_array_length(membership_snapshot)=1 AND progress='{}'::jsonb AND result='{}'::jsonb + """, ("id", BranchB.Request))).Should().Be(1); + } + + [Fact] + public async Task Chunk_CHECKs_bound_the_nonce_tag_ciphertext_and_index() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + var artifact = await AdminExportArtifactAsync(app, transaction, 2 * DataRequestLimits.ChunkPlaintextBytes + 1); + foreach (var (index, nonce, ciphertext, tag, constraint) in new (int, int, int, int, string)[] + { + (0, 11, 10, 16, "ck_data_export_chunks_nonce"), + (0, 13, 10, 16, "ck_data_export_chunks_nonce"), + (0, 12, 10, 15, "ck_data_export_chunks_tag"), + (0, 12, 10, 17, "ck_data_export_chunks_tag"), + (0, 12, 0, 16, "ck_data_export_chunks_ciphertext"), + (0, 12, DataRequestLimits.ChunkPlaintextBytes + 1, 16, "ck_data_export_chunks_ciphertext"), + (-1, 12, 10, 16, "ck_data_export_chunks_index"), + }) + (await RefuseAsync(transaction, () => InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, index, + nonce, ciphertext, tag))).ConstraintName.Should().Be(constraint); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 0, 12, DataRequestLimits.ChunkPlaintextBytes, 16); + (await RefuseAsync(transaction, () => InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 0))) + .ConstraintName.Should().Be("pk_data_export_chunks"); + (await RefuseAsync(transaction, () => InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 3))) + .MessageText.Should().Be("Data export chunk refused.", "an index at or past the artifact's chunk count is refused"); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_export_chunks SET nonce=nonce WHERE artifact_id=@id", ("id", artifact)))).SqlState.Should().Be("42501", + "chunks are written once and deleted, never updated"); + (await ScalarAsync(app, transaction, + "SELECT attstorage::text FROM pg_attribute WHERE attrelid='public.data_export_chunks'::regclass AND attname='ciphertext'")) + .Should().Be("e", "incompressible ciphertext is stored out of line without compression"); + } + + [Fact] + public async Task An_available_artifact_holds_exactly_its_chunks_and_a_revoked_one_none_at_commit() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + var artifact = await AdminExportArtifactAsync(app, transaction, 2 * DataRequestLimits.ChunkPlaintextBytes + 1); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 0); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 1); + var incomplete = await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE")); + incomplete.ConstraintName.Should().Be("data_export_artifact_chunks", "two of three chunks is not a stored bundle"); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 2); + await transaction.SaveAsync("complete"); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.RollbackAsync("complete"); + + await RevokeAsync(app, transaction, artifact); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"))) + .ConstraintName.Should().Be("data_export_artifact_chunks", "a revocation that leaves ciphertext behind is refused"); + (await ExecuteCountAsync(app, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", artifact))) + .Should().Be(3); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + (await RefuseAsync(transaction, () => InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 0))) + .MessageText.Should().Be("Data export chunk refused.", "a revoked artifact accepts no chunk"); + } + + [Fact] + public async Task The_artifact_guard_holds_its_request_lifecycle_and_one_available_artifact_per_subject_and_group() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + var first = await AdminExportArtifactAsync(app, transaction, 10); + var firstRequest = await ScalarAsync(app, transaction, "SELECT request_id FROM public.data_export_artifacts WHERE id=@id", ("id", first)); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, first, 0); + await StepAsync(app, transaction, firstRequest, "status='completed',completed_at=now()"); + + var second = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, second, SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + second, AdminA, 10))).MessageText.Should().Be("Data export artifact request refused.", "only a fulfilling export has an artifact"); + await StepAsync(app, transaction, second, "status='fulfilling'"); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + second, AdminA, 10))).ConstraintName.Should().Be("ux_data_export_artifacts_available", + "ADR-0107 § 4: a new export revokes the previous artifact first"); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + second, PersonA, 10))).MessageText.Should().Be("Data export artifact request refused.", "the subject mirrors the request's"); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, + SchemaFixture.OrgA1, second, AdminA, 10))).MessageText.Should().StartWith("parent scope is unavailable or mismatched", + "the group mirrors the request's"); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + TenantWideA.Request, PersonA, 10))).MessageText.Should().Be("Data export artifact request refused.", + "a request completed in an earlier transaction gains no artifact"); + + foreach (var (set, reason) in new[] + { + ("status='expired'", "Data export artifact transition refused."), + ("status='purged',purged_at=now()", "Data export artifact transition refused."), + ("status='revoked'", "Data export artifact transition refused."), + }) + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + $"UPDATE public.data_export_artifacts SET {set},row_version=row_version+1,updated_at=now(),updated_by=@system WHERE id=@id", + ("id", first), ("system", SystemActor)))).MessageText.Should().Be(reason, set); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_export_artifacts SET byte_count=byte_count WHERE id=@id", ("id", first)))).SqlState.Should().Be("42501", + "the size is not an application-writable column"); + + await RevokeAsync(app, transaction, first); + await ExecuteAsync(app, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", first)); + var replacement = Guid.CreateVersion7(); + await InsertArtifactAsync(app, transaction, replacement, SchemaFixture.TenantA, null, second, AdminA, 10); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, replacement, 0); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + } + + [Fact] + public async Task Only_the_subject_mints_a_ticket_and_it_is_consumed_once() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + var artifact = await AdminExportArtifactAsync(app, transaction, 10); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, artifact, 0); + (await RefuseAsync(transaction, () => InsertTicketAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + artifact, PersonA))).MessageText.Should().Be("Data export ticket artifact refused.", "ADR-0106 § 6: the recipient is the subject"); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, """ + INSERT INTO public.data_export_tickets(id,tenant_id,organization_id,artifact_id,digest,session_binding_digest, + created_at,created_by,expires_at,consumed_at) + VALUES(@id,@tenant,NULL,@artifact,sha256('a'::bytea),sha256('b'::bytea),now(),@subject,now()+interval '15 minutes',now()) + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("artifact", artifact), ("subject", AdminA)))) + .MessageText.Should().Be("Data export ticket initial state refused."); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, """ + INSERT INTO public.data_export_tickets(id,tenant_id,organization_id,artifact_id,digest,session_binding_digest, + created_at,created_by,expires_at) + VALUES(@id,@tenant,NULL,@artifact,'\x00'::bytea,sha256('b'::bytea),now(),@subject,now()+interval '15 minutes') + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("artifact", artifact), ("subject", AdminA)))) + .ConstraintName.Should().Be("ck_data_export_tickets_digests"); + + var ticket = Guid.CreateVersion7(); + await InsertTicketAsync(app, transaction, ticket, SchemaFixture.TenantA, null, artifact, AdminA); + (await ExecuteCountAsync(app, transaction, "UPDATE public.data_export_tickets SET consumed_at=now() WHERE id=@id", ("id", ticket))) + .Should().Be(1); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_export_tickets SET consumed_at=now() WHERE id=@id", ("id", ticket)))).MessageText + .Should().Be("Data export ticket consumption refused.", "a resumed download mints a new ticket"); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_export_tickets SET digest=digest WHERE id=@id", ("id", ticket)))).SqlState.Should().Be("42501", + "the consumed marker is the only application-writable column"); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "DELETE FROM public.data_export_tickets WHERE id=@id", ("id", ticket)))).SqlState.Should().Be("42501"); + + await RevokeAsync(app, transaction, artifact); + (await RefuseAsync(transaction, () => InsertTicketAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + artifact, AdminA))).MessageText.Should().Be("Data export ticket artifact refused.", "a revoked artifact mints no ticket"); + } + + [Fact] + public async Task The_grant_matrix_is_exactly_ADR_0107_section_8() + { + await using var owner = await PostgresFixture.OpenAsync(schema.Postgres.MigrationConnectionString); + var grants = await SchemaQueries.ReadStringsAsync(owner, """ + WITH tables AS (SELECT oid, relname, relowner, relacl FROM pg_class + WHERE oid IN ('public.data_subject_requests'::regclass,'public.data_export_artifacts'::regclass, + 'public.data_export_tickets'::regclass,'public.data_export_chunks'::regclass)) + SELECT t.relname || ':' || COALESCE(r.rolname, 'PUBLIC') || ':' || x.privilege_type + FROM tables t CROSS JOIN LATERAL aclexplode(t.relacl) x LEFT JOIN pg_roles r ON r.oid = x.grantee + WHERE x.grantee <> t.relowner + UNION ALL + SELECT t.relname || '.' || a.attname || ':' || COALESCE(r.rolname, 'PUBLIC') || ':' || x.privilege_type + FROM tables t JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum > 0 AND NOT a.attisdropped + CROSS JOIN LATERAL aclexplode(a.attacl) x LEFT JOIN pg_roles r ON r.oid = x.grantee + ORDER BY 1 + """); + var expected = AppTableGrants + .Concat(AppRequestUpdate.Select(column => $"data_subject_requests.{column}:learnstack_app:UPDATE")) + .Concat(AppArtifactUpdate.Select(column => $"data_export_artifacts.{column}:learnstack_app:UPDATE")) + .Concat(PlatformRequestSelect.Select(column => $"data_subject_requests.{column}:learnstack_platform:SELECT")) + .Concat(PlatformRequestUpdate.Select(column => $"data_subject_requests.{column}:learnstack_platform:UPDATE")); + grants.Should().BeEquivalentTo(expected, "PUBLIC, learnstack_outbox_admin and the two Identity machine roles hold nothing, " + + "and learnstack_platform holds only its closed request columns"); + PlatformRequestSelect.Should().NotContain(UnreadActors, + "the operator read names no actor beyond the subject"); + } + + [Fact] + public async Task The_platform_role_reads_only_its_closed_columns_and_writes_nothing_its_guard_has_not_admitted() + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(schema.Postgres.PlatformConnectionString); + (await ScalarAsync(platform, null, "SELECT count(*) FROM (SELECT id,tenant_id,status,membership_snapshot FROM public.data_subject_requests) rows")) + .Should().Be(Rows.Length, "BYPASSRLS reads every tenant's rows; the grant, not a policy, is the bound"); + foreach (var statement in new[] + { + "SELECT requester_user_id FROM public.data_subject_requests", + "SELECT * FROM public.data_subject_requests", + "INSERT INTO public.data_subject_requests(id) VALUES(uuidv7())", + "UPDATE public.data_subject_requests SET last_refusal='blocked_hold'", + "DELETE FROM public.data_subject_requests", + "SELECT count(*) FROM public.data_export_artifacts", + "UPDATE public.data_export_artifacts SET status='revoked'", + "SELECT count(*) FROM public.data_export_tickets", + "UPDATE public.data_export_tickets SET consumed_at=now()", + "SELECT count(*) FROM public.data_export_chunks", + "DELETE FROM public.data_export_chunks", + }) + { + await using var transaction = await platform.BeginTransactionAsync(); + var act = () => ExecuteAsync(platform, transaction, statement); + (await act.Should().ThrowAsync()).Which.SqlState.Should().Be("42501", statement); + } + + await using (var transaction = await platform.BeginTransactionAsync()) + { + var act = () => ExecuteAsync(platform, transaction, + "UPDATE public.data_subject_requests SET status='completed',completed_at=now(),row_version=row_version+1 WHERE id=@id", + ("id", BranchB.Request)); + var refusal = (await act.Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be("23514", "the grant reaches the guard, which admits no platform arm until Steps 2 and 3 add it"); + refusal.MessageText.Should().Be("Data request mutation refused."); + } + } + + [Fact] + public async Task The_aggregates_round_trip_through_EF_as_the_application_role() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using var frame = await unit.BeginTransactionAsync(); + var tenant = TenantId.From(SchemaFixture.TenantA); + var subject = UserId.From(AdminA); + await unit.SetProvisioningTenantContextAsync(tenant); + await new IdentityMutationLocks(unit).AcquireAsync(new([subject], tenant, IdentityTenantLockMode.Shared)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(unit.Connection).Options, + new StaticTenantContextAccessor(new SeedTenantContext(tenant, null)), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(unit.Transaction); + var now = DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + var group = new DataRequestScopeGroup(tenant, null); + + var request = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, subject, + group, [MembershipId.From(AdminMembershipA)], now).Value!; + db.Add(request); + await db.SaveChangesAsync(); + request.StartFulfilling(now.AddSeconds(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + await db.SaveChangesAsync(); + request.RecordParticipantCompleted("identity", now.AddSeconds(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + await db.SaveChangesAsync(); + var artifact = DataExportArtifact.Create(DataExportArtifactId.From(Guid.CreateVersion7()), request, + 2 * DataRequestLimits.ChunkPlaintextBytes + 7, "v1", now.AddSeconds(3), UserId.SystemActor).Value!; + db.Add(artifact); + await db.SaveChangesAsync(); + var connection = (NpgsqlConnection)unit.Connection; + var transaction = (NpgsqlTransaction)unit.Transaction!; + for (var index = 0; index < artifact.ChunkCount; index++) + await InsertChunkAsync(connection, transaction, SchemaFixture.TenantA, null, artifact.Id.Value, index); + request.Complete([new(RetainedReferenceKind.RequestReceipt, 1)], now.AddSeconds(4), UserId.SystemActor).IsSuccess.Should().BeTrue(); + await db.SaveChangesAsync(); + // The completeness check is deferred to commit; force it here, then return to the default. + await ExecuteAsync(connection, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(connection, transaction, "SET CONSTRAINTS ALL DEFERRED"); + var ticket = DataExportTicket.Mint(DataExportTicketId.From(Guid.CreateVersion7()), artifact, new string('c', 64), + new string('d', 64), now.AddSeconds(5), subject).Value!; + db.Add(ticket); + await db.SaveChangesAsync(); + ticket.Consume(now.AddSeconds(6)).IsSuccess.Should().BeTrue(); + await db.SaveChangesAsync(); + + db.ChangeTracker.Clear(); + var stored = await db.Set().SingleAsync(row => row.Id == request.Id); + stored.Status.Should().Be(DataRequestStatus.Completed); + stored.Kind.Should().Be(DataRequestKind.Export); + stored.Origin.Should().Be(DataRequestOrigin.Self); + stored.RequesterUserId.Should().Be(subject); + stored.SnapshotMembershipIds.Should().Equal(MembershipId.From(AdminMembershipA)); + stored.Progress.Should().BeEquivalentTo(new Dictionary { ["identity"] = now.AddSeconds(2) }); + stored.RetainedReport.Should().BeEquivalentTo(new Dictionary { [RetainedReferenceKind.RequestReceipt] = 1 }); + stored.CompletedAt.Should().Be(now.AddSeconds(4)); + stored.Version.Should().Be(3); + var storedArtifact = await db.Set().SingleAsync(row => row.Id == artifact.Id); + storedArtifact.ChunkCount.Should().Be(3); + storedArtifact.ExpiresAt.Should().Be(now.AddSeconds(3) + DataRequestLimits.ArtifactLifetime); + var storedTicket = await db.Set().SingleAsync(row => row.Id == ticket.Id); + storedTicket.ConsumedAt.Should().Be(now.AddSeconds(6)); + storedTicket.Matches(new string('c', 64), new string('d', 64)).Should().BeTrue("the digests round-trip through bytea"); + (await db.Set().CountAsync(row => row.Status == DataRequestStatus.Completed && row.Kind == DataRequestKind.Export)) + .Should().BeGreaterThanOrEqualTo(2, "the closed-code converter translates into the stored spelling"); + + storedArtifact.Revoke(now.AddSeconds(7), subject).IsSuccess.Should().BeTrue(); + await db.SaveChangesAsync(); + await ExecuteAsync(connection, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", artifact.Id.Value)); + await ExecuteAsync(connection, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await frame.FailAsync(); + } + + /// A fresh tenant-wide export of AdminA, fulfilling, with an artifact of the given size and no chunks yet. + private static async Task AdminExportArtifactAsync(NpgsqlConnection app, NpgsqlTransaction transaction, long bytes) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, AdminA); + var request = Guid.CreateVersion7(); + var artifact = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, request, SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + await StepAsync(app, transaction, request, "status='fulfilling'"); + await InsertArtifactAsync(app, transaction, artifact, SchemaFixture.TenantA, null, request, AdminA, bytes); + return artifact; + } + + private static Task RevokeAsync(NpgsqlConnection app, NpgsqlTransaction transaction, Guid artifact) => + ExecuteAsync(app, transaction, """ + UPDATE public.data_export_artifacts SET status='revoked',purged_at=now(),row_version=row_version+1, + updated_at=now(),updated_by=@subject WHERE id=@id + """, ("id", artifact), ("subject", AdminA)); + + /// Runs a statement expected to fail inside a savepoint, so the transaction continues. + private static async Task RefuseAsync(NpgsqlTransaction transaction, Func act) + { + await transaction.SaveAsync("probe"); + var refusal = (await act.Should().ThrowAsync()).Which; + await transaction.RollbackAsync("probe"); + return refusal; + } + + private static Task CountAsync(NpgsqlConnection app, NpgsqlTransaction transaction, string table, string predicate = "true") => + ScalarAsync(app, transaction, $"SELECT count(*) FROM public.{table} WHERE {predicate}"); + + private static async Task ExecuteCountAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, + params (string Name, object Value)[] values) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + foreach (var (name, value) in values) command.Parameters.AddWithValue(name, value); + return await command.ExecuteNonQueryAsync(); + } + + private async Task OpenAppAsync() + { + var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(schema.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + return app; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.DataRequestRelations.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.DataRequestRelations.cs new file mode 100644 index 00000000..39dc71ba --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.DataRequestRelations.cs @@ -0,0 +1,61 @@ +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class EducationStructureTests +{ + // ADR-0107 § 4's ciphertext chunks are SQL-only, so the relation has no EF counterpart; the applied foreign key + // and the canonical parent-scope function are still checked exactly. + private static readonly ParentRelation DataExportChunkRelation = + new("data_export_chunks", "data_export_artifacts", "artifact_id", "r"); + + private static bool IsDeclaredDataExportChunkRelation(ForeignKey key) => + key.Child == DataExportChunkRelation.Child && key.Parent == DataExportChunkRelation.Parent; + + private static List DataExportChunkGuardOffenders(List applied, List triggers) + { + var offenders = new List(); + var relation = DataExportChunkRelation; + var keys = applied.Where(IsDeclaredDataExportChunkRelation).ToArray(); + if (keys.Length != 1) + offenders.Add($"{relation.Child}: missing parent FK"); + else if (!ValidForeignKey(keys[0], relation) || keys[0].DeleteAction != relation.DeleteAction) + offenders.Add($"{relation.Child}: tenant-composite FK"); + if (!triggers.Any(trigger => trigger[0] == relation.Child && trigger[1] == "public" && trigger[3] == "true" + && trigger[5] == "23" && trigger[6] == "false" && trigger[7] == "false" && IsParentGuardBody(trigger[2], relation))) + offenders.Add($"{relation.Child}: parent guard"); + return offenders; + } + + [Theory] + [InlineData("data_export_artifacts")] + [InlineData("data_export_tickets")] + [InlineData("data_export_chunks")] + public async Task The_data_request_parent_guard_rejects_a_missing_weakened_or_inert_relation(string table) + { + await using var owner = await PostgresFixture.OpenAsync(_schema.Postgres.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + + var key = (await ReadForeignKeysAsync(owner, transaction)).Single(item => item.Child == table); + await SchemaQueries.ExecuteAsync(owner, transaction, $"SAVEPOINT relation; ALTER TABLE public.{table} DROP CONSTRAINT {key.Name}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().ContainSingle().Which.Should().Be($"{table}: missing parent FK"); + await SchemaQueries.ExecuteAsync(owner, transaction, + $"ROLLBACK TO SAVEPOINT relation; ALTER TABLE public.{table} DROP CONSTRAINT {key.Name}; " + + $"ALTER TABLE public.{table} ADD CONSTRAINT {key.Name} " + + key.Definition.Replace("ON DELETE RESTRICT", "ON DELETE CASCADE", StringComparison.Ordinal)); + (await ParentGuardOffendersAsync(owner, transaction)).Should().ContainSingle().Which.Should().Be($"{table}: tenant-composite FK"); + await SchemaQueries.ExecuteAsync(owner, transaction, "ROLLBACK TO SAVEPOINT relation"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + + await SchemaQueries.ExecuteAsync(owner, transaction, $"DROP TRIGGER tg_{table}_parent_scope ON public.{table}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().ContainSingle().Which.Should().Be($"{table}: parent guard"); + await SchemaQueries.ExecuteAsync(owner, transaction, "ROLLBACK TO SAVEPOINT relation"); + await SchemaQueries.ExecuteAsync(owner, transaction, + $"CREATE OR REPLACE FUNCTION public.fn_{table}_parent_scope() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER " + + "SET search_path = pg_catalog AS $probe$ BEGIN RETURN NEW; END; $probe$"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().ContainSingle().Which.Should().Be($"{table}: parent guard", + "an early-returning function is not the canonical parent check"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs index 348cc842..46946710 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs @@ -37,8 +37,16 @@ private sealed record ParentRelation(string Child, string Parent, string ParentI new("invitations", "memberships", "result_membership_id", "r"), ]; + // ADR-0107 § 4: an artifact and a ticket mirror their parent's group through Standards 05's canonical + // parent-scope function; the SQL-only chunk relation is declared in EducationStructureTests.DataRequestRelations. + private static readonly ParentRelation[] DataRequestParentRelations = + [ + new("data_export_artifacts", "data_subject_requests", "request_id", "r"), + new("data_export_tickets", "data_export_artifacts", "artifact_id", "r"), + ]; + private static readonly ParentRelation[] ParentRelations = - [.. EducationParentRelations, .. IdentityParentRelations, .. InvitationParentRelations]; + [.. EducationParentRelations, .. IdentityParentRelations, .. InvitationParentRelations, .. DataRequestParentRelations]; private sealed record PatternRoot(Type Root, Type Satellite, string Table, string SatelliteTable, string ParentId, string[] Columns); @@ -84,7 +92,8 @@ private static async Task> ParentGuardOffendersAsync( } else if (!Columns(key.Properties).SequenceEqual(["tenant_id", declaration.ParentId]) || !Columns(key.PrincipalKey.Properties).SequenceEqual(["tenant_id", "id"]) - || ((IdentityParentRelations.Contains(declaration) || InvitationParentRelations.Contains(declaration)) + || ((IdentityParentRelations.Contains(declaration) || InvitationParentRelations.Contains(declaration) + || DataRequestParentRelations.Contains(declaration)) && key.DeleteBehavior != DeleteBehavior.Restrict)) { offenders.Add($"{child}: model tenant-composite FK"); @@ -93,7 +102,7 @@ private static async Task> ParentGuardOffendersAsync( var applied = await ReadForeignKeysAsync(connection, transaction); foreach (var key in applied.Where(key => !declarations.Any(item => item.Child == key.Child && item.Parent == key.Parent) - && !IsDeclaredJobRelation(key) && !IsDeclaredInvitationProviderRelation(key))) + && !IsDeclaredJobRelation(key) && !IsDeclaredInvitationProviderRelation(key) && !IsDeclaredDataExportChunkRelation(key))) { offenders.Add($"{key.Child}: undeclared applied relation"); } @@ -128,7 +137,8 @@ WHERE c.oid IN ({SchemaQueries.TableOids}) AND NOT t.tgisinternal offenders.Add($"{relation.Child}: missing parent FK"); } else if (!ValidForeignKey(keys[0], relation) - || ((IdentityParentRelations.Contains(relation) || InvitationParentRelations.Contains(relation)) + || ((IdentityParentRelations.Contains(relation) || InvitationParentRelations.Contains(relation) + || DataRequestParentRelations.Contains(relation)) && keys[0].DeleteAction != relation.DeleteAction)) { offenders.Add($"{relation.Child}: tenant-composite FK"); @@ -155,6 +165,7 @@ WHERE c.oid IN ({SchemaQueries.TableOids}) AND NOT t.tgisinternal offenders.AddRange(await JobParentGuardOffendersAsync(applied, triggers)); offenders.AddRange(await InvitationProviderGuardOffendersAsync(connection, transaction, applied, triggers)); + offenders.AddRange(DataExportChunkGuardOffenders(applied, triggers)); return offenders.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs index 67bf43d6..0becd9fb 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs @@ -33,7 +33,9 @@ ORDER BY 1 } await MigrationChains.ApplyAllAsync(database.MigrationConnectionString); (await ParentGuardOffendersAsync(owner)).Should().BeEmpty(); - (await ReadForeignKeysAsync(owner, null)).Should().BeEquivalentTo(beforeRelations); + // The P03-10 data-request tables arrive after the invitation predecessors; only their own relations are new. + (await ReadForeignKeysAsync(owner, null)).Where(key => !SchemaTableClasses.IdentityDataRequest.Contains(key.Child)) + .Should().BeEquivalentTo(beforeRelations); (await SchemaQueries.ReadStringsAsync(owner, aclSql)).Should().Equal(beforeAcl); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index c32ca8b0..5eaaea3c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -407,12 +407,14 @@ 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(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.Should().HaveCount(38, "the closed set includes three provider definers, one target transition guard, the federation connection guard, the operator resolver, the identity authority key guard, " + + "and the four data-request guards, their chunk completeness check and three canonical parent-scope checks"); 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(30); + functions.SelectMany(function => function.Triggers).Should().HaveCount(39, + "the data-request functions add four mutation guards, two deferred completeness triggers and three parent-scope triggers"); 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/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs index 8791bc8b..fa9b1d23 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -55,11 +55,11 @@ SELECT set_config('app.identity_authority_id','not-a-uuid',true), } [Fact] - public async Task Applied_census_has_sixty_six_tables_and_exactly_sixteen_confined_definers() + public async Task Applied_census_has_seventy_tables_and_exactly_sixteen_confined_definers() { await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); await SchemaTableClasses.AssertCompleteAsync(owner); - (await SchemaTableClasses.ReadAsync(owner)).Should().HaveCount(66); + (await SchemaTableClasses.ReadAsync(owner)).Should().HaveCount(70, "sixty-six before P03-10 and its four data-request tables"); var names = await SchemaQueries.ReadStringsAsync(owner, """ SELECT p.proname FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public' AND p.prosecdef ORDER BY p.proname @@ -163,7 +163,9 @@ public async Task Non_success_evidence_needs_no_User_and_cannot_satisfy_success( [Theory] [InlineData("DELETE FROM public.users")] - [InlineData("TRUNCATE public.users, public.memberships, public.membership_profiles, public.membership_role_assignments, public.invitations")] + // The data-request tables reference users, so a TRUNCATE that reaches the users guard names them too. + [InlineData("TRUNCATE public.users, public.memberships, public.membership_profiles, public.membership_role_assignments, public.invitations, " + + "public.data_subject_requests, public.data_export_artifacts, public.data_export_tickets, public.data_export_chunks")] [InlineData("UPDATE public.users SET status='Closing'")] public async Task Owner_execution_cannot_remove_or_mutate_the_permanent_binding(string sql) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs index 0cde89fc..60fcd03d 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs @@ -79,6 +79,7 @@ INSERT INTO public.role_permission_grants(tenant_id,role_id,permission_scope,per await CommitMemberAsync(app, SchemaFixture.TenantB, SchemaFixture.OrgB1, BranchMembershipB, PersonB, BuiltInRoleKey.Learner); await InvitationSchemaSeed.SeedAsync(appConnection); await FederationConnectionSchemaSeed.SeedAsync(appConnection); + await DataRequestSchemaSeed.SeedAsync(appConnection); } private static async Task CommitMemberAsync(NpgsqlConnection connection, Guid tenant, Guid? organization, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs index 6169b205..224e68d9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs @@ -19,6 +19,10 @@ public sealed partial class IdentityMembershipTests ["role_permission_grants"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), ["invitations"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), ["federation_connections"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["data_subject_requests"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["data_export_artifacts"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["data_export_tickets"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["data_export_chunks"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), }; [Theory] @@ -29,6 +33,10 @@ public sealed partial class IdentityMembershipTests [InlineData("role_permission_grants")] [InlineData("invitations")] [InlineData("federation_connections")] + [InlineData("data_subject_requests")] + [InlineData("data_export_artifacts")] + [InlineData("data_export_tickets")] + [InlineData("data_export_chunks")] public async Task Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them(string table) { await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); @@ -49,6 +57,7 @@ SELECT string_agg(tgname || ':' || tgenabled::text, ',' ORDER BY tgname) { "memberships" or "membership_role_assignments" => [$"tg_{table}_mutation_guard", $"tg_{table}_admission"], "role_permission_grants" => [$"tg_{table}_mutation_guard", "tg_role_permission_grants_root_lock"], + "data_export_artifacts" or "data_export_tickets" or "data_export_chunks" => [$"tg_{table}_mutation_guard", $"tg_{table}_parent_scope"], _ => [$"tg_{table}_mutation_guard"], }; foreach (var guard in guards) @@ -73,13 +82,18 @@ SELECT string_agg(tgname || ':' || tgenabled::text, ',' ORDER BY tgname) "roles" => "UPDATE public.roles SET row_version=row_version+1 WHERE id=@role", "invitations" => "UPDATE public.invitations SET row_version=row_version+1 WHERE id=@invitation", "federation_connections" => "UPDATE public.federation_connections SET row_version=row_version+1 WHERE id=@federation", + "data_subject_requests" => "UPDATE public.data_subject_requests SET row_version=row_version+1 WHERE id=@request", + "data_export_artifacts" => "UPDATE public.data_export_artifacts SET row_version=row_version+1 WHERE id=@artifact", + "data_export_tickets" => "UPDATE public.data_export_tickets SET consumed_at=created_at WHERE id=@ticket", + "data_export_chunks" => "INSERT INTO public.data_export_chunks(tenant_id,artifact_id,chunk_index,nonce,ciphertext,tag) VALUES(@tenant,@artifact,1,'\\x000000000000000000000000'::bytea,'\\x00'::bytea,'\\x00000000000000000000000000000000'::bytea)", "membership_role_assignments" => "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id) VALUES(@tenant,@member,@role)", _ => "INSERT INTO public.role_permission_grants(tenant_id,role_id,permission_scope,permission_key) VALUES(@tenant,@role,'Tenant',@key)", }; (string Name, object? Value)[] values = [("member", AdminMembershipB), ("tenant", SchemaFixture.TenantB), ("role", RoleId(SchemaFixture.TenantB, BuiltInRoleKey.Instructor, PermissionScope.Tenant)), ("key", IdentityFoundationManifest.ProfileWrite), ("invitation", InvitationSchemaSeed.TenantOfferB), - ("federation", FederationConnectionSchemaSeed.LiveB)]; + ("federation", FederationConnectionSchemaSeed.LiveB), ("request", DataRequestSchemaSeed.TenantWideB.Request), + ("artifact", DataRequestSchemaSeed.TenantWideB.Artifact!.Value), ("ticket", DataRequestSchemaSeed.TenantWideB.Ticket!.Value)]; await using (var clean = await app.BeginTransactionAsync()) { await ScopeAsync(app, clean, SchemaFixture.TenantA); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 891cf7d2..1437192b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -95,7 +95,8 @@ public async Task Reversible_chain_prefixes_reverse_to_empty_and_current_heads_r // Reinstall the complete current chains, including forward-only retained-evidence heads. await MigrationChains.ApplyAllAsync(_fixture.Postgres.MigrationConnectionString); - (await CountAsync(connection, TablesQuery)).Should().Be(66L); + (await CountAsync(connection, TablesQuery)).Should().Be(70L, + "the current chains add the four P03-10 data-request tables to the sixty-six before them"); (await CountAsync(connection, "SELECT count(*) FROM pg_class WHERE relnamespace='public'::regnamespace AND relkind='r' AND relname IN ('tenant_custom_field_defs','membership_field_consents')")) .Should().Be(2, "both current custom-field tables were restored"); await SchemaTableClasses.AssertCompleteAsync(connection); @@ -103,8 +104,9 @@ 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(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 CountAsync(connection, IdentityFunctionQuery)).Should().Be(30L, + "current Identity also installs three provider definers, one target transition guard, the federation connection guard, the operator subject resolver, the authority key guard, " + + "and the four data-request guards with their chunk completeness check"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); @@ -219,6 +221,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() 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 federationProjection = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.grant_platform_federation_projection().DownOperations; + federationProjection.Should().Throw().WithMessage("The platform federation projection grant 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)[] @@ -227,8 +231,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, "20261120090000_add_identity_authority_rebind", IdentityReversibleHead, - "20261120160000_grant_platform_federation_projection", "The platform federation projection grant requires a reviewed forward migration."), + (identity, "20261120160000_grant_platform_federation_projection", IdentityReversibleHead, + "20261122013001_add_data_subject_requests", "Data request 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/OrgScopeSchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OrgScopeSchemaTests.cs index f2505995..1e77b85b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OrgScopeSchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OrgScopeSchemaTests.cs @@ -116,7 +116,8 @@ public async Task Every_OrgScoped_Table_Has_An_Organization_Immutability_Guard() scoped.Should().Contain(["tenant_settings", "audit_log", "courses", "lessons", "course_translations", "lesson_translations", "background_jobs", "background_job_attempts", "background_job_recipients", - "invitations", "membership_field_consents", "invitation_email_envelopes", "invitation_email_attempt_receipts"], + "invitations", "membership_field_consents", "invitation_email_envelopes", "invitation_email_attempt_receipts", + "data_subject_requests", "data_export_artifacts", "data_export_tickets", "data_export_chunks"], "a guard over no classified tables proves nothing"); all.Except(scoped).Should().BeEquivalentTo(["platform_host_to_tenant", "outbox_messages"], "these are the two documented table-class exceptions, not an extensible exclusion list"); @@ -191,6 +192,10 @@ CREATE TRIGGER tg_scope_guard_probe BEFORE UPDATE ON scope_guard_probe [InlineData("membership_field_consents", "tg_membership_field_consents_organization_id_immutable")] [InlineData("invitation_email_envelopes", "tg_invitation_email_envelopes_guard")] [InlineData("invitation_email_attempt_receipts", "tg_invitation_email_attempt_receipts_guard")] + [InlineData("data_subject_requests", "tg_data_subject_requests_organization_id_immutable")] + [InlineData("data_export_artifacts", "tg_data_export_artifacts_organization_id_immutable")] + [InlineData("data_export_tickets", "tg_data_export_tickets_organization_id_immutable")] + [InlineData("data_export_chunks", "tg_data_export_chunks_organization_id_immutable")] public async Task The_Organization_Guard_Rejects_A_Missing_Guard_On_Each_Existing_Table( string table, string trigger) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs index 75040c14..734d7b4f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs @@ -169,6 +169,13 @@ static SchemaFixture() RowsVisibleToTenantA[table] = SchemaTableClasses.SelectDenied; RowsVisibleToTenantB[table] = SchemaTableClasses.SelectDenied; } + // DataRequestSchemaSeed: each tenant's tenant-wide completed export, its artifact, ticket and chunk. + // Tenant A's two organization exports and tenant B's organization request need app.organization_id. + foreach (var table in SchemaTableClasses.IdentityDataRequest) + { + RowsVisibleToTenantA[table] = 1; + RowsVisibleToTenantB[table] = 1; + } foreach (var table in SchemaTableClasses.JobTenant) { RowsVisibleToTenantA[table] = table == "background_job_reservations" ? 3 : 1; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs index f1674ff6..f77574a4 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs @@ -38,8 +38,11 @@ internal static class SchemaTableClasses "federation_connections"]; public static readonly string[] InvitationProvider = ["invitation_email_envelopes", "invitation_email_attempt_receipts"]; public static readonly string[] ProviderIngress = ["identity_provider_event_receipts", "identity_provider_event_scan", "identity_provider_event_problems"]; + // ADR-0106/0107: the organization-scoped request, artifact and ticket receipts and the SQL-only ciphertext chunks. + public static readonly string[] IdentityDataRequest = ["data_subject_requests", "data_export_artifacts", "data_export_tickets", + "data_export_chunks"]; public static readonly string[] Data = [.. Existing, .. JobTenant, .. Control, .. Vendor, - .. GlobalIdentity, .. IdentityPlatform, .. IdentityContextual, .. InvitationProvider, .. ProviderIngress]; + .. GlobalIdentity, .. IdentityPlatform, .. IdentityContextual, .. InvitationProvider, .. ProviderIngress, .. IdentityDataRequest]; public static bool AppSelectDenied(string table) => Control.Contains(table) || Vendor.Contains(table) || table == "identity_creation_capacity" || InvitationProvider.Contains(table) || ProviderIngress.Contains(table); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs index e2e5f41e..11a8c7a4 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs @@ -1359,7 +1359,14 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi "learnstack_identity_ingress identity_provider_event_scan INSERT,SELECT", "learnstack_identity_ingress identity_provider_event_problems INSERT,SELECT", "learnstack_identity_rebind identity_authority SELECT", - "learnstack_identity_rebind audit_log INSERT"]), + "learnstack_identity_rebind audit_log INSERT", + // ADR-0107 § 8. The application role's column-limited UPDATEs and the platform role's closed-column + // SELECT and UPDATE on data_subject_requests are column grants, invisible here; DataRequestStorageTests + // asserts the complete column matrix, and learnstack_platform has no table-level line at all. + "learnstack_app data_subject_requests INSERT,SELECT", + "learnstack_app data_export_artifacts INSERT,SELECT", + "learnstack_app data_export_tickets INSERT,SELECT", + "learnstack_app data_export_chunks DELETE,INSERT,SELECT"]), "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/DataExportArtifactDomainTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportArtifactDomainTests.cs new file mode 100644 index 00000000..68d06d8f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportArtifactDomainTests.cs @@ -0,0 +1,143 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// ADR-0107 § 4's artifact lifecycle and session-bound download tickets. +public sealed class DataExportArtifactDomainTests +{ + private static readonly DateTimeOffset At = new(2026, 11, 22, 9, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly UserId Subject = UserId.From(Guid.CreateVersion7()); + private static readonly UserId Other = UserId.From(Guid.CreateVersion7()); + private static readonly string TicketDigest = new('a', 64); + private static readonly string SessionDigest = new('b', 64); + + [Theory] + [InlineData(1L, 1)] + [InlineData(131072L, 1)] + [InlineData(131073L, 2)] + [InlineData(16L * 1024 * 1024, 128)] + [InlineData(64L * 1024 * 1024, 512)] + public void An_artifact_of_a_fulfilling_export_mirrors_its_request_and_counts_its_chunks(long bytes, int chunks) + { + var request = FulfillingExport(out var at); + var artifact = DataExportArtifact.Create(NewArtifactId(), request, bytes, "v1", at, UserId.SystemActor).Value!; + + artifact.Status.Should().Be(DataExportArtifactStatus.Available); + artifact.ChunkCount.Should().Be(chunks); + artifact.TenantId.Should().Be(request.TenantId); + artifact.OrganizationId.Should().Be(request.OrganizationId); + artifact.SubjectUserId.Should().Be(Subject); + artifact.RequestId.Should().Be(request.Id); + artifact.ExpiresAt.Should().Be(at + TimeSpan.FromDays(7), "ADR-0107 § 4: readable for seven days"); + artifact.IsReadable(at).Should().BeTrue(); + artifact.IsReadable(artifact.ExpiresAt).Should().BeFalse("expiry is a time check, whether or not the purge ran"); + } + + [Fact] + public void An_artifact_belongs_only_to_a_fulfilling_export_and_a_bounded_bundle() + { + var requested = DataSubjectRequest.FileForSelf(NewRequestId(), DataRequestKind.Export, Subject, Group(), [NewMembership()], At).Value!; + DataExportArtifact.Create(NewArtifactId(), requested, 10, "v1", At.AddMinutes(1), UserId.SystemActor).IsFailure.Should().BeTrue(); + var erasure = DataSubjectRequest.FileForSelf(NewRequestId(), DataRequestKind.Erasure, Subject, Group(), [NewMembership()], At).Value!; + erasure.StartFulfilling(erasure.ExecuteAt!.Value, UserId.SystemActor).IsSuccess.Should().BeTrue(); + DataExportArtifact.Create(NewArtifactId(), erasure, 10, "v1", erasure.ExecuteAt!.Value, UserId.SystemActor).IsFailure.Should().BeTrue(); + + var export = FulfillingExport(out var at); + DataExportArtifact.Create(NewArtifactId(), export, 0, "v1", at, UserId.SystemActor).IsFailure.Should().BeTrue(); + DataExportArtifact.Create(NewArtifactId(), export, DataRequestLimits.MaximumBundleBytes + 1, "v1", at, UserId.SystemActor) + .IsFailure.Should().BeTrue("ADR-0107 § 4: 64 MiB at most"); + DataExportArtifact.Create(NewArtifactId(), export, 10, "key/1", at, UserId.SystemActor).IsFailure.Should().BeTrue(); + DataExportArtifact.Create(NewArtifactId(), export, 10, new string('k', 33), at, UserId.SystemActor).IsFailure.Should().BeTrue(); + } + + [Fact] + public void Revocation_purges_an_unexpired_artifact_at_once_and_is_final() + { + var artifact = Artifact(out var at); + artifact.Revoke(at.AddHours(1), Subject).IsSuccess.Should().BeTrue(); + artifact.Status.Should().Be(DataExportArtifactStatus.Revoked); + artifact.PurgedAt.Should().Be(at.AddHours(1)); + artifact.Version.Should().Be(1); + artifact.Revoke(at.AddHours(2), Subject).IsFailure.Should().BeTrue(); + artifact.Purge(artifact.ExpiresAt, UserId.SystemActor).IsFailure.Should().BeTrue("a revoked artifact holds nothing to purge"); + + var expired = Artifact(out at); + expired.Revoke(expired.ExpiresAt, Subject).IsFailure.Should().BeTrue("only an unexpired artifact is revoked"); + } + + [Fact] + public void Expiry_and_purge_follow_the_expiry_instant() + { + var artifact = Artifact(out var at); + artifact.Expire(artifact.ExpiresAt.AddTicks(-1), UserId.SystemActor).IsFailure.Should().BeTrue(); + artifact.Purge(artifact.ExpiresAt.AddTicks(-1), UserId.SystemActor).IsFailure.Should().BeTrue(); + artifact.Expire(artifact.ExpiresAt, UserId.SystemActor).IsSuccess.Should().BeTrue(); + artifact.PurgedAt.Should().BeNull("an expired artifact may still hold chunks until the purge"); + artifact.Purge(artifact.ExpiresAt.AddMinutes(5), UserId.SystemActor).IsSuccess.Should().BeTrue(); + artifact.Status.Should().Be(DataExportArtifactStatus.Purged); + artifact.PurgedAt.Should().Be(artifact.ExpiresAt.AddMinutes(5)); + artifact.Expire(artifact.ExpiresAt.AddDays(1), UserId.SystemActor).IsFailure.Should().BeTrue(); + + var direct = Artifact(out at); + direct.Purge(direct.ExpiresAt, UserId.SystemActor).IsSuccess.Should().BeTrue("the purge job may find it still available"); + } + + [Fact] + public void Only_the_subject_mints_a_ticket_for_a_readable_artifact_and_it_lasts_fifteen_minutes() + { + var artifact = Artifact(out var at); + DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, SessionDigest, at, Other).IsFailure.Should().BeTrue( + "ADR-0106 § 6: the recipient of an export is always the subject"); + DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, SessionDigest, at, UserId.SystemActor).IsFailure.Should().BeTrue(); + DataExportTicket.Mint(NewTicketId(), artifact, "A".PadLeft(64, 'A'), SessionDigest, at, Subject).IsFailure.Should().BeTrue(); + DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, "short", at, Subject).IsFailure.Should().BeTrue(); + + var ticket = DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, SessionDigest, at, Subject).Value!; + ticket.ExpiresAt.Should().Be(at + TimeSpan.FromMinutes(15)); + ticket.CreatedBy.Should().Be(Subject); + ticket.ArtifactId.Should().Be(artifact.Id); + ticket.OrganizationId.Should().Be(artifact.OrganizationId); + ticket.Matches(TicketDigest, SessionDigest).Should().BeTrue(); + ticket.Matches(TicketDigest, TicketDigest).Should().BeFalse("the ticket is bound to the session that minted it"); + ticket.Matches(SessionDigest, SessionDigest).Should().BeFalse(); + + artifact.Revoke(at.AddMinutes(1), Subject).IsSuccess.Should().BeTrue(); + DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, SessionDigest, at.AddMinutes(2), Subject).IsFailure.Should().BeTrue( + "a revoked artifact is not readable"); + } + + [Fact] + public void A_ticket_is_consumed_once_inside_its_lifetime() + { + var artifact = Artifact(out var at); + var ticket = DataExportTicket.Mint(NewTicketId(), artifact, TicketDigest, SessionDigest, at, Subject).Value!; + ticket.Consume(ticket.ExpiresAt).IsFailure.Should().BeTrue(); + ticket.Consume(at.AddMinutes(14)).IsSuccess.Should().BeTrue(); + ticket.ConsumedAt.Should().Be(at.AddMinutes(14)); + ticket.IsUsable(at.AddMinutes(14)).Should().BeFalse("a consumed ticket authorizes no further read"); + ticket.Consume(at.AddMinutes(14)).IsFailure.Should().BeTrue("a resumed download mints a new ticket"); + } + + private static DataSubjectRequest FulfillingExport(out DateTimeOffset at) + { + var request = DataSubjectRequest.FileForSelf(NewRequestId(), DataRequestKind.Export, Subject, Group(), [NewMembership()], At).Value!; + at = At.AddMinutes(1); + request.StartFulfilling(at, UserId.SystemActor).IsSuccess.Should().BeTrue(); + at = at.AddMinutes(1); + return request; + } + + private static DataExportArtifact Artifact(out DateTimeOffset at) => + DataExportArtifact.Create(NewArtifactId(), FulfillingExport(out at), 4096, "v1", at, UserId.SystemActor).Value!; + + private static DataRequestScopeGroup Group() => new(Tenant, null); + private static MembershipId NewMembership() => MembershipId.From(Guid.CreateVersion7()); + private static DataSubjectRequestId NewRequestId() => DataSubjectRequestId.From(Guid.CreateVersion7()); + private static DataExportArtifactId NewArtifactId() => DataExportArtifactId.From(Guid.CreateVersion7()); + private static DataExportTicketId NewTicketId() => DataExportTicketId.From(Guid.CreateVersion7()); +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataSubjectRequestDomainTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataSubjectRequestDomainTests.cs new file mode 100644 index 00000000..37ed98ab --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataSubjectRequestDomainTests.cs @@ -0,0 +1,411 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// ADR-0106 § 8's status machine, the immutable snapshot and the closed documents of a request. +public sealed class DataSubjectRequestDomainTests +{ + private static readonly DateTimeOffset At = new(2026, 11, 22, 9, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly OrganizationId Organization = OrganizationId.From(Guid.CreateVersion7()); + private static readonly UserId Subject = UserId.From(Guid.CreateVersion7()); + private static readonly UserId Administrator = UserId.From(Guid.CreateVersion7()); + private static readonly MembershipId Current = MembershipId.From(Guid.CreateVersion7()); + private static readonly MembershipId Tombstone = MembershipId.From(Guid.CreateVersion7()); + + public enum Action { StartFulfilling, AwaitPrivilegedStep, Complete, Fail, Block, Cancel } + + /// ADR-0106 § 8, row by row: the only arrows each kind has. + private static readonly Dictionary<(DataRequestKind, DataRequestStatus, Action), DataRequestStatus> Arrows = new() + { + [(DataRequestKind.Export, DataRequestStatus.Requested, Action.StartFulfilling)] = DataRequestStatus.Fulfilling, + [(DataRequestKind.Export, DataRequestStatus.Requested, Action.Cancel)] = DataRequestStatus.Cancelled, + [(DataRequestKind.Export, DataRequestStatus.Fulfilling, Action.Complete)] = DataRequestStatus.Completed, + [(DataRequestKind.Export, DataRequestStatus.Fulfilling, Action.Fail)] = DataRequestStatus.Failed, + [(DataRequestKind.Erasure, DataRequestStatus.Scheduled, Action.StartFulfilling)] = DataRequestStatus.Fulfilling, + [(DataRequestKind.Erasure, DataRequestStatus.Scheduled, Action.Cancel)] = DataRequestStatus.Cancelled, + [(DataRequestKind.Erasure, DataRequestStatus.Fulfilling, Action.AwaitPrivilegedStep)] = DataRequestStatus.AwaitingPrivilegedStep, + [(DataRequestKind.Erasure, DataRequestStatus.Fulfilling, Action.Block)] = DataRequestStatus.Blocked, + [(DataRequestKind.Erasure, DataRequestStatus.Fulfilling, Action.Fail)] = DataRequestStatus.Failed, + [(DataRequestKind.Erasure, DataRequestStatus.AwaitingPrivilegedStep, Action.Complete)] = DataRequestStatus.Completed, + [(DataRequestKind.Closure, DataRequestStatus.Scheduled, Action.StartFulfilling)] = DataRequestStatus.Fulfilling, + [(DataRequestKind.Closure, DataRequestStatus.Scheduled, Action.Cancel)] = DataRequestStatus.Cancelled, + [(DataRequestKind.Closure, DataRequestStatus.Fulfilling, Action.Complete)] = DataRequestStatus.Completed, + }; + + private static readonly Dictionary Reachable = new() + { + [DataRequestKind.Export] = [DataRequestStatus.Requested, DataRequestStatus.Fulfilling, DataRequestStatus.Completed, + DataRequestStatus.Failed, DataRequestStatus.Cancelled], + [DataRequestKind.Erasure] = [DataRequestStatus.Scheduled, DataRequestStatus.Fulfilling, DataRequestStatus.AwaitingPrivilegedStep, + DataRequestStatus.Completed, DataRequestStatus.Blocked, DataRequestStatus.Failed, DataRequestStatus.Cancelled], + [DataRequestKind.Closure] = [DataRequestStatus.Scheduled, DataRequestStatus.Fulfilling, DataRequestStatus.Completed, + DataRequestStatus.Cancelled], + }; + + public static TheoryData EveryReachableStatusAndAction() + { + var data = new TheoryData(); + foreach (var (kind, statuses) in Reachable) + foreach (var status in statuses) + foreach (var action in Enum.GetValues()) + data.Add(kind, status, action); + return data; + } + + [Theory] + [MemberData(nameof(EveryReachableStatusAndAction))] + public void Every_action_from_every_reachable_status_takes_exactly_the_ADR_arrow( + DataRequestKind kind, DataRequestStatus from, Action action) + { + var request = Reach(kind, from); + var version = request.Version; + var expected = Arrows.TryGetValue((kind, from, action), out var to) ? to : (DataRequestStatus?)null; + + var result = Apply(request, action, ActionTime(request, action)); + + result.IsSuccess.Should().Be(expected is not null, $"{kind} {from} --{action}--> is {(expected is null ? "not " : "")}an arrow"); + if (expected is { } next) + { + request.Status.Should().Be(next); + request.Version.Should().Be(version + 1, "every transition is a versioned mutation"); + } + else + { + request.Status.Should().Be(from, "a refused transition changes nothing"); + request.Version.Should().Be(version); + result.Error!.Code.Should().Be("business_rule_violation", "an expected refusal is a Result, never an exception"); + } + } + + [Fact] + public void The_arrow_table_covers_ADR_0106_section_8_and_nothing_else() + { + Arrows.Should().HaveCount(13); + Arrows.Keys.Select(key => key.Item1).Distinct().Should().BeEquivalentTo(Enum.GetValues()); + Arrows.Values.Should().NotContain(DataRequestStatus.Requested).And.NotContain(DataRequestStatus.Scheduled, + "no arrow re-enters an initial status"); + Arrows.Keys.Where(key => DataRequestCodes.IsTerminal(key.Item2)).Should().BeEmpty("every terminal status is final"); + } + + [Theory] + [InlineData(DataRequestKind.Export, DataRequestStatus.Requested, false)] + [InlineData(DataRequestKind.Erasure, DataRequestStatus.Scheduled, true)] + [InlineData(DataRequestKind.Closure, DataRequestStatus.Scheduled, true)] + public void A_person_files_each_kind_for_themselves_in_its_initial_status(DataRequestKind kind, DataRequestStatus initial, bool windowed) + { + var request = DataSubjectRequest.FileForSelf(NewId(), kind, Subject, Group(), [Current, Tombstone], At).Value!; + + request.Status.Should().Be(initial); + request.Origin.Should().Be(DataRequestOrigin.Self); + request.RequesterUserId.Should().Be(Subject); + request.CreatedBy.Should().Be(Subject); + request.ExecuteAt.Should().Be(windowed ? At + TimeSpan.FromHours(24) : null, "ADR-0106 § 11's 24-hour window"); + request.TenantId.Should().Be(Tenant); + request.OrganizationId.Should().Be(Organization); + request.SnapshotMembershipIds.Should().BeEquivalentTo([Current, Tombstone]); + request.Progress.Should().BeEmpty(); + request.RetainedReport.Should().BeEmpty(); + request.Version.Should().Be(0); + } + + [Fact] + public void An_administrator_files_an_export_or_an_erasure_for_another_person_but_never_a_closure() + { + foreach (var kind in new[] { DataRequestKind.Export, DataRequestKind.Erasure }) + { + var request = DataSubjectRequest.FileForSubject(NewId(), kind, Administrator, Subject, Group(), [Current], At).Value!; + request.Origin.Should().Be(DataRequestOrigin.Administrator); + request.RequesterUserId.Should().Be(Administrator); + request.CreatedBy.Should().Be(Administrator, "the audit actor of an administrator request is the administrator"); + request.SubjectUserId.Should().Be(Subject); + } + + DataSubjectRequest.FileForSubject(NewId(), DataRequestKind.Closure, Administrator, Subject, Group(), [Current], At) + .IsFailure.Should().BeTrue("ADR-0106 § 3: an administrator never creates a closure"); + DataSubjectRequest.FileForSubject(NewId(), DataRequestKind.Export, Subject, Subject, Group(), [Current], At) + .IsFailure.Should().BeTrue("a request for oneself is the self origin"); + } + + [Fact] + public void A_closure_fan_out_erasure_starts_fulfilling_with_no_window_and_cannot_be_cancelled() + { + var request = DataSubjectRequest.FanOutErasure(NewId(), Subject, Group(), [Current], At).Value!; + + request.Kind.Should().Be(DataRequestKind.Erasure); + request.Origin.Should().Be(DataRequestOrigin.ClosureFanout); + request.Status.Should().Be(DataRequestStatus.Fulfilling); + request.ExecuteAt.Should().BeNull(); + request.RequesterUserId.Should().BeNull(); + request.CreatedBy.Should().Be(UserId.SystemActor); + request.Cancel(At.AddMinutes(1), Subject).IsFailure.Should().BeTrue("closure is irreversible once Begin commits"); + request.StartFulfilling(At.AddMinutes(1), UserId.SystemActor).IsFailure.Should().BeTrue(); + request.AwaitPrivilegedStep(At.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.Complete([], At.AddMinutes(2), Administrator).IsSuccess.Should().BeTrue(); + } + + [Theory] + [InlineData(DataRequestKind.Erasure)] + [InlineData(DataRequestKind.Closure)] + public void A_scheduled_request_executes_only_once_its_window_has_passed(DataRequestKind kind) + { + var request = DataSubjectRequest.FileForSelf(NewId(), kind, Subject, Group(), [Current], At).Value!; + var due = request.ExecuteAt!.Value; + + request.StartFulfilling(due.AddTicks(-1), UserId.SystemActor).IsFailure.Should().BeTrue(); + request.Status.Should().Be(DataRequestStatus.Scheduled); + request.StartFulfilling(due, UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.Status.Should().Be(DataRequestStatus.Fulfilling); + } + + [Fact] + public void An_erasure_is_cancellable_only_inside_its_window_and_a_closure_until_its_Begin() + { + var erasure = DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Erasure, Subject, Group(), [Current], At).Value!; + erasure.Cancel(erasure.ExecuteAt!.Value, Subject).IsFailure.Should().BeTrue("the window ends at the execution time"); + erasure.Cancel(erasure.ExecuteAt!.Value.AddTicks(-1), Subject).IsSuccess.Should().BeTrue(); + + var closure = DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Closure, Subject, Group(), [Current], At).Value!; + closure.Cancel(closure.ExecuteAt!.Value.AddHours(3), Subject).IsSuccess.Should().BeTrue( + "a closure is cancellable until its Begin commits, however late"); + } + + [Theory] + [InlineData(DataRequestRefusal.BlockedHold, true)] + [InlineData(DataRequestRefusal.BlockedLastAdministrator, true)] + [InlineData(DataRequestRefusal.BlockedWindow, false)] + public void An_erasure_blocks_only_with_a_re_check_refusal(DataRequestRefusal refusal, bool admitted) + { + var request = Reach(DataRequestKind.Erasure, DataRequestStatus.Fulfilling); + request.Block(refusal, ActionTime(request, Action.Block), UserId.SystemActor).IsSuccess.Should().Be(admitted); + if (admitted) request.LastRefusal.Should().Be(refusal); + } + + [Fact] + public void Export_too_large_is_an_export_failure_only() + { + var erasure = Reach(DataRequestKind.Erasure, DataRequestStatus.Fulfilling); + erasure.Fail(DataRequestFailureReason.ExportTooLarge, ActionTime(erasure, Action.Fail), UserId.SystemActor) + .IsFailure.Should().BeTrue(); + erasure.Fail(DataRequestFailureReason.ExecutionFailed, ActionTime(erasure, Action.Fail), UserId.SystemActor) + .IsSuccess.Should().BeTrue(); + + var export = Reach(DataRequestKind.Export, DataRequestStatus.Fulfilling); + export.Fail(DataRequestFailureReason.ExportTooLarge, ActionTime(export, Action.Fail), UserId.SystemActor).IsSuccess.Should().BeTrue(); + export.FailureReason.Should().Be(DataRequestFailureReason.ExportTooLarge); + export.Fail((DataRequestFailureReason)99, At.AddDays(3), UserId.SystemActor).IsFailure.Should().BeTrue(); + } + + [Fact] + public void A_refusal_is_recorded_on_a_scheduled_request_only_and_repeats_are_no_ops() + { + var closure = DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Closure, Subject, Group(), [Current], At).Value!; + closure.RecordRefusal(DataRequestRefusal.BlockedWindow, At.AddMinutes(1), Administrator).IsSuccess.Should().BeTrue(); + var version = closure.Version; + closure.RecordRefusal(DataRequestRefusal.BlockedWindow, At.AddMinutes(2), Administrator).IsSuccess.Should().BeTrue(); + closure.Version.Should().Be(version, "recording the same refusal again changes nothing"); + closure.RecordRefusal(DataRequestRefusal.BlockedLastAdministrator, At.AddMinutes(3), Administrator).IsSuccess.Should().BeTrue(); + closure.LastRefusal.Should().Be(DataRequestRefusal.BlockedLastAdministrator); + closure.Status.Should().Be(DataRequestStatus.Scheduled); + + var export = Reach(DataRequestKind.Export, DataRequestStatus.Fulfilling); + export.RecordRefusal(DataRequestRefusal.BlockedHold, At.AddDays(1), Administrator).IsFailure.Should().BeTrue(); + } + + [Fact] + public void Progress_records_each_participant_once_and_only_while_fulfilling() + { + var request = Reach(DataRequestKind.Erasure, DataRequestStatus.Fulfilling); + var at = ActionTime(request, Action.AwaitPrivilegedStep); + request.RecordParticipantCompleted("identity", at, UserId.SystemActor).IsSuccess.Should().BeTrue(); + var version = request.Version; + request.RecordParticipantCompleted("identity", at.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.Version.Should().Be(version, "a resumed job re-recording a participant changes nothing"); + request.RecordParticipantCompleted("tenancy", at.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.Progress.Should().BeEquivalentTo(new Dictionary + { + ["identity"] = at, + ["tenancy"] = at.AddMinutes(1), + }); + foreach (var malformed in new[] { "", "Identity", "1identity", "identity-module", new string('a', 33) }) + request.RecordParticipantCompleted(malformed, at.AddMinutes(2), UserId.SystemActor).IsFailure.Should().BeTrue(malformed); + + request.AwaitPrivilegedStep(at.AddMinutes(3), UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.RecordParticipantCompleted("audit", at.AddMinutes(4), UserId.SystemActor).IsFailure.Should().BeTrue( + "progress closes when the request leaves fulfilling"); + } + + [Fact] + public void The_retained_report_is_a_closed_kind_to_count_map() + { + var request = Reach(DataRequestKind.Erasure, DataRequestStatus.Fulfilling); + var at = ActionTime(request, Action.AwaitPrivilegedStep); + request.RecordRetained([new(RetainedReferenceKind.ConsentEvidence, 2), new(RetainedReferenceKind.AttributionReference, 7)], + at, UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.ResultJson.Should().Be("{\"attribution_reference\":7,\"consent_evidence\":2}", "sorted closed codes and counts, nothing else"); + request.RecordRetained([new(RetainedReferenceKind.ConsentEvidence, 1), new(RetainedReferenceKind.ConsentEvidence, 1)], + at.AddMinutes(1), UserId.SystemActor).IsFailure.Should().BeTrue("a kind is reported once"); + request.AwaitPrivilegedStep(at.AddMinutes(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + request.Complete([new(RetainedReferenceKind.AuditActorReference, 3), new(RetainedReferenceKind.ConsentEvidence, 2)], + at.AddMinutes(3), Administrator).IsSuccess.Should().BeTrue(); + request.RetainedReport.Should().BeEquivalentTo(new Dictionary + { + [RetainedReferenceKind.AuditActorReference] = 3, + [RetainedReferenceKind.ConsentEvidence] = 2, + }); + request.CompletedAt.Should().Be(at.AddMinutes(3)); + FluentActions.Invoking(() => new RetainedReferenceCount(RetainedReferenceKind.ExternalCopy, -1)) + .Should().Throw(); + } + + [Fact] + public void Every_legal_path_leaves_the_snapshot_exactly_as_filed() + { + foreach (var (kind, statuses) in Reachable) + foreach (var status in statuses) + { + var request = Reach(kind, status, out var filed); + Snapshot(request).Should().Be(Snapshot(filed), $"{kind} reaching {status} keeps its snapshot"); + } + } + + [Fact] + public void The_snapshot_members_have_no_setter_outside_the_aggregate() + { + string[] snapshot = + [ + nameof(DataSubjectRequest.TenantId), nameof(DataSubjectRequest.OrganizationId), nameof(DataSubjectRequest.Kind), + nameof(DataSubjectRequest.Origin), nameof(DataSubjectRequest.SubjectUserId), nameof(DataSubjectRequest.RequesterUserId), + nameof(DataSubjectRequest.MembershipSnapshotJson), nameof(DataSubjectRequest.ExecuteAt), + ]; + foreach (var name in snapshot) + { + var setter = typeof(DataSubjectRequest).GetProperty(name)!.GetSetMethod(nonPublic: true); + setter.Should().NotBeNull(); + setter!.IsPrivate.Should().BeTrue($"{name} is set by a factory only"); + } + + typeof(DataSubjectRequest).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(method => !method.IsSpecialName).Select(method => method.Name).Distinct() + .Should().BeEquivalentTo(["StartFulfilling", "AwaitPrivilegedStep", "Complete", "Fail", "Block", "Cancel", + "RecordRefusal", "RecordParticipantCompleted", "RecordRetained"], + "the transitions and the two records are the only mutators"); + } + + [Fact] + public void Creation_refuses_an_empty_duplicated_or_unbounded_snapshot_and_unreal_people() + { + DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, Subject, Group(), [], At).IsFailure.Should().BeTrue(); + DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, Subject, Group(), [Current, Current], At).IsFailure.Should().BeTrue(); + DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, Subject, Group(), + Enumerable.Range(0, 257).Select(_ => MembershipId.From(Guid.CreateVersion7())).ToArray(), At).IsFailure.Should().BeTrue(); + DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, UserId.SystemActor, Group(), [Current], At).IsFailure.Should().BeTrue(); + DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.NewGuid()), DataRequestKind.Export, Subject, Group(), [Current], At) + .IsFailure.Should().BeTrue("identifiers are UUIDv7"); + DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, Subject, Group(), [Current], At.ToOffset(TimeSpan.FromHours(3))) + .IsFailure.Should().BeTrue("instants are UTC"); + DataSubjectRequest.FileForSelf(NewId(), (DataRequestKind)0, Subject, Group(), [Current], At).IsFailure.Should().BeTrue(); + } + + [Fact] + public void A_transition_refuses_a_stamp_earlier_than_the_last_one() + { + var request = DataSubjectRequest.FileForSelf(NewId(), DataRequestKind.Export, Subject, Group(), [Current], At).Value!; + request.StartFulfilling(At.AddTicks(-1), UserId.SystemActor).IsFailure.Should().BeTrue(); + request.StartFulfilling(At, UserId.SystemActor).IsSuccess.Should().BeTrue(); + } + + [Fact] + public void The_closed_codes_are_the_ADR_spellings() + { + DataRequestCodes.Kinds.Codes.Should().Equal("export", "erasure", "closure"); + DataRequestCodes.Statuses.Codes.Should().Equal("requested", "scheduled", "fulfilling", "awaiting_privileged_step", + "completed", "blocked", "failed", "cancelled"); + DataRequestCodes.Origins.Codes.Should().Equal("self", "administrator", "closure_fanout"); + DataRequestCodes.Refusals.Codes.Should().Equal("blocked_window", "blocked_hold", "blocked_last_administrator"); + DataRequestCodes.FailureReasons.Codes.Should().Equal("export_too_large", "execution_failed"); + DataRequestCodes.ArtifactStatuses.Codes.Should().Equal("available", "revoked", "expired", "purged"); + DataRequestCodes.RetainedKinds.Codes.Should().Equal("consent_evidence", "invitation_record", "invitation_envelope", + "audit_actor_reference", "audit_entity_reference", "audit_metadata_reference", "unscoped_audit_rows", + "transport_evidence", "execution_evidence", "provider_event_record", "idempotency_cache", "attribution_reference", + "federation_actor_reference", "request_receipt", "external_copy", "unserved_group"); + DataRequestCodes.NonTerminal.Should().BeEquivalentTo([DataRequestStatus.Requested, DataRequestStatus.Scheduled, + DataRequestStatus.Fulfilling, DataRequestStatus.AwaitingPrivilegedStep]); + DataRequestCodes.Statuses.TryParse("AwaitingPrivilegedStep", out _).Should().BeFalse("member names are not codes"); + DataRequestCodes.Statuses.TryParse("Completed", out _).Should().BeFalse("codes are case-sensitive"); + FluentActions.Invoking(() => DataRequestCodes.Kinds.Parse("delete")).Should().Throw(); + FluentActions.Invoking(() => DataRequestCodes.Kinds.ToCode((DataRequestKind)0)).Should().Throw(); + } + + [Fact] + public void Stored_documents_are_read_strictly() + { + FluentActions.Invoking(() => DataRequestDocuments.ReadMemberships("[]")).Should().Throw(); + FluentActions.Invoking(() => DataRequestDocuments.ReadMemberships("[\"" + Guid.NewGuid() + "\"]")) + .Should().Throw("only UUIDv7 Membership identifiers"); + FluentActions.Invoking(() => DataRequestDocuments.ReadMemberships("{}")).Should().Throw(); + FluentActions.Invoking(() => DataRequestDocuments.ReadProgress("{\"identity\":\"yesterday\"}")).Should().Throw(); + FluentActions.Invoking(() => DataRequestDocuments.ReadResult("{\"anonymous\":1}")) + .Should().Throw("nothing is reported outside the closed kinds"); + FluentActions.Invoking(() => DataRequestDocuments.ReadResult("{\"consent_evidence\":-1}")).Should().Throw(); + // jsonb re-spaces and reorders what it stores; the reader accepts that form. + var current = Current.Value.ToString("D"); + DataRequestDocuments.ReadMemberships($"[\"{current}\"]").Should().Equal(Current); + DataRequestDocuments.ReadProgress("{\"identity\": \"2026-11-22T09:00:00.0000000Z\"}")["identity"].Should().Be(At); + } + + private static DataSubjectRequest Reach(DataRequestKind kind, DataRequestStatus status) => Reach(kind, status, out _); + + /// Walks the legal path to a status, from a freshly filed request whose snapshot copy is returned. + private static DataSubjectRequest Reach(DataRequestKind kind, DataRequestStatus status, out DataSubjectRequest filed) + { + var id = NewId(); + filed = DataSubjectRequest.FileForSelf(id, kind, Subject, Group(), [Current, Tombstone], At).Value!; + var request = DataSubjectRequest.FileForSelf(id, kind, Subject, Group(), [Current, Tombstone], At).Value!; + Action[] path = (kind, status) switch + { + (_, DataRequestStatus.Requested or DataRequestStatus.Scheduled) => [], + (_, DataRequestStatus.Cancelled) => [Action.Cancel], + (_, DataRequestStatus.Fulfilling) => [Action.StartFulfilling], + (DataRequestKind.Erasure, DataRequestStatus.AwaitingPrivilegedStep) => [Action.StartFulfilling, Action.AwaitPrivilegedStep], + (DataRequestKind.Erasure, DataRequestStatus.Completed) => [Action.StartFulfilling, Action.AwaitPrivilegedStep, Action.Complete], + (_, DataRequestStatus.Completed) => [Action.StartFulfilling, Action.Complete], + (_, DataRequestStatus.Blocked) => [Action.StartFulfilling, Action.Block], + (_, DataRequestStatus.Failed) => [Action.StartFulfilling, Action.Fail], + _ => throw new InvalidOperationException("No legal path is declared for this status."), + }; + foreach (var step in path) + Apply(request, step, ActionTime(request, step)).IsSuccess.Should().BeTrue($"{kind} path to {status} at {step}"); + request.Status.Should().Be(status); + return request; + } + + private static DateTimeOffset ActionTime(DataSubjectRequest request, Action action) => + action == Action.StartFulfilling && request.ExecuteAt is { } due && request.Status == DataRequestStatus.Scheduled + ? due + : (request.UpdatedAt ?? request.CreatedAt).AddMinutes(1); + + private static LearnStack.SharedKernel.Results.Result Apply( + DataSubjectRequest request, Action action, DateTimeOffset at) => action switch + { + Action.StartFulfilling => request.StartFulfilling(at, UserId.SystemActor), + Action.AwaitPrivilegedStep => request.AwaitPrivilegedStep(at, UserId.SystemActor), + Action.Complete => request.Complete([], at, UserId.SystemActor), + Action.Fail => request.Fail(DataRequestFailureReason.ExecutionFailed, at, UserId.SystemActor), + Action.Block => request.Block(DataRequestRefusal.BlockedHold, at, UserId.SystemActor), + _ => request.Cancel(at, Subject), + }; + + private static string Snapshot(DataSubjectRequest request) => string.Join("|", request.Id, request.TenantId, + request.OrganizationId, request.Kind, request.Origin, request.SubjectUserId, request.RequesterUserId, + request.MembershipSnapshotJson, request.ExecuteAt, request.CreatedAt, request.CreatedBy); + + private static DataRequestScopeGroup Group() => new(Tenant, Organization); + + private static DataSubjectRequestId NewId() => DataSubjectRequestId.From(Guid.CreateVersion7()); +} diff --git a/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/DataRequestPortTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/DataRequestPortTests.cs new file mode 100644 index 00000000..670f9fbb --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/DataRequestPortTests.cs @@ -0,0 +1,150 @@ +using FluentAssertions; +using LearnStack.Application.DataProtection; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace LearnStack.Tests.Unit.SharedKernel.DataProtection; + +/// The SharedKernel data-request ports (ADR-0106 § 7, ADR-0107 § 1 and § 4) and the participant seam. +public sealed class DataRequestPortTests +{ + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly UserId Subject = UserId.From(Guid.CreateVersion7()); + + [Fact] + public void A_scope_group_is_a_real_tenant_and_an_optional_real_organization() + { + new DataRequestScopeGroup(Tenant, null).IsTenantWide.Should().BeTrue(); + new DataRequestScopeGroup(Tenant, OrganizationId.From(Guid.CreateVersion7())).IsTenantWide.Should().BeFalse(); + FluentActions.Invoking(() => new DataRequestScopeGroup(TenantId.PlatformSentinel, null)).Should().Throw( + "a tenant request never carries the platform sentinel"); + FluentActions.Invoking(() => new DataRequestScopeGroup(TenantId.From(Guid.Empty), null)).Should().Throw(); + FluentActions.Invoking(() => new DataRequestScopeGroup(Tenant, OrganizationId.From(Guid.Empty))).Should().Throw(); + } + + [Fact] + public void A_participant_subject_carries_a_bounded_frozen_snapshot_and_prints_nothing() + { + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, Subject, + new DataRequestScopeGroup(Tenant, null), [Guid.CreateVersion7()]); + subject.ToString().Should().Be(nameof(UserDataSubject)); + subject.MembershipIds.Should().ContainSingle(); + + var group = new DataRequestScopeGroup(Tenant, null); + FluentActions.Invoking(() => new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + Subject, group, [])).Should().Throw(); + var duplicate = Guid.CreateVersion7(); + FluentActions.Invoking(() => new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + Subject, group, [duplicate, duplicate])).Should().Throw(); + FluentActions.Invoking(() => new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + UserId.SystemActor, group, [Guid.CreateVersion7()])).Should().Throw(); + FluentActions.Invoking(() => new UserDataSubject(Guid.Empty, DataRequestKind.Export, DataRequestOrigin.Self, + Subject, group, [Guid.CreateVersion7()])).Should().Throw(); + } + + [Fact] + public void Eligibility_queries_name_their_request_only_at_execution_and_decisions_are_closed() + { + var group = new DataRequestScopeGroup(Tenant, null); + _ = new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, group, DataRequestEligibilityStage.Creation); + _ = new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, group, + DataRequestEligibilityStage.Execution, Guid.CreateVersion7()); + FluentActions.Invoking(() => new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, group, + DataRequestEligibilityStage.Execution)).Should().Throw(); + FluentActions.Invoking(() => new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, group, + DataRequestEligibilityStage.Creation, Guid.CreateVersion7())).Should().Throw(); + + DataRequestEligibilityDecision.Eligible.IsEligible.Should().BeTrue(); + DataRequestEligibilityDecision.Refused(DataRequestIneligibility.BlockedHold).Refusal.Should().Be(DataRequestRefusal.BlockedHold); + DataRequestEligibilityDecision.Refused(DataRequestIneligibility.BlockedLastAdministrator).Refusal + .Should().Be(DataRequestRefusal.BlockedLastAdministrator); + DataRequestEligibilityDecision.Refused(DataRequestIneligibility.RequestAlreadyActive).Refusal.Should().BeNull( + "an already-active request is a 409 response, not a recorded refusal"); + FluentActions.Invoking(() => DataRequestEligibilityDecision.Refused((DataRequestIneligibility)9)) + .Should().Throw(); + } + + [Fact] + public async Task The_default_hold_source_reports_no_hold() + { + var query = new DataRequestHoldQuery(DataRequestKind.Closure, Subject, new DataRequestScopeGroup(Tenant, null)); + (await new NoHoldSource().HasHoldAsync(query, CancellationToken.None)).Should().BeFalse(); + } + + [Fact] + public void Artifact_store_values_carry_the_chunk_bounds_and_print_no_content() + { + var put = new DataExportArtifactPut(Guid.CreateVersion7(), Guid.CreateVersion7(), Subject, + new DataRequestScopeGroup(Tenant, null), DataRequestLimits.ChunkPlaintextBytes + 1); + put.ChunkCount.Should().Be(2); + FluentActions.Invoking(() => new DataExportArtifactPut(Guid.CreateVersion7(), Guid.CreateVersion7(), Subject, + new DataRequestScopeGroup(Tenant, null), DataRequestLimits.MaximumBundleBytes + 1)).Should().Throw(); + + var chunk = new DataExportPlaintextChunk(0, 1, new byte[] { 1, 2, 3 }); + chunk.ToString().Should().Be(nameof(DataExportPlaintextChunk)); + FluentActions.Invoking(() => new DataExportPlaintextChunk(1, 1, new byte[] { 1 })).Should().Throw(); + FluentActions.Invoking(() => new DataExportPlaintextChunk(0, 1, new byte[DataRequestLimits.ChunkPlaintextBytes + 1])) + .Should().Throw(); + DataRequestLimits.MaximumChunkCount.Should().Be(512); + DataRequestLimits.ChunkPlaintextBytes.Should().Be(131072); + DataRequestLimits.NonceBytes.Should().Be(12); + DataRequestLimits.TagBytes.Should().Be(16); + } + + [Fact] + public void The_registry_orders_participants_by_key_and_refuses_duplicates_and_malformed_keys() + { + var registry = new UserDataParticipantRegistry([new Participant("tenancy"), new Participant("identity")]); + registry.Participants.Select(participant => participant.Key).Should().Equal("identity", "tenancy"); + registry.TryGet("identity", out var found).Should().BeTrue(); + found!.Key.Should().Be("identity"); + registry.TryGet("Identity", out _).Should().BeFalse("keys are ordinal"); + + FluentActions.Invoking(() => new UserDataParticipantRegistry([new Participant("identity"), new Participant("identity")])) + .Should().Throw("two participants writing one progress key would skip unfinished work"); + FluentActions.Invoking(() => new UserDataParticipantRegistry([new Participant("Identity-Module")])) + .Should().Throw(); + new UserDataParticipantRegistry([]).Participants.Should().BeEmpty("no module registers a participant yet"); + } + + [Fact] + public async Task The_composition_seam_collects_module_registrations_and_defaults_the_hold_source() + { + var services = new ServiceCollection(); + services.AddLearnStackUserDataProtection(); + services.AddLearnStackUserDataProtection(); + services.AddScoped(_ => new Participant("identity")); + await using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }); + await using var scope = provider.CreateAsyncScope(); + + scope.ServiceProvider.GetRequiredService().Participants.Should().ContainSingle() + .Which.Key.Should().Be("identity"); + scope.ServiceProvider.GetRequiredService().Should().BeOfType(); + services.Count(descriptor => descriptor.ServiceType == typeof(IUserDataParticipantRegistry)).Should().Be(1); + } + + [Fact] + public async Task A_participant_without_an_erasure_erases_nothing() + { + IUserDataParticipant participant = new Participant("audit"); + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, + new DataRequestScopeGroup(Tenant, null), [Guid.CreateVersion7()]); + await participant.EraseAsync(subject, CancellationToken.None); + (await participant.DescribeRetainedAsync(subject, CancellationToken.None)).Should().ContainSingle() + .Which.Kind.Should().Be(RetainedReferenceKind.AuditActorReference); + } + + private sealed class Participant(string key) : IUserDataParticipant + { + public string Key => key; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => + Task.CompletedTask; + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => + Task.FromResult>([new(RetainedReferenceKind.AuditActorReference, 1)]); + } +} diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 1d26036b..2555160e 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -307,6 +307,10 @@ govern personal data; exclusion here grants no erasure exemption. | `role_permission_grants` | Synchronous explicit authority definitions, not delivery or diagnostic copies | | `invitations` | Synchronous scoped Identity offer and acceptance result, including sensitive recipient/verifier and job linkage; the invitation inventory below owns fulfillment constraints | | `federation_connections` | Synchronous tenant-owned federation configuration (ADR-0099): public IdP identifiers, nonsecret digests and lifecycle, with pseudonymous pending/test actor identifiers; no secret, token or assertion and no queued payload | +| `data_subject_requests` | Synchronous organization-scoped subject request receipt (ADR-0106): subject and requester UserId, frozen Membership identifiers, closed status/refusal/failure codes, participant progress and retained-kind counts; retained as `request_receipt` with Phase 11 retention, and the job parameters carry identifiers only | +| `data_export_artifacts` | Synchronous export receipt metadata (ADR-0107 § 4): subject, request, size, chunk count, key-ring label and lifecycle; no content or key; retained as `request_receipt` after its chunks are purged | +| `data_export_tickets` | Synchronous session-bound download cursor (ADR-0107 § 4): subject, artifact and credential digests only, never the ticket value; retained as `request_receipt` | +| `data_export_chunks` | Synchronous encrypted export bundle (ADR-0107 § 4): PII-Sensitive AES-256-GCM ciphertext of the subject's own data, never in an EF snapshot or audit row; purged at revocation, expiry or erasure, not an asynchronous delivery copy | LearnStack job-table no-delete triggers also bind the owner; BYPASSRLS is not diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 8aae8089..49fa85c0 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -79,6 +79,8 @@ "LearnStack.Tests.Integration.Database.CustomizationProjectionTests", "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests", "LearnStack.Tests.Integration.Database.CustomizationSchemaTests", + "LearnStack.Tests.Integration.Database.DataRequestStorageControlTests", + "LearnStack.Tests.Integration.Database.DataRequestStorageTests", "LearnStack.Tests.Integration.Database.DatabaseQualificationProofTests", "LearnStack.Tests.Integration.Database.DatabaseRoleTests", "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests", From 2929f22feba15b3b40a88ac4f95af8703e2f899d Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 07:01:21 +0300 Subject: [PATCH 05/61] feat(identity): add the retained own data-request scope P03-10 Step 1, unit 3: fn_identity_own_data_request_scopes with its two owner arms, the HostAndOwnDataRequestScope origin and witness, the unit-of-work setter, and the key-less OwnDataRequest and OwnDataRequestEntry policy kinds. The native entry endpoints follow with the request API. ADR: 0106, 0107, 0095 Module: Identity, SharedKernel, Application, Api Co-Authored-By: Claude Sonnet 5.5 --- .../OperationAuthorizationPolicyProvider.cs | 1 + .../OperationHttpClassification.cs | 3 +- .../PersistenceCompositionExtensions.cs | 2 + .../OperationAuthorizationCoordinator.cs | 13 +- .../TransactionExecutionCoordinator.cs | 12 + .../Pipeline/TenantContextBehavior.cs | 3 + .../NpgsqlUnitOfWork.OwnDataRequest.cs | 52 ++ .../Persistence/NpgsqlUnitOfWork.cs | 35 +- .../Identity/OwnDataRequestScopeWitness.cs | 138 +++++ .../Permissions/OperationPolicy.cs | 20 +- .../Permissions/ProtectedOperationDecision.cs | 23 +- .../Persistence/IOwnDataRequestUnitOfWork.cs | 15 + .../Tenancy/TenantContextFactory.cs | 20 + .../Tenancy/TenantContextOrigin.cs | 7 + .../IOwnDataRequestScopeLookup.cs | 29 + .../IdentityOperationAuthorizer.cs | 18 +- .../Authorization/IdentityPolicyEvaluation.cs | 16 + .../IdentityAuthorizationRegistration.cs | 3 +- ...61122140000_add_own_data_request_scopes.cs | 17 + .../Persistence/OwnDataRequestScopeDdl.cs | 123 ++++ .../Persistence/OwnDataRequestScopeLookup.cs | 118 ++++ ...itConventionTests.AuthorizationEvidence.cs | 3 +- ...tegrationDeliveryLifecycleBoundaryTests.cs | 57 +- .../OperationPolicyOwnershipTests.cs | 2 +- .../OwnDataRequestScopeConventionTests.cs | 145 +++++ .../TenancyConventionTests.ScopeCarrier.cs | 2 +- .../TenantContextConstructionTests.cs | 8 +- .../GlobalIdentitySchemaTests.Controls.cs | 9 +- ...IdentitySchemaTests.EntryPolicyControls.cs | 14 +- .../Database/GlobalIdentitySchemaTests.cs | 7 +- .../Database/InvitationSmtpStorageTests.cs | 6 +- .../Database/MigrationRollbackTests.cs | 10 +- .../Database/OwnDataRequestScopeTests.cs | 531 ++++++++++++++++++ .../Identity/OwnDataRequestPolicyTests.cs | 492 ++++++++++++++++ docs/standards/05-database.md | 96 +++- docs/standards/11-security.md | 18 +- docs/standards/19-permissions.md | 13 + .../21-architecture-tests-catalogue.md | 40 +- scripts/ci-test-shards-plan.json | 1 + 39 files changed, 2059 insertions(+), 63 deletions(-) create mode 100644 backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.OwnDataRequest.cs create mode 100644 backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs create mode 100644 backend/src/LearnStack.SharedKernel/Persistence/IOwnDataRequestUnitOfWork.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122140000_add_own_data_request_scopes.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeDdl.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs create mode 100644 backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs diff --git a/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs b/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs index ba1c0577..c25a618a 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs @@ -25,6 +25,7 @@ internal sealed class OperationAuthorizationPolicyProvider(IOptions(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/src/LearnStack.Application/Authorization/OperationAuthorizationCoordinator.cs b/backend/src/LearnStack.Application/Authorization/OperationAuthorizationCoordinator.cs index f6692719..185ca47c 100644 --- a/backend/src/LearnStack.Application/Authorization/OperationAuthorizationCoordinator.cs +++ b/backend/src/LearnStack.Application/Authorization/OperationAuthorizationCoordinator.cs @@ -36,6 +36,9 @@ public sealed class OperationAuthorizationCoordinator( public LearnStack.SharedKernel.Identity.ConsentSubjectScopeWitness? CurrentConsentWitness => CurrentDecision is { ConsentWitness: { IsActive: true } witness } ? witness : null; + public LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness? CurrentDataRequestWitness => + CurrentDecision is { DataRequestWitness: { IsActive: true } witness } ? witness : null; + public ProtectedOperationDecision? CurrentDecision => _current.Value is { Closed: false, Decision: { IsActive: true } decision } ? decision : null; @@ -90,9 +93,14 @@ private async Task ExecuteAsync(object operation, Operatio else trusted = captured[0]; break; case OperationPolicyKind.OwnConsentEntry: + case OperationPolicyKind.OwnDataRequestEntry: case OperationPolicyKind.InvitationEntry: - var requiredOrigin = policy.Kind == OperationPolicyKind.OwnConsentEntry - ? TenantContextOrigin.HostAndConsentSubjectScope : TenantContextOrigin.HostAndInvitationOffer; + var requiredOrigin = policy.Kind switch + { + OperationPolicyKind.OwnConsentEntry => TenantContextOrigin.HostAndConsentSubjectScope, + OperationPolicyKind.OwnDataRequestEntry => TenantContextOrigin.HostAndOwnDataRequestScope, + _ => TenantContextOrigin.HostAndInvitationOffer, + }; if (!context.IsResolved || context.Origin != requiredOrigin || context.HostScope is not { } offerHost || offerHost.TenantId != context.TenantId || offerHost.OrganizationId is { } offerOrganization && offerOrganization != context.OrganizationId) @@ -107,6 +115,7 @@ private async Task ExecuteAsync(object operation, Operatio case OperationPolicyKind.NativeSessionAdmission: case OperationPolicyKind.OwnMembershipRead: case OperationPolicyKind.OwnFieldConsentGrant: + case OperationPolicyKind.OwnDataRequest: case OperationPolicyKind.Protected: if (!HasProtectedContext() || (policy.Kind is OperationPolicyKind.AccountRead or OperationPolicyKind.NativeSessionAdmission diff --git a/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs index 48dcd35d..9c4851aa 100644 --- a/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs +++ b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs @@ -82,6 +82,13 @@ private async Task ExecuteCoreAsync( throw new InvalidOperationException("Consent execution requires its exact fresh owner."); scope = await entry.BeginConsentSubjectTransactionAsync(consent, tenantContext, cancellationToken); } + else if (authorization?.CurrentDataRequestWitness is { } dataRequest) + { + if (!openingOwner || dataRequest.Mode != mode || dataRequest.Invocation.Policy.RequestType != operationType + || !ReferenceEquals(dataRequest.Invocation.Operation, operation) || unitOfWork is not IOwnDataRequestUnitOfWork entry) + throw new InvalidOperationException("Own data request execution requires its exact fresh owner."); + scope = await entry.BeginOwnDataRequestTransactionAsync(dataRequest, tenantContext, cancellationToken); + } else scope = await unitOfWork.BeginTransactionAsync(mode, cancellationToken); } catch @@ -193,6 +200,11 @@ private async Task ExecuteFrameAsync( if (!scope.IsOwner || unitOfWork is not IConsentSubjectUnitOfWork entry || !entry.IsConsentSubjectOwner(consent)) throw new InvalidOperationException("Consent execution lost its owner."); } + else if (authorization?.CurrentDataRequestWitness is { } dataRequest) + { + if (!scope.IsOwner || unitOfWork is not IOwnDataRequestUnitOfWork entry || !entry.IsOwnDataRequestOwner(dataRequest)) + throw new InvalidOperationException("Own data request execution lost its owner."); + } else if (!tenantContext.IsResolved && provisioning is not null) { await unitOfWork.SetProvisioningTenantContextAsync( diff --git a/backend/src/LearnStack.Application/Pipeline/TenantContextBehavior.cs b/backend/src/LearnStack.Application/Pipeline/TenantContextBehavior.cs index 44640943..d6f1a737 100644 --- a/backend/src/LearnStack.Application/Pipeline/TenantContextBehavior.cs +++ b/backend/src/LearnStack.Application/Pipeline/TenantContextBehavior.cs @@ -164,6 +164,9 @@ tenantContext.Origin is TenantContextOrigin.HostOnly or TenantContextOrigin.Host TenantContextOrigin.HostAndConsentSubjectScope => !IsPublicSurface && policies is not null && policies.TryGet(typeof(TRequest), out var consentPolicy) && consentPolicy.Kind == LearnStack.SharedKernel.Permissions.OperationPolicyKind.OwnConsentEntry, + TenantContextOrigin.HostAndOwnDataRequestScope => !IsPublicSurface && policies is not null + && policies.TryGet(typeof(TRequest), out var dataRequestPolicy) + && dataRequestPolicy.Kind == LearnStack.SharedKernel.Permissions.OperationPolicyKind.OwnDataRequestEntry, // null — an implementation that states no origin — and any member added later // without deciding its ceiling. Fail-closed, which is the whole reason this is diff --git a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.OwnDataRequest.cs b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.OwnDataRequest.cs new file mode 100644 index 00000000..24a650bd --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.OwnDataRequest.cs @@ -0,0 +1,52 @@ +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Infrastructure.Persistence; + +/// +/// The retained own data-request scope's logical tenant setter (ADR-0106 § 9): a fresh owner in the witness's +/// mode that announces exactly the witness's group through the one private witness-aware core. +/// +public sealed partial class NpgsqlUnitOfWork +{ + private OwnDataRequestScopeWitness? _dataRequestWitness; + + public bool IsOwnDataRequestOwner(OwnDataRequestScopeWitness witness) => + ReferenceEquals(_dataRequestWitness, witness) && _transaction is not null + && witness.IsBoundTo(this, _transaction, _generation) && _mode == witness.Mode + && _depth == 1 && !_disposed && !_rollbackOnly && _tenantContextIssued; + + public async Task BeginOwnDataRequestTransactionAsync(OwnDataRequestScopeWitness witness, + ITenantContext context, CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ObjectDisposedException.ThrowIf(_disposed, this); + RequireWriteAllowed(); + ArgumentNullException.ThrowIfNull(witness); + if (HasActiveTransaction || IsGlobalIdentityTransaction || _dataRequestWitness is not null || _consentWitness is not null + || _invitationWitness is not null || _selfDiscoveryWitness is not null || _openingSelfDiscovery + || _jobSourceOwner is not null || JobApplicationSourceOwner.Current is not null || !witness.IsActive + || !ReferenceEquals(witness.Invocation.Context, context)) + { + MarkRollbackOnly(); + throw new InvalidOperationException("Own data request entry requires its fresh exact operation owner."); + } + IUnitOfWorkScope? frame = null; + try + { + frame = await BeginTransactionCoreAsync(witness.Mode, globalIdentity: false, cancellationToken); + await SetTenantContextCoreAsync(context, null, false, cancellationToken, dataRequestWitness: witness); + if (!IsOwnDataRequestOwner(witness)) throw new InvalidOperationException("Own data request provenance closed."); + return frame; + } + catch + { + MarkRollbackOnly(); + try { await RollbackCoreAsync(); } catch { LogSetupCleanupFailure(_logger, null); } + if (frame is not null) await frame.DisposeAsync(); + throw; + } + } +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs index 21baf7ab..f02800f1 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs @@ -51,7 +51,8 @@ namespace LearnStack.Infrastructure.Persistence; /// public sealed partial class NpgsqlUnitOfWork : IGlobalIdentityUnitOfWork, IOperationReadScopeView, IPreContextSelfDiscoveryUnitOfWork, IFixedSeedPrerequisiteUnitOfWork, IUnitOfWorkWriteGuard, - IUnitOfWorkContextEnrollment, IInvitationEntryUnitOfWork, IConsentSubjectUnitOfWork, IConfidentialCommitUnitOfWork + IUnitOfWorkContextEnrollment, IInvitationEntryUnitOfWork, IConsentSubjectUnitOfWork, IOwnDataRequestUnitOfWork, + IConfidentialCommitUnitOfWork { private readonly NpgsqlDataSource _dataSource; @@ -170,7 +171,8 @@ private async Task BeginTransactionCoreAsync( ObjectDisposedException.ThrowIf(_disposed || _idempotencyEnding, this); RequireWriteAllowed(); - if (_selfDiscoveryWitness is not null || _invitationWitness is not null || _consentWitness is not null) + if (_selfDiscoveryWitness is not null || _invitationWitness is not null || _consentWitness is not null + || _dataRequestWitness is not null) { MarkRollbackOnly(); throw new InvalidOperationException("A transaction cannot join a captured entry owner."); @@ -434,7 +436,7 @@ public Task SetTenantContextAsync(ITenantContext context, OperationReadWitness r private async Task SetTenantContextCoreAsync(ITenantContext context, OperationReadWitness? readWitness, bool tenantWideRead, CancellationToken cancellationToken, InvitationEntryScopeWitness? invitationWitness = null, - ConsentSubjectScopeWitness? consentWitness = null) + ConsentSubjectScopeWitness? consentWitness = null, OwnDataRequestScopeWitness? dataRequestWitness = null) { JobApplicationSourceOwner.RefuseExternalEntry(); ObjectDisposedException.ThrowIf(_disposed, this); @@ -449,6 +451,7 @@ private async Task SetTenantContextCoreAsync(ITenantContext context, OperationRe if (context.Origin == TenantContextOrigin.ProviderEventRecipient && (context is not ProviderEventRecipient recipient || _depth != 1 || _tenantContextIssued || _transaction is null || tenantWideRead || invitationWitness is not null || consentWitness is not null + || dataRequestWitness is not null || !recipient.TryBind(this, _transaction, _generation))) { MarkRollbackOnly(); @@ -470,6 +473,15 @@ private async Task SetTenantContextCoreAsync(ITenantContext context, OperationRe MarkRollbackOnly(); throw new InvalidOperationException("Consent context requires its exact unused subject witness."); } + if (_dataRequestWitness is not null + || (context.Origin == TenantContextOrigin.HostAndOwnDataRequestScope) != (dataRequestWitness is not null) + || dataRequestWitness is not null && (invitationWitness is not null || consentWitness is not null || _depth != 1 + || _tenantContextIssued || tenantWideRead || !dataRequestWitness.IsActive + || !ReferenceEquals(dataRequestWitness.Invocation.Context, context))) + { + MarkRollbackOnly(); + throw new InvalidOperationException("Own data request context requires its exact unused subject witness."); + } if (IsGlobalIdentityTransaction || _selfDiscoveryWitness is not null) { MarkRollbackOnly(); @@ -567,6 +579,9 @@ private async Task SetTenantContextCoreAsync(ITenantContext context, OperationRe if (consentWitness is not null && (!consentWitness.TryBindTo(this, _transaction, _generation, _mode!.Value) || consentWitness.TenantId != tenantId || consentWitness.OrganizationId != organizationId || !consentWitness.IsBoundTo(this, _transaction, _generation))) RefuseOperationReadScope(); + if (dataRequestWitness is not null && (!dataRequestWitness.TryBindTo(this, _transaction, _generation, _mode!.Value) + || dataRequestWitness.TenantId != tenantId || dataRequestWitness.OrganizationId != organizationId + || !dataRequestWitness.IsBoundTo(this, _transaction, _generation))) RefuseOperationReadScope(); if (invitationWitness is not null && (!invitationWitness.TryBindTo(this, _transaction, _generation, _mode!.Value) || invitationWitness.Offer.TenantId != tenantId || invitationWitness.Offer.OrganizationId != organizationId)) RefuseOperationReadScope(); @@ -623,6 +638,11 @@ await ExecuteAsync( if (!consentWitness.IsBoundTo(this, _transaction, _generation)) RefuseOperationReadScope(); _consentWitness = consentWitness; } + if (dataRequestWitness is not null) + { + if (!dataRequestWitness.IsBoundTo(this, _transaction, _generation)) RefuseOperationReadScope(); + _dataRequestWitness = dataRequestWitness; + } _tenantContextIssued = true; _tenantContextAnnouncement = tenantId is { } announcedTenant ? new TenantContextAnnouncement(_generation, announcedTenant, organizationId) @@ -649,7 +669,8 @@ public async Task SetProvisioningTenantContextAsync( ObjectDisposedException.ThrowIf(_disposed, this); RequireWriteAllowed(); - if (_tenantWideRead || _readScopeFaulted || _invitationWitness is not null || _consentWitness is not null || _selfDiscoveryWitness is not null) RefuseOperationReadScope(); + if (_tenantWideRead || _readScopeFaulted || _invitationWitness is not null || _consentWitness is not null + || _dataRequestWitness is not null || _selfDiscoveryWitness is not null) RefuseOperationReadScope(); if (IsGlobalIdentityTransaction) { @@ -759,6 +780,11 @@ private bool ValidateOperationReadScope(bool requireCurrentFrame = true) { _rollbackOnly = true; _tenantContextIssued = false; _tenantContextAnnouncement = null; return false; } + if (_dataRequestWitness is { } dataRequest && (_transaction is null || _depth != 1 || _mode != dataRequest.Mode + || !dataRequest.IsBoundTo(this, _transaction, _generation))) + { + _rollbackOnly = true; _tenantContextIssued = false; _tenantContextAnnouncement = null; return false; + } if (_selfDiscoveryWitness is { } own && !own.IsBoundTo(this)) { _rollbackOnly = true; @@ -820,6 +846,7 @@ private void ClearTenantContextAnnouncement() _selfDiscoveryWitness = null; _invitationWitness = null; _consentWitness = null; + _dataRequestWitness = null; _providerRecipient = null; _providerCancellation.Dispose(); _providerCancellation = default; diff --git a/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs b/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs new file mode 100644 index 00000000..63897406 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs @@ -0,0 +1,138 @@ +using System.Collections.Immutable; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.SharedKernel.Identity; + +/// +/// The closed purposes of the retained own data-request scope (ADR-0106 § 9). discovers the +/// subject's groups on the real host; every other purpose acts in one exact group the function returned. +/// +public enum OwnDataRequestPurpose { List = 1, Create = 2, Read = 3, Cancel = 4, Ticket = 5, Chunk = 6 } + +/// One page of the subject's retained groups on the real host, ordered as the function returned them. +public sealed record OwnDataRequestScopePage(ImmutableArray Items, string? NextCursor); + +/// The one source that captures a verified subject, real host and retained group for an invocation. +public interface IOwnDataRequestScopeSource +{ + OwnDataRequestScopeWitness? ForInvocation(OperationInvocation invocation); +} + +/// +/// One verified subject, real host and closed data-request purpose, bound to the group +/// fn_identity_own_data_request_scopes returned for that subject; no ordinary Membership authority. +/// +/// +/// Modelled on : a single-use, immutable, privately constructed +/// witness that only an enumerated minting source captures, that the actual subsequent owner binds once +/// to its physical transaction, and that stays live only while its operation invocation, policy kind +/// (), origin +/// (), actor, group and real host all still agree. +/// +public sealed class OwnDataRequestScopeWitness +{ + /// The function's own page bound; the source never asks for more. + public const int MaximumPage = 20; + + private readonly MintingSource _source; + private readonly object _evidence; + private readonly object _gate = new(); + private (IUnitOfWork Unit, DbTransaction Transaction, long Generation)? _binding; + + private OwnDataRequestScopeWitness(MintingSource source, object evidence, OperationInvocation invocation, + GlobalIdentitySubject subject, UserId actor, TenantId hostTenant, OrganizationId? hostOrganization, + string host, OwnDataRequestPurpose purpose, DataRequestScopeGroup? group, OwnDataRequestScopePage? scopePage) + { + ArgumentNullException.ThrowIfNull(invocation); + ArgumentNullException.ThrowIfNull(subject); + if (!StronglyTypedId.IsAssigned(actor) || actor == UserId.SystemActor + || !StronglyTypedId.IsAssigned(hostTenant) || hostTenant == TenantId.PlatformSentinel + || !StronglyTypedId.IsAssignedWhenPresent(hostOrganization) || string.IsNullOrWhiteSpace(host) + || !Enum.IsDefined(purpose) || (purpose == OwnDataRequestPurpose.List) != (scopePage is not null) + || (purpose == OwnDataRequestPurpose.List) != (group is null)) + throw new ArgumentException("Own data request subject provenance refused."); + bool WithinHost(DataRequestScopeGroup scope) => scope.TenantId == hostTenant + && StronglyTypedId.IsAssignedWhenPresent(scope.OrganizationId) + && (hostOrganization is null || scope.OrganizationId == hostOrganization); + if (group is not null && !WithinHost(group) + || scopePage is not null && (scopePage.Items.IsDefault || scopePage.Items.Length > MaximumPage + || scopePage.Items.Any(scope => scope is null || !WithinHost(scope)) + || scopePage.Items.Distinct().Count() != scopePage.Items.Length + || scopePage.NextCursor is { Length: > 1024 })) + throw new ArgumentException("Own data request subject scope refused."); + _source = source; _evidence = evidence; Invocation = invocation; Actor = actor; + AuthorityId = subject.AuthorityId; SubjectKey = subject.SubjectKey; Host = host; + HostTenantId = hostTenant; HostOrganizationId = hostOrganization; Purpose = purpose; + Group = group; ScopePage = scopePage; + TenantId = group?.TenantId ?? hostTenant; + OrganizationId = group is null ? hostOrganization : group.OrganizationId; + } + + public OperationInvocation Invocation { get; } + public UserId Actor { get; } + public IdentityAuthorityId AuthorityId { get; } + [PiiSensitive] public IdentitySubjectKey SubjectKey { get; } + /// The announced tenant: the group's, or the host's for . + public TenantId TenantId { get; } + /// The announced organization: the group's, or the host's for . + public OrganizationId? OrganizationId { get; } + public TenantId HostTenantId { get; } + public OrganizationId? HostOrganizationId { get; } + /// The exact retained group; only for . + public DataRequestScopeGroup? Group { get; } + public string Host { get; } + public OwnDataRequestPurpose Purpose { get; } + public OwnDataRequestScopePage? ScopePage { get; } + + /// Discovery and status reads are physically read-only; filing, cancelling and retrieval write. + public TransactionMode Mode => Purpose is OwnDataRequestPurpose.List or OwnDataRequestPurpose.Read + ? TransactionMode.ReadOnly : TransactionMode.ReadWrite; + + public bool IsActive => _source.Current(_evidence, Invocation) && Invocation.IsActive + && Invocation.Policy.Kind == OperationPolicyKind.OwnDataRequestEntry + && Invocation.Context.Origin == TenantContextOrigin.HostAndOwnDataRequestScope + && Invocation.Actor == Actor && Invocation.TenantId == TenantId && Invocation.OrganizationId == OrganizationId + && Invocation.Context.HostScope is { } host && host.TenantId == HostTenantId && host.OrganizationId == HostOrganizationId; + + public bool TryBindTo(IUnitOfWork unit, DbTransaction transaction, long generation, TransactionMode mode) + { + lock (_gate) + { + if (!IsActive || Invocation.EntryKind != OperationEntryKind.Application || _binding is not null + || generation <= 0 || mode != Mode) return false; + _binding = (unit, transaction, generation); return true; + } + } + + public bool IsBoundTo(IUnitOfWork unit, DbTransaction transaction, long generation) => IsActive + && _binding is { } bound && ReferenceEquals(bound.Unit, unit) && ReferenceEquals(bound.Transaction, transaction) + && bound.Generation == generation; + + public override string ToString() => nameof(OwnDataRequestScopeWitness); + +#pragma warning disable CA1034 // A closed source census owns the sole production minter. + [SuppressMessage("Design", "CA1063:Implement IDisposable Correctly", Justification = "Nonvirtual disposal closes captured provenance.")] + public abstract class MintingSource : IDisposable +#pragma warning restore CA1034 + { + private int _closed; + protected bool IsOpen => Volatile.Read(ref _closed) == 0; + internal bool Current(object evidence, OperationInvocation invocation) => Volatile.Read(ref _closed) == 0 + && IsEvidenceCurrent(evidence, invocation); + protected abstract bool IsEvidenceCurrent(object evidence, OperationInvocation invocation); + protected OwnDataRequestScopeWitness Capture(object evidence, OperationInvocation invocation, + GlobalIdentitySubject subject, UserId actor, TenantId hostTenant, OrganizationId? hostOrganization, + string host, OwnDataRequestPurpose purpose, DataRequestScopeGroup? group, OwnDataRequestScopePage? page) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _closed) != 0, this); + return new(this, evidence, invocation, subject, actor, hostTenant, hostOrganization, host, purpose, group, page); + } + public void Dispose() { Interlocked.Exchange(ref _closed, 1); GC.SuppressFinalize(this); } + } +} diff --git a/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs index f94e3fc9..c94498f0 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs @@ -3,7 +3,11 @@ namespace LearnStack.SharedKernel.Permissions; -public enum OperationPolicyKind { PublicRead = 1, AccountRead = 2, Protected = 3, FiniteTrusted = 4, NativeSessionAdmission = 5, OwnMembershipRead = 6, InvitationEntry = 7, OwnFieldConsentGrant = 8, OwnConsentEntry = 9 } +public enum OperationPolicyKind +{ + PublicRead = 1, AccountRead = 2, Protected = 3, FiniteTrusted = 4, NativeSessionAdmission = 5, OwnMembershipRead = 6, InvitationEntry = 7, OwnFieldConsentGrant = 8, OwnConsentEntry = 9, + OwnDataRequest = 10, OwnDataRequestEntry = 11 +} public enum OperationReadScope { Scoped = 0, Tenant = 1 } /// Definition composition is separate from stored grants and operation admission. @@ -111,6 +115,20 @@ public static OperationPolicy ForOwnFieldConsentGrant(string id) => public static OperationPolicy ForOwnConsentEntry(string id) => new(typeof(TRequest), id, OperationPolicyKind.OwnConsentEntry, null, OperationReadScope.Scoped, [], false); + /// + /// The subject's own data request through a live session: an Active Membership of the actor in exactly the + /// announced group (ADR-0106 § 4). It carries no assignable key and grants no administration authority. + /// + public static OperationPolicy ForOwnDataRequest(string id) => + new(typeof(TRequest), id, OperationPolicyKind.OwnDataRequest, null, OperationReadScope.Scoped, [], false); + + /// + /// The retained own scope of ADR-0106 § 9: admitted only by the subject's own data-request scope witness, so it + /// also serves a Suspended person and a person whose Membership is gone. It carries no assignable key. + /// + public static OperationPolicy ForOwnDataRequestEntry(string id) => + new(typeof(TRequest), id, OperationPolicyKind.OwnDataRequestEntry, null, OperationReadScope.Scoped, [], false); + public static OperationPolicy ForProtected(string id, PermissionDefinition permission, OperationReadScope readScope = OperationReadScope.Scoped, bool requiresOrglessWrite = false, bool requiresOrganization = false) => ForProtected(id, [new OperationPolicyClause([permission], readScope)], requiresOrglessWrite, requiresOrganization); diff --git a/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs b/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs index 14eb29d7..9d9f7e03 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs @@ -9,7 +9,8 @@ public enum ProtectedOperationOutcome { Unavailable = 0, NotCovered = 1, Forbidd public sealed class ProtectedOperationDecision { private ProtectedOperationDecision(OperationInvocation invocation, ProtectedOperationOutcome outcome, - ImmutableArray membershipIds, ImmutableArray roleIds, OperationPolicyClause? matchedClause, OperationReadWitness? readWitness, InvitationEntryScopeWitness? invitationWitness, ConsentSubjectScopeWitness? consentWitness) + ImmutableArray membershipIds, ImmutableArray roleIds, OperationPolicyClause? matchedClause, OperationReadWitness? readWitness, InvitationEntryScopeWitness? invitationWitness, ConsentSubjectScopeWitness? consentWitness, + OwnDataRequestScopeWitness? dataRequestWitness) { Invocation = invocation; Outcome = outcome; @@ -19,6 +20,7 @@ private ProtectedOperationDecision(OperationInvocation invocation, ProtectedOper ReadWitness = readWitness; InvitationWitness = invitationWitness; ConsentWitness = consentWitness; + DataRequestWitness = dataRequestWitness; } public OperationInvocation Invocation { get; } @@ -29,7 +31,9 @@ private ProtectedOperationDecision(OperationInvocation invocation, ProtectedOper public OperationReadWitness? ReadWitness { get; } public InvitationEntryScopeWitness? InvitationWitness { get; } public ConsentSubjectScopeWitness? ConsentWitness { get; } - public bool IsActive => Invocation.IsActive && (InvitationWitness?.IsActive ?? true) && (ConsentWitness?.IsActive ?? true); + public OwnDataRequestScopeWitness? DataRequestWitness { get; } + public bool IsActive => Invocation.IsActive && (InvitationWitness?.IsActive ?? true) && (ConsentWitness?.IsActive ?? true) + && (DataRequestWitness?.IsActive ?? true); public override string ToString() => nameof(ProtectedOperationDecision); #pragma warning disable CA1034 // Only the enumerated Identity evaluator derives the decision source. @@ -39,14 +43,15 @@ public abstract class MintingSource : OperationReadWitness.MintingSource protected static ProtectedOperationDecision ForDecision(OperationInvocation invocation, AuthorizationCandidate candidate, ProtectedOperationOutcome outcome, IEnumerable? membershipIds = null, IEnumerable? roleIds = null, OperationPolicyClause? matchedClause = null, InvitationEntryScopeWitness? invitationWitness = null, - ConsentSubjectScopeWitness? consentWitness = null) + ConsentSubjectScopeWitness? consentWitness = null, OwnDataRequestScopeWitness? dataRequestWitness = null) { ArgumentNullException.ThrowIfNull(invocation); ArgumentNullException.ThrowIfNull(candidate); if (!Enum.IsDefined(outcome) || !ReferenceEquals(invocation.Candidate, candidate) || invocation.Policy.Kind is not (OperationPolicyKind.AccountRead or OperationPolicyKind.Protected or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead or OperationPolicyKind.InvitationEntry - or OperationPolicyKind.OwnFieldConsentGrant or OperationPolicyKind.OwnConsentEntry)) + or OperationPolicyKind.OwnFieldConsentGrant or OperationPolicyKind.OwnConsentEntry + or OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry)) throw new ArgumentException("Protected operation decision provenance is invalid."); var members = Snapshot(membershipIds, 2); var roles = Snapshot(roleIds, 8); @@ -60,8 +65,14 @@ or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembersh && (consentWitness is not { IsActive: true } || !ReferenceEquals(consentWitness.Invocation, invocation)) : consentWitness is not null) throw new InvalidOperationException("Consent operation requires its exact subject witness."); + if (invocation.Policy.Kind == OperationPolicyKind.OwnDataRequestEntry + ? !members.IsEmpty || !roles.IsEmpty || outcome == ProtectedOperationOutcome.Allowed + && (dataRequestWitness is not { IsActive: true } || !ReferenceEquals(dataRequestWitness.Invocation, invocation)) + : dataRequestWitness is not null) + throw new InvalidOperationException("Own data request entry requires its exact subject witness."); if (outcome == ProtectedOperationOutcome.Allowed && (!invocation.IsActive || !candidate.IsActive - || invocation.Policy.Kind is not (OperationPolicyKind.InvitationEntry or OperationPolicyKind.OwnConsentEntry) && members.IsEmpty)) + || invocation.Policy.Kind is not (OperationPolicyKind.InvitationEntry or OperationPolicyKind.OwnConsentEntry + or OperationPolicyKind.OwnDataRequestEntry) && members.IsEmpty)) throw new InvalidOperationException("Protected operation admission has no active membership witness."); if (outcome == ProtectedOperationOutcome.Allowed && invocation.Policy.Kind == OperationPolicyKind.Protected) { @@ -73,7 +84,7 @@ or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembersh throw new ArgumentException("Protected operation clause is incompatible with its outcome."); var read = matchedClause?.ReadScope == OperationReadScope.Tenant ? ForTenantRead(invocation, candidate, matchedClause) : null; - return new(invocation, outcome, members, roles, matchedClause, read, invitationWitness, consentWitness); + return new(invocation, outcome, members, roles, matchedClause, read, invitationWitness, consentWitness, dataRequestWitness); } private static ImmutableArray Snapshot(IEnumerable? values, int maximum) diff --git a/backend/src/LearnStack.SharedKernel/Persistence/IOwnDataRequestUnitOfWork.cs b/backend/src/LearnStack.SharedKernel/Persistence/IOwnDataRequestUnitOfWork.cs new file mode 100644 index 00000000..af19fd5f --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Persistence/IOwnDataRequestUnitOfWork.cs @@ -0,0 +1,15 @@ +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.SharedKernel.Persistence; + +/// +/// The retained own data-request scope's one physical owner (ADR-0106 § 9): it opens a fresh transaction in +/// the witness's mode and announces exactly the witness's group, never a joined, tenant-wide or retargeted one. +/// +public interface IOwnDataRequestUnitOfWork +{ + Task BeginOwnDataRequestTransactionAsync(OwnDataRequestScopeWitness witness, + ITenantContext context, CancellationToken cancellationToken = default); + bool IsOwnDataRequestOwner(OwnDataRequestScopeWitness witness); +} diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs b/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs index 1eadec53..da96f7cc 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs @@ -171,6 +171,26 @@ public static Result CreateForConsentSubjectScope(TenantId hostTe TenantContextOrigin.HostAndConsentSubjectScope, correlationId, new HostScope(hostTenant, hostOrganization))); } + /// + /// Pure scope reconciliation for the retained own data-request scope (ADR-0106 § 9). Only the separate + /// verified-subject witness supplies authority; this factory enforces the independently known host ceiling: + /// a selected group lies in the host tenant and, on an organization host, is exactly that organization's group. + /// Without a selection (the list purpose) the context is the host's own scope. + /// + public static Result CreateForOwnDataRequestScope(TenantId hostTenant, OrganizationId? hostOrganization, + UserId actor, LearnStack.SharedKernel.DataProtection.DataRequestScopeGroup? selected, string? correlationId) + { + if (!StronglyTypedId.IsAssigned(hostTenant) || hostTenant == TenantId.PlatformSentinel + || !StronglyTypedId.IsAssigned(actor) || actor == UserId.SystemActor + || !StronglyTypedId.IsAssignedWhenPresent(hostOrganization) + || selected is not null && (selected.TenantId != hostTenant + || !StronglyTypedId.IsAssignedWhenPresent(selected.OrganizationId) + || hostOrganization is { } branch && selected.OrganizationId != branch)) + return Result.Fail(Refused); + return Result.Ok(new TenantContext(hostTenant, selected is null ? hostOrganization : selected.OrganizationId, actor, + TenantContextOrigin.HostAndOwnDataRequestScope, correlationId, new HostScope(hostTenant, hostOrganization))); + } + /// /// Which signals carried this context — the authority ceiling, decided once. /// diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextOrigin.cs b/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextOrigin.cs index 6b8e65e1..4adb5ae0 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextOrigin.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextOrigin.cs @@ -76,4 +76,11 @@ public enum TenantContextOrigin /// Actual private machine claim; only its tenant outbox production owner. ProviderEventRecipient, + + /// + /// Verified subject and real host bound only to the subject's retained data-request scope groups (ADR-0106 § 9): + /// the groups fn_identity_own_data_request_scopes returned for that subject. It admits only + /// OwnDataRequestEntry operations and supplies no Membership, ordinary native session or tenant-wide read. + /// + HostAndOwnDataRequestScope, } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs new file mode 100644 index 00000000..073f8f05 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs @@ -0,0 +1,29 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.Contracts.DataRequests; + +/// The two closed modes of fn_identity_own_data_request_scopes. +public enum OwnDataRequestLookupMode { List = 1, Select = 2 } + +/// +/// Preliminary retained-scope observation for the subject of a data request under a supplied host ceiling +/// (ADR-0106 § 9). It returns the groups in the host's tenant (and, on an organization host, only that +/// organization's group) in which the actor holds or held a Membership of any status or has any data request. +/// This is not credential, global-binding or host admission and supplies no tenant authority: the caller +/// supplies an actor it has already normalized from a verified credential, never one taken from a request. +/// +public interface IOwnDataRequestScopeLookup +{ + /// The verified subject. + /// The independently classified real host's tenant. + /// The real host's organization, or for a tenant host. + /// pages the groups in order; proves one exact group. + /// For only: the group to prove. + /// For only: the last group of the previous page. + /// 1–20 for a list, exactly 1 for a selection. + /// The request's cancellation. + Task> LookupAsync(UserId actor, TenantId hostTenant, + OrganizationId? hostOrganization, OwnDataRequestLookupMode mode, DataRequestScopeGroup? selected, + DataRequestScopeGroup? after, int limit, CancellationToken cancellationToken = default); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityOperationAuthorizer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityOperationAuthorizer.cs index 69de26b7..f359e79f 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityOperationAuthorizer.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityOperationAuthorizer.cs @@ -7,7 +7,8 @@ namespace LearnStack.Modules.Identity.Application.Authorization; /// One fresh committed-state evaluation per act; no fact or permission decision cache. public sealed class IdentityOperationAuthorizer(Func reader, IOperationPolicyCatalog catalog, - IEnumerable? invitationSources = null, IEnumerable? consentSources = null) + IEnumerable? invitationSources = null, IEnumerable? consentSources = null, + IEnumerable? dataRequestSources = null) : ProtectedOperationDecision.MintingSource, IProtectedOperationAuthorizer { public async Task AuthorizeAsync(OperationInvocation invocation, OperationPolicy policy, @@ -19,7 +20,8 @@ public async Task AuthorizeAsync(OperationInvocation cancellationToken.ThrowIfCancellationRequested(); if (invocation.Candidate is not { } original || invocation.Policy.Kind is not (OperationPolicyKind.AccountRead or OperationPolicyKind.Protected or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead or OperationPolicyKind.InvitationEntry - or OperationPolicyKind.OwnFieldConsentGrant or OperationPolicyKind.OwnConsentEntry)) + or OperationPolicyKind.OwnFieldConsentGrant or OperationPolicyKind.OwnConsentEntry + or OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry)) throw new ArgumentException("Protected operation invocation provenance is invalid.", nameof(invocation)); if (!ReferenceEquals(original, candidate)) return ForDecision(invocation, original, ProtectedOperationOutcome.NotCovered); @@ -43,6 +45,17 @@ public async Task AuthorizeAsync(OperationInvocation ? ForDecision(invocation, candidate, ProtectedOperationOutcome.Allowed, consentWitness: witnesses[0]) : ForDecision(invocation, candidate, ProtectedOperationOutcome.NotCovered); } + if (policy.Kind == OperationPolicyKind.OwnDataRequestEntry) + { + // ADR-0106 § 9: the retained own scope is the subject's own witness, never a Membership read, so a + // Suspended person and a person whose Membership is gone are served; exactly one live source answers. + var witnesses = (dataRequestSources ?? []).Select(source => source.ForInvocation(invocation)) + .Where(witness => witness is not null).Cast().Take(2).ToArray(); + return witnesses.Length == 1 && witnesses[0].IsActive && ReferenceEquals(witnesses[0].Invocation, invocation) + && witnesses[0].Actor == candidate.Actor && candidate.SourceKind == AuthorizationSourceKind.Http + ? ForDecision(invocation, candidate, ProtectedOperationOutcome.Allowed, dataRequestWitness: witnesses[0]) + : ForDecision(invocation, candidate, ProtectedOperationOutcome.NotCovered); + } var facts = await reader().ReadAsync(candidate, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (!invocation.IsActive || !candidate.IsActive) @@ -63,6 +76,7 @@ private bool Matches(OperationInvocation invocation, OperationPolicy policy, Aut && catalog.TryGet(policy.RequestType, out var registered) && ReferenceEquals(registered, policy) && policy.Kind is OperationPolicyKind.AccountRead or OperationPolicyKind.Protected or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead or OperationPolicyKind.InvitationEntry or OperationPolicyKind.OwnFieldConsentGrant or OperationPolicyKind.OwnConsentEntry + or OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry && invocation.Context.IsResolved && invocation.Context.UserId == candidate.Actor && candidate.Actor != UserId.SystemActor && candidate.TenantId != TenantId.PlatformSentinel && invocation.Actor == candidate.Actor && invocation.TenantId == candidate.TenantId diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityPolicyEvaluation.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityPolicyEvaluation.cs index a0a965c1..602bc2d6 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityPolicyEvaluation.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Authorization/IdentityPolicyEvaluation.cs @@ -8,6 +8,9 @@ namespace LearnStack.Modules.Identity.Application.Authorization; /// Pure scoped-pair assessment; only live, separately confined sources mint authority from its result. internal static class IdentityPolicyEvaluation { + /// The one operation-id family an policy may carry. + internal const string OwnDataRequestPrefix = "identity.data_request."; + internal static IdentityPolicyAssessment Evaluate(OperationPolicy policy, AuthorizationCandidate candidate, IdentityAuthorizationResult facts, IOperationPolicyCatalog catalog) { @@ -30,6 +33,19 @@ internal static IdentityPolicyAssessment Evaluate(OperationPolicy policy, Author [.. own[0].Roles.Select(role => role.RoleId).Distinct()], null) : Refused(ProtectedOperationOutcome.NotCovered); } + if (policy.Kind == OperationPolicyKind.OwnDataRequest) + { + // ADR-0106 § 2 and § 4: the subject's own Active Membership in exactly the announced group, through a live + // session. A tenant-wide Membership does not cover an organization's group, nor the reverse, and no grant + // or role is consulted: the policy confers no administration authority. + if (candidate.SourceKind != AuthorizationSourceKind.Http || !policy.Id.StartsWith(OwnDataRequestPrefix, StringComparison.Ordinal)) + return Refused(ProtectedOperationOutcome.NotCovered); + var own = members.Where(member => member.OrganizationId == candidate.OrganizationId).ToArray(); + return own.Length == 1 + ? new(ProtectedOperationOutcome.Allowed, [own[0].MembershipId], + [.. own[0].Roles.Select(role => role.RoleId).Distinct()], null) + : Refused(ProtectedOperationOutcome.NotCovered); + } if (policy.Kind is OperationPolicyKind.AccountRead or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead) return new(ProtectedOperationOutcome.Allowed, [.. members.Select(member => member.MembershipId)], [.. members.SelectMany(member => member.Roles).Select(role => role.RoleId).Distinct()], null); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Authorization/IdentityAuthorizationRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Authorization/IdentityAuthorizationRegistration.cs index 197736ab..ddd9b4d8 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Authorization/IdentityAuthorizationRegistration.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Authorization/IdentityAuthorizationRegistration.cs @@ -29,7 +29,8 @@ public static IServiceCollection AddIdentityOperationPolicies(this IServiceColle services.TryAddScoped(provider => new IdentityOperationAuthorizer( () => provider.GetRequiredService(), provider.GetRequiredService(), provider.GetServices(), - provider.GetServices())); + provider.GetServices(), + provider.GetServices())); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122140000_add_own_data_request_scopes.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122140000_add_own_data_request_scopes.cs new file mode 100644 index 00000000..4ace5b7a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122140000_add_own_data_request_scopes.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("20261122140000_add_own_data_request_scopes")] +public sealed class add_own_data_request_scopes : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => OwnDataRequestScopeDdl.Install(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0106 § 9), like every recent Identity head: the confined definer and its two owner arms + // are retired by a reviewed forward migration, so a reversal cannot strand the retained own-scope path. + throw new NotSupportedException("The retained own data-request scope requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeDdl.cs new file mode 100644 index 00000000..113fa6ca --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeDdl.cs @@ -0,0 +1,123 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The retained own data-request scope of ADR-0106 § 9: the confined definer +/// fn_identity_own_data_request_scopes and the two owner arms it reads through, one on +/// memberships and one on data_subject_requests (ADR-0107 § 8). +/// +/// +/// +/// The function is modelled on the consent subject's fn_tenancy_own_field_consent_scope: a +/// verified actor the caller normalized from its credential, an independently classified real host as the +/// ceiling, closed list and select modes, at most twenty distinct keys per call ordered by +/// organization (the tenant-wide group first), and a fixed search path, migration ownership and an exact +/// application EXECUTE grant. It returns the scope groups — a tenant and an organization or none — in the host's +/// tenant where the actor holds a Membership of any status (a Revoked tombstone included) or has any data +/// request; on an organization host only that organization's group. It returns no Membership, request, status, +/// profile or provider data, and writes nothing. It refuses, as 23514, any session but the application +/// role, any announced tenant, organization, scope or global identity, any transaction that is not read-only +/// READ COMMITTED, the nil and reserved identifiers, and any argument outside its two modes. +/// +/// +/// The owner arms. Both tables are under forced row security keyed by the tenant announcement, which this +/// pre-context reader deliberately has not made, so the function runs as the NOBYPASSRLS migration owner and +/// each table gains one owner arm, beside its unchanged application arm and unchanged WITH CHECK. Each arm admits +/// exactly the state the function itself requires on entry: the migration owner as the current user (only a +/// definer body runs so), the application role as the session user, no tenant, organization, scope or global +/// identity announcement, and a read-only transaction. No other definer reads these tables in that state: +/// the self-discovery and creation definers require a global identity announcement, the membership guards run +/// in a tenant's write, the provider definers run for their own login role, the consent definer reads only its +/// own table, and no other definer body names data_subject_requests at all — the function census pins +/// every body. A row-visibility arm is not a write path: the arms are read-only by their own predicate, WITH +/// CHECK is unchanged and the mutation guards refuse every role but the application one. +/// +/// +internal static class OwnDataRequestScopeDdl +{ + internal static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + // The Membership policy restates its three existing arms unchanged (the application arm, the provider + // ingress arm and the global self-discovery arm, as ProviderEventStorageDdl last wrote them) and adds the + // fourth; ALTER POLICY ... USING leaves its WITH CHECK as it is. Both owner arms are written out literally + // and identically: they admit exactly the state the function requires on entry. + migration.Sql(""" + ALTER POLICY memberships_isolation ON public.memberships + USING ((tenant_id=NULLIF(current_setting('app.tenant_id',true),'')::uuid + AND (organization_id IS NULL OR organization_id=NULLIF(current_setting('app.organization_id',true),'')::uuid + OR NULLIF(current_setting('app.scope',true),'')='tenant')) + OR (current_user='learnstack_migration' AND session_user='learnstack_identity_ingress' + AND status IN ('Active','Suspended') AND deleted_at IS NULL AND deleted_by IS NULL) + OR (current_user='learnstack_migration' AND status='Active' AND deleted_at IS NULL + AND EXISTS (SELECT FROM public.users u WHERE u.id=public.memberships.user_id + AND u.authority_id::text=NULLIF(current_setting('app.identity_authority_id',true),'') + AND encode(u.subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key',true),'') + AND u.status='Active')) + OR (current_user='learnstack_migration' AND session_user='learnstack_app' + AND NULLIF(current_setting('app.tenant_id',true),'') IS NULL + AND NULLIF(current_setting('app.organization_id',true),'') IS NULL + AND NULLIF(current_setting('app.scope',true),'') IS NULL + AND NULLIF(current_setting('app.identity_authority_id',true),'') IS NULL + AND NULLIF(current_setting('app.identity_subject_key',true),'') IS NULL + AND current_setting('transaction_read_only')='on')); + ALTER POLICY data_subject_requests_isolation ON public.data_subject_requests + USING ((tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid + AND (organization_id IS NULL + OR organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid + OR NULLIF(current_setting('app.scope', true), '') = 'tenant')) + OR (current_user='learnstack_migration' AND session_user='learnstack_app' + AND NULLIF(current_setting('app.tenant_id',true),'') IS NULL + AND NULLIF(current_setting('app.organization_id',true),'') IS NULL + AND NULLIF(current_setting('app.scope',true),'') IS NULL + AND NULLIF(current_setting('app.identity_authority_id',true),'') IS NULL + AND NULLIF(current_setting('app.identity_subject_key',true),'') IS NULL + AND current_setting('transaction_read_only')='on')); + """); + migration.Sql(Function); + } + + private const string Function = """ + CREATE FUNCTION public.fn_identity_own_data_request_scopes(p_actor uuid, p_host_tenant uuid, p_host_organization uuid, + p_mode text, p_organization uuid, p_after_organization uuid, p_limit integer) + RETURNS TABLE (tenant_id uuid, organization_id uuid) + LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path=pg_catalog AS $scopes$ + BEGIN + IF (session_user <> 'learnstack_app' + OR NULLIF(current_setting('app.tenant_id',true),'') IS NOT NULL + OR NULLIF(current_setting('app.organization_id',true),'') IS NOT NULL + OR NULLIF(current_setting('app.scope',true),'') IS NOT NULL + OR NULLIF(current_setting('app.identity_authority_id',true),'') IS NOT NULL + OR NULLIF(current_setting('app.identity_subject_key',true),'') IS NOT NULL + OR current_setting('transaction_read_only') <> 'on' + OR current_setting('transaction_isolation') <> 'read committed' + OR p_actor IS NULL OR p_actor IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000001'::uuid) + OR p_host_tenant IS NULL + OR p_host_tenant IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid) + OR p_host_organization IS NOT DISTINCT FROM '00000000-0000-0000-0000-000000000000'::uuid + OR p_organization IS NOT DISTINCT FROM '00000000-0000-0000-0000-000000000000'::uuid + OR p_mode IS NULL OR p_mode NOT IN ('list','select') + OR p_limit IS NULL OR p_limit NOT BETWEEN 1 AND 20 + OR (p_mode = 'list' AND p_organization IS NOT NULL) + OR (p_mode = 'select' AND (p_after_organization IS NOT NULL OR p_limit <> 1))) IS NOT FALSE + THEN RAISE EXCEPTION 'Own data request scope discovery refused.' USING ERRCODE='23514'; END IF; + -- The tenant-wide group sorts first under the nil key, which is also the list cursor that follows it. + RETURN QUERY SELECT held.group_tenant, held.group_organization + FROM (SELECT m.tenant_id, m.organization_id FROM public.memberships AS m + WHERE m.user_id = p_actor AND m.tenant_id = p_host_tenant + UNION + SELECT r.tenant_id, r.organization_id FROM public.data_subject_requests AS r + WHERE r.subject_user_id = p_actor AND r.tenant_id = p_host_tenant) AS held(group_tenant, group_organization) + WHERE (p_host_organization IS NULL OR held.group_organization = p_host_organization) + AND ((p_mode = 'select' AND held.group_organization IS NOT DISTINCT FROM p_organization) + OR (p_mode = 'list' AND (p_after_organization IS NULL + OR COALESCE(held.group_organization,'00000000-0000-0000-0000-000000000000'::uuid) > p_after_organization))) + ORDER BY COALESCE(held.group_organization,'00000000-0000-0000-0000-000000000000'::uuid) + LIMIT p_limit; + END $scopes$; + ALTER FUNCTION public.fn_identity_own_data_request_scopes(uuid,uuid,uuid,text,uuid,uuid,integer) OWNER TO learnstack_migration; + REVOKE ALL ON FUNCTION public.fn_identity_own_data_request_scopes(uuid,uuid,uuid,text,uuid,uuid,integer) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_own_data_request_scopes(uuid,uuid,uuid,text,uuid,uuid,integer) TO learnstack_app; + """; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs new file mode 100644 index 00000000..7535a76b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs @@ -0,0 +1,118 @@ +using LearnStack.Infrastructure.Email; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// One preliminary fixed-function read of fn_identity_own_data_request_scopes (ADR-0106 § 9), on its own +/// physically read-only owner in a child scope, disposed before any scope observation escapes. Modelled on the +/// consent subject's ConsentSubjectScopeLookup. +/// +public sealed class OwnDataRequestScopeLookup(IServiceScopeFactory scopes, IUnitOfWork ambient) : IOwnDataRequestScopeLookup +{ + public async Task> LookupAsync(UserId actor, TenantId hostTenant, + OrganizationId? hostOrganization, OwnDataRequestLookupMode mode, DataRequestScopeGroup? selected, + DataRequestScopeGroup? after, int limit, CancellationToken cancellationToken = default) + { + if (!StronglyTypedId.IsAssigned(actor) || actor == UserId.SystemActor || actor.Value.Version != 7 + || !StronglyTypedId.IsAssigned(hostTenant) || hostTenant == TenantId.PlatformSentinel || hostTenant.Value.Version != 7 + || !StronglyTypedId.IsAssignedWhenPresent(hostOrganization) + || (hostOrganization is { } hostOrg && hostOrg.Value.Version != 7) || !Enum.IsDefined(mode) + || limit is < 1 or > OwnDataRequestScopeWitness.MaximumPage + || !WithinHost(selected, hostTenant) || !WithinHost(after, hostTenant) + || (mode == OwnDataRequestLookupMode.List && selected is not null) + || (mode == OwnDataRequestLookupMode.Select && (selected is null || after is not null || limit != 1))) + throw new ArgumentException("Own data request scope lookup input refused."); + + if (ambient.HasActiveTransaction || ambient.IsRollbackOnly) + throw new InfrastructureException("Own data request scope lookup unavailable."); + try + { + IReadOnlyList observed; + await using (var childScope = scopes.CreateAsyncScope()) + { + var child = childScope.ServiceProvider.GetRequiredService(); + if (child.HasActiveTransaction || child.IsRollbackOnly) + throw new InfrastructureException("Own data request scope lookup unavailable."); + await using var owner = await child.BeginTransactionAsync(TransactionMode.ReadOnly, cancellationToken); + if (!owner.IsOwner || child is IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true }) + throw new InfrastructureException("Own data request scope lookup unavailable."); + await RequirePrivacyAsync(child, cancellationToken); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, organization_id + FROM public.fn_identity_own_data_request_scopes(@actor,@tenant,@host_organization,@mode,@organization,@after,@limit) + """, (NpgsqlConnection)child.Connection, (NpgsqlTransaction)child.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("actor", NpgsqlDbType.Uuid, actor.Value); + command.Parameters.AddWithValue("tenant", NpgsqlDbType.Uuid, hostTenant.Value); + command.Parameters.AddWithValue("host_organization", NpgsqlDbType.Uuid, hostOrganization is { } org ? org.Value : DBNull.Value); + command.Parameters.AddWithValue("mode", NpgsqlDbType.Text, mode == OwnDataRequestLookupMode.List ? "list" : "select"); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, + selected?.OrganizationId is { } chosen ? chosen.Value : DBNull.Value); + // The tenant-wide group's list key is nil: it sorts first, so "after it" is every organization's group. + command.Parameters.AddWithValue("after", NpgsqlDbType.Uuid, + after is null ? DBNull.Value : after.OrganizationId is { } cursor ? cursor.Value : Guid.Empty); + command.Parameters.AddWithValue("limit", NpgsqlDbType.Integer, limit); + observed = await ReadAsync(command, hostTenant, hostOrganization, mode, selected, after, limit, cancellationToken); + await owner.CompleteAsync(cancellationToken); + } + return observed; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or OperationCanceledException + or InvalidCastException or InvalidOperationException or ArgumentException) + { + throw new InfrastructureException("Own data request scope lookup unavailable."); + } + } + + private static bool WithinHost(DataRequestScopeGroup? group, TenantId hostTenant) => group is null + || (group.TenantId == hostTenant && (group.OrganizationId is not { } organization || organization.Value.Version == 7)); + + private static async Task RequirePrivacyAsync(IUnitOfWork owner, CancellationToken cancellationToken) + { + try { await new InvitationEmailDatabasePrivacy(owner).RequireAsync(cancellationToken); } + catch (InvalidOperationException) + { + cancellationToken.ThrowIfCancellationRequested(); + throw new InfrastructureException("Own data request database privacy unavailable."); + } + } + + /// + /// Re-checks every row the function returned against the same host ceiling, order, page and selection, so a + /// function that drifted can never widen what the caller observes. + /// + private static async Task> ReadAsync(NpgsqlCommand command, + TenantId hostTenant, OrganizationId? hostOrganization, OwnDataRequestLookupMode mode, DataRequestScopeGroup? selected, + DataRequestScopeGroup? after, int limit, CancellationToken cancellationToken) + { + var result = new List(limit); + Guid? previous = after is null ? null : after.OrganizationId?.Value ?? Guid.Empty; + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + if (result.Count == limit || reader.IsDBNull(0)) RefuseObservation(); + var tenant = reader.GetGuid(0); + Guid? organization = reader.IsDBNull(1) ? null : reader.GetGuid(1); + var key = organization ?? Guid.Empty; + if (tenant != hostTenant.Value + || (organization is { } branch && (branch == Guid.Empty || branch.Version != 7)) + || (hostOrganization is { } host && organization != host.Value) + || (previous is { } anchor && key.CompareTo(anchor) <= 0) + || (mode == OwnDataRequestLookupMode.Select && organization != selected!.OrganizationId?.Value)) RefuseObservation(); + result.Add(new DataRequestScopeGroup(hostTenant, organization is { } org ? OrganizationId.From(org) : null)); + previous = key; + } + return result.AsReadOnly(); + } + + private static void RefuseObservation() => throw new InfrastructureException("Own data request scope observation refused."); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 0cf7c202..97dba08a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -386,7 +386,8 @@ instruction.Operand is MethodReference target EvidenceCallers(census, errors, callerIndex, InvocationContext, "get_CurrentDecision", CurrentDecisionBorrowers); EvidenceCallers(census, errors, callerIndex, PolicyOwner, "get_CurrentDecision", [("LearnStack.Application.Persistence.TransactionExecutionCoordinator", "ExecuteFrameAsync", 1), - (PolicyOwner, "get_CurrentInvitationWitness", 1), (PolicyOwner, "get_CurrentConsentWitness", 1)]); + (PolicyOwner, "get_CurrentInvitationWitness", 1), (PolicyOwner, "get_CurrentConsentWitness", 1), + (PolicyOwner, "get_CurrentDataRequestWitness", 1)]); EvidenceCallers(census, errors, callerIndex, "LearnStack.SharedKernel.Audit.IAuthorizationRefusalReporter", "ReportRecheck", [(RoleAuthorization, "ReportRecheck", 1), (MemberAuthorization, "ReportRecheck", 1), (TenancyAuthorization, "RecheckAsync", 1), (ReceiptAuthorization, "RecheckAsync", 1), (ReadAuthorization, "RecheckAsync", 1), (InvitationAuthorization, "RecheckAsync", 1), (FederationAuthorization, "RecheckAsync", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (CustomFieldAdmission, "RecheckAsync", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index e39fd8a3..c2a8508d 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -27,6 +27,8 @@ public sealed partial class OutboxDispatchConventionTests private const string LifecycleInvitationWitness = "LearnStack.SharedKernel.Identity.InvitationEntryScopeWitness"; private const string LifecycleConsentWitness = "LearnStack.SharedKernel.Identity.ConsentSubjectScopeWitness"; private const string LifecycleConsentLookup = "LearnStack.Modules.Tenancy.Infrastructure.Persistence.ConsentSubjectScopeLookup"; + private const string LifecycleDataRequestWitness = "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness"; + private const string LifecycleDataRequestLookup = "LearnStack.Modules.Identity.Infrastructure.Persistence.OwnDataRequestScopeLookup"; private const string LifecycleInvitationLookup = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEntryLookup"; private const string LifecycleReadWitness = "LearnStack.SharedKernel.Permissions.OperationReadWitness"; private const string LifecycleGlobalPrepared = DeliveryCoordinator + "/PreparedGlobalIdentityOwner"; @@ -254,7 +256,7 @@ public void Integration_delivery_lifecycle_census_rejects_typed_helper_async_del var readAnnouncements = OwnedBodies(census).SelectMany(item => item.Body.Body.Instructions) .Where(instruction => instruction.Operand is MethodReference target && IntegrationLifecycleCapability(target, types) is "unit.announce-wide" or "owned-unit.announce").ToArray(); - readAnnouncements.Should().HaveCount(5, "the common owner, two fixed public overloads and both entry owners use their exact announcement paths"); + readAnnouncements.Should().HaveCount(6, "the common owner, two fixed public overloads and the three entry owners use their exact announcement paths"); foreach (var announcement in readAnnouncements) { AssertMutation(census, "a missing actual operation read announcement path", () => @@ -270,10 +272,10 @@ public void Integration_delivery_lifecycle_census_rejects_typed_helper_async_del .Where(pair => pair.instruction.Operand is MethodReference target && target.DeclaringType.FullName == LifecycleAdapter && target.Name == "SetTenantContextCoreAsync" && pair.index >= 3) - .SelectMany(pair => new[] { instructions[pair.index - (item.Owner.Name == "BeginConsentSubjectTransactionAsync" ? 3 : 2)], - instructions[pair.index - 1] }); + .SelectMany(pair => CoreWitnessArguments(instructions, pair.index) is { } slots + ? slots.Select(slot => instructions[slot]) : []); }).ToArray(); - coreForwardingArguments.Should().HaveCount(8, "each of four exact callers supplies both closed entry witness arguments"); + coreForwardingArguments.Should().HaveCount(15, "each of five exact callers supplies its three closed entry witness arguments"); foreach (var argument in coreForwardingArguments) AssertMutation(census, "an altered entry witness forwarded to the tenant core", () => ReplaceInstruction(argument, argument.OpCode == OpCodes.Ldnull ? OpCodes.Ldc_I4_0 : OpCodes.Ldnull, null!), @@ -369,7 +371,8 @@ private static SortedSet IntegrationLifecycleOffenders(ProductionCensus var core = adapter.Methods.Where(method => method.Name == "SetTenantContextCoreAsync").ToArray(); if (core.Length != 1 || !core[0].IsPrivate || core[0].IsStatic || core[0].HasGenericParameters || core[0].ReturnType.FullName != LifecycleTask || !ParametersMatch(core[0], - ["LearnStack.SharedKernel.Tenancy.ITenantContext", LifecycleReadWitness, "System.Boolean", BoundaryCancellation, LifecycleInvitationWitness, LifecycleConsentWitness])) + ["LearnStack.SharedKernel.Tenancy.ITenantContext", LifecycleReadWitness, "System.Boolean", BoundaryCancellation, LifecycleInvitationWitness, LifecycleConsentWitness, + LifecycleDataRequestWitness])) offenders.Add("The ordinary tenant setter retains one private witness-aware core"); // The two ordinary setters may not manufacture either entry witness. Each // entry owner forwards only its own captured witness to the private core. @@ -382,20 +385,20 @@ private static SortedSet IntegrationLifecycleOffenders(ProductionCensus || target.Name != "SetTenantContextCoreAsync") continue; var invitationOwner = item.Owner.Name == "BeginInvitationEntryTransactionAsync"; var consentOwner = item.Owner.Name == "BeginConsentSubjectTransactionAsync"; - // Loading an async captured field also loads the state-machine receiver; - // the consent field is last, so its receiver separates the two arguments. - var invitationIndex = index - (consentOwner ? 3 : 2); - if (invitationIndex < 0) { offenders.Add("Tenant context core witness arguments are missing"); continue; } - var invitation = instructions[invitationIndex]; - var consent = instructions[index - 1]; + var dataRequestOwner = item.Owner.Name == "BeginOwnDataRequestTransactionAsync"; + // Loading an async captured field also loads the state-machine receiver, so each + // captured witness argument is two instructions and each absent one is one. + if (CoreWitnessArguments(instructions, index) is not { } slots) + { offenders.Add("Tenant context core witness arguments are missing"); continue; } bool CapturedWitness(int position, string type) => position > 0 && instructions[position - 1].OpCode == OpCodes.Ldarg_0 && instructions[position].OpCode == OpCodes.Ldfld && instructions[position].Operand is FieldReference field && field.Name == "witness" && field.FieldType.FullName == type && field.DeclaringType.FullName == item.Body.DeclaringType.FullName && item.Owner.Parameters.Count(parameter => parameter.Name == "witness" && parameter.ParameterType.FullName == type) == 1; - if (!(invitationOwner ? CapturedWitness(invitationIndex, LifecycleInvitationWitness) : invitation.OpCode == OpCodes.Ldnull) - || !(consentOwner ? CapturedWitness(index - 1, LifecycleConsentWitness) : consent.OpCode == OpCodes.Ldnull)) + if (!(invitationOwner ? CapturedWitness(slots[0], LifecycleInvitationWitness) : instructions[slots[0]].OpCode == OpCodes.Ldnull) + || !(consentOwner ? CapturedWitness(slots[1], LifecycleConsentWitness) : instructions[slots[1]].OpCode == OpCodes.Ldnull) + || !(dataRequestOwner ? CapturedWitness(slots[2], LifecycleDataRequestWitness) : instructions[slots[2]].OpCode == OpCodes.Ldnull)) offenders.Add("Tenant context core must receive only the exact entry owner's witness: " + MethodId(item.Owner)); } } @@ -501,7 +504,8 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( ["unit.begin-mode"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteCoreAsync"), Owner(DeliveryApplication, DeliveryPrepared, "CreateAsync"), Owner(InfrastructureAssembly, LifecycleAdapter, "BeginTransactionAsync", [BoundaryCancellation]), Owner(LifecycleIdentityAssembly, LifecycleInvitationLookup, "LookupAsync"), - Owner("LearnStack.Modules.Tenancy.Infrastructure", LifecycleConsentLookup, "LookupAsync")], + Owner("LearnStack.Modules.Tenancy.Infrastructure", LifecycleConsentLookup, "LookupAsync"), + Owner(LifecycleIdentityAssembly, LifecycleDataRequestLookup, "LookupAsync")], ["unit.commit"] = [Owner(InfrastructureAssembly, LifecycleFrame, "CompleteAsync")], ["unit.rollback"] = [], ["unit.announce"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), @@ -512,7 +516,8 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(InfrastructureAssembly, LifecycleAdapter, "SetTenantContextAsync", ["LearnStack.SharedKernel.Tenancy.ITenantContext", LifecycleReadWitness, BoundaryCancellation]), Owner(InfrastructureAssembly, LifecycleAdapter, "BeginInvitationEntryTransactionAsync"), - Owner(InfrastructureAssembly, LifecycleAdapter, "BeginConsentSubjectTransactionAsync")], + Owner(InfrastructureAssembly, LifecycleAdapter, "BeginConsentSubjectTransactionAsync"), + Owner(InfrastructureAssembly, LifecycleAdapter, "BeginOwnDataRequestTransactionAsync")], ["scope.complete"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync"), Owner(DeliveryApplication, LifecycleGlobalPrepared, "CompleteExistingAsync"), Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "GlobalIdentityBindingService", "ResolveExistingAsync"), @@ -520,6 +525,7 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "GlobalIdentityBindingService", "ReadScopesAsync"), Owner(LifecycleIdentityAssembly, LifecycleInvitationLookup, "LookupAsync"), Owner("LearnStack.Modules.Tenancy.Infrastructure", LifecycleConsentLookup, "LookupAsync"), + Owner(LifecycleIdentityAssembly, LifecycleDataRequestLookup, "LookupAsync"), Owner("LearnStack.Modules.Tenancy.Infrastructure", "LearnStack.Modules.Tenancy.Infrastructure.Persistence.PreContextSelfDiscoveryScopeReader", "ReadAsync")], ["scope.fail"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(DeliveryApplication, DeliveryPrepared, "CreateAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync"), @@ -617,13 +623,32 @@ string Owner(string assembly, string typeName, string name, string[]? parameters } } + /// + /// The instruction index of each of the core's three trailing entry-witness arguments — invitation, consent, + /// own data request, in declaration order — read backwards from the call. An absent witness is one + /// ldnull; a captured one is the state-machine receiver and its field load, so it spans two. + /// + private static int[]? CoreWitnessArguments(Instruction[] instructions, int call) + { + var slots = new int[3]; + var position = call - 1; + for (var slot = slots.Length - 1; slot >= 0; slot--) + { + if (position < 0) return null; + slots[slot] = position; + position -= instructions[position].OpCode == OpCodes.Ldfld ? 2 : 1; + } + return slots; + } + private static string? IntegrationLifecycleCapability(MethodReference target, Dictionary<(string Assembly, string Type), TypeDefinition> types) { var name = target.Name[(target.Name.LastIndexOf('.') + 1)..]; var cancellation = ParametersMatch(target, [BoundaryCancellation]); if (target.DeclaringType.FullName == LifecycleAdapter && name == "SetTenantContextCoreAsync") - return ParametersMatch(target, ["LearnStack.SharedKernel.Tenancy.ITenantContext", LifecycleReadWitness, "System.Boolean", BoundaryCancellation, LifecycleInvitationWitness, LifecycleConsentWitness]) + return ParametersMatch(target, ["LearnStack.SharedKernel.Tenancy.ITenantContext", LifecycleReadWitness, "System.Boolean", BoundaryCancellation, LifecycleInvitationWitness, LifecycleConsentWitness, + LifecycleDataRequestWitness]) && target.ReturnType.FullName == LifecycleTask ? "owned-unit.announce" : "invalid-owned-unit-announce"; if (types.TryGetValue((InfrastructureAssembly, LifecycleFrame), out var frame) && SameType(target.DeclaringType, frame) && name == "FailOwnedAsync") diff --git a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs index 737a7374..fb4d1147 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs @@ -300,7 +300,7 @@ private static List Offenders(Census census) Exact(Decision, ".ctor", [(Decision + "/MintingSource", "ForDecision", 1)]); Exact(Witness, ".ctor", [(Witness + "/MintingSource", "ForTenantRead", 1)]); Exact(Invocation + "/MintingSource", "ForInvocation", [(Coordinator, "ExecuteAsync", 1)]); - Exact(Decision + "/MintingSource", "ForDecision", [(Evaluator, "AuthorizeAsync", 10), + Exact(Decision + "/MintingSource", "ForDecision", [(Evaluator, "AuthorizeAsync", 12), (RoleEvaluator, "RecheckAsync", 2), (MemberEvaluator, "RecheckAsync", 2)]); Exact(Witness + "/MintingSource", "ForTenantRead", [(Decision + "/MintingSource", "ForDecision", 1)]); Exact(Permissions + "IProtectedOperationAuthorizer", "AuthorizeAsync", [(Coordinator, "ExecuteAsync", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs new file mode 100644 index 00000000..80abaded --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs @@ -0,0 +1,145 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0106 § 9: the retained own data-request scope is the consent subject's model applied to data requests. These +/// rules pin its closed owners — the one definer caller, the one physical owner, the witness's private construction +/// and binding callers — and the fact that, until the native retained-entry operations land with their endpoints, +/// nothing mints the witness and no policy carries either new kind. +/// +public sealed class OwnDataRequestScopeConventionTests +{ + private const string Witness = "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness"; + private const string Unit = "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork"; + private const string Lookup = "LearnStack.Modules.Identity.Infrastructure.Persistence.OwnDataRequestScopeLookup"; + + [Fact] + public void Own_data_request_witness_owner_and_lookup_have_closed_shapes() + { + var types = ProductionAssemblies.All().SelectMany(assembly => assembly.GetTypes()).ToArray(); + types.Where(type => !type.IsAbstract && typeof(OwnDataRequestScopeWitness.MintingSource).IsAssignableFrom(type)) + .Should().BeEmpty("the HTTP source that captures the verified subject lands with the native retained-entry endpoints"); + types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestScopeSource).IsAssignableFrom(type)) + .Should().BeEmpty("no source may answer before the minting source exists"); + types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestUnitOfWork).IsAssignableFrom(type)) + .Should().Equal(typeof(NpgsqlUnitOfWork)); + types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestScopeLookup).IsAssignableFrom(type)) + .Select(type => type.FullName).Should().Equal(Lookup); + typeof(OwnDataRequestScopeWitness).IsSealed.Should().BeTrue(); + typeof(OwnDataRequestScopeWitness).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Should().ContainSingle().Which.IsPrivate.Should().BeTrue(); + typeof(OwnDataRequestScopeWitness).GetProperties().Should().OnlyContain(property => property.SetMethod == null); + typeof(OwnDataRequestScopeWitness).GetProperty(nameof(OwnDataRequestScopeWitness.SubjectKey))! + .GetCustomAttributes().Select(attribute => attribute.GetType().Name).Should().Contain("PiiSensitiveAttribute"); + Enum.GetNames().Should().Equal("List", "Create", "Read", "Cancel", "Ticket", "Chunk"); + Enum.IsDefined(TenantContextOrigin.HostAndOwnDataRequestScope).Should().BeTrue(); + new[] { OperationPolicyKind.OwnDataRequest, OperationPolicyKind.OwnDataRequestEntry } + .Select(kind => (int)kind).Should().Equal(10, 11); + } + + [Fact] + public void Own_data_request_witness_callers_are_closed_and_detect_an_extra_minter_or_binding_caller() + { + var modules = ProductionAssemblies.All().Select(assembly => ModuleDefinition.ReadModule(assembly.Location)).ToArray(); + try + { + string[] Callers(string targetType, string member) => modules.SelectMany(module => module.Types) + .SelectMany(Flatten).Where(type => !type.Name.Contains('<', StringComparison.Ordinal) + && !type.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "CompilerGeneratedAttribute")) + .SelectMany(type => Il.Methods(type).Where(method => method.Definition.HasBody) + .SelectMany(method => method.Definition.Body.Instructions.Where(instruction => instruction.Operand is MethodReference target + && target.DeclaringType.FullName == targetType && target.Name == member) + .Select(_ => type.FullName + "." + method.DeclaredAs))).Distinct().ToArray(); + Callers(Witness + "/MintingSource", "Capture").Should().BeEmpty(); + Callers(Witness, ".ctor").Should().Equal(Witness + "/MintingSource.Capture"); + Callers(Witness, "TryBindTo").Should().Equal(Unit + ".SetTenantContextCoreAsync"); + Callers(Witness, "IsBoundTo").Should().BeEquivalentTo(Unit + ".SetTenantContextCoreAsync", + Unit + ".ValidateOperationReadScope", Unit + ".IsOwnDataRequestOwner"); + Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "BeginOwnDataRequestTransactionAsync") + .Should().Equal("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteCoreAsync"); + Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "IsOwnDataRequestOwner") + .Should().Equal("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteFrameAsync"); + Callers("LearnStack.SharedKernel.Tenancy.TenantContextFactory", "CreateForOwnDataRequestScope") + .Should().BeEmpty("only the native retained-entry resolver may build this context, and it lands with its endpoints"); + Callers("LearnStack.Modules.Identity.Application.Contracts.DataRequests.IOwnDataRequestScopeLookup", "LookupAsync") + .Should().BeEmpty("only the native retained-entry source may observe the retained groups"); + + var module = modules.Single(item => item.Assembly.Name.Name == "LearnStack.SharedKernel"); + var witnessType = module.Types.SelectMany(Flatten).Single(type => type.FullName == Witness); + var minter = witnessType.NestedTypes.Single(type => type.Name == "MintingSource"); + TypeDefinition[] Minters() => modules.SelectMany(item => item.Types).SelectMany(Flatten) + .Where(type => !type.IsAbstract && type.BaseType?.FullName == minter.FullName).ToArray(); + Minters().Should().BeEmpty(); + var rogueMinter = new TypeDefinition("ReviewProbe", "DataRequestMinter", Mono.Cecil.TypeAttributes.Class, minter); + module.Types.Add(rogueMinter); + Minters().Select(type => type.FullName).Should().Equal("ReviewProbe.DataRequestMinter"); + module.Types.Remove(rogueMinter); + Minters().Should().BeEmpty(); + var target = witnessType.Methods.Single(method => method.Name == "TryBindTo"); + var probe = new TypeDefinition("ReviewProbe", "DataRequestBinding", Mono.Cecil.TypeAttributes.Class, module.TypeSystem.Object); + var method = new MethodDefinition("Bind", Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, target)); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + probe.Methods.Add(method); module.Types.Add(probe); + Callers(Witness, "TryBindTo").Should().Contain("ReviewProbe.DataRequestBinding.Bind"); + module.Types.Remove(probe); + Callers(Witness, "TryBindTo").Should().Equal(Unit + ".SetTenantContextCoreAsync"); + } + finally { foreach (var module in modules) module.Dispose(); } + } + + /// The definer has one caller outside its migration: the confined lookup. Its literal is the census. + [Fact] + public void Only_the_confined_lookup_calls_the_retained_scope_definer() + { + const string Function = "fn_identity_own_data_request_scopes"; + SourceScan.FilesContaining(SourceScan.SourceRoot, Function, except: null).Order(StringComparer.Ordinal) + .Should().Equal("Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeDdl.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs"); + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OwnDataRequestScopeLookup.cs")); + var root = CSharpSyntaxTree.ParseText(source).GetRoot(); + var statements = root.DescendantNodes().OfType() + .Where(literal => literal.Token.ValueText.Contains(Function, StringComparison.Ordinal)) + .Select(literal => string.Join(" ", literal.Token.ValueText.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))) + .ToArray(); + statements.Should().Equal(new[] { "SELECT tenant_id, organization_id FROM public.fn_identity_own_data_request_scopes(" + + "@actor,@tenant,@host_organization,@mode,@organization,@after,@limit)" }, + "the one statement reads the function's two result columns and nothing else"); + } + + [Fact] + public void Retained_scope_lookup_is_scoped_in_the_api_composition_and_nowhere_else() + { + static string[] Registrations(string source) => CSharpSyntaxTree.ParseText(source).GetRoot() + .DescendantNodes().OfType() + .Select(call => call.Expression is MemberAccessExpressionSyntax { Name: GenericNameSyntax generic } ? generic : null) + .Where(generic => generic is not null && generic.Identifier.ValueText.Contains("Add", StringComparison.Ordinal) + && generic.TypeArgumentList.Arguments.Any(argument => argument.ToString().EndsWith("IOwnDataRequestScopeLookup", StringComparison.Ordinal) + || argument.ToString().EndsWith("IOwnDataRequestScopeSource", StringComparison.Ordinal))) + .Select(generic => generic!.Identifier.ValueText + "<" + string.Join(",", generic.TypeArgumentList.Arguments + .Select(argument => argument.ToString().Split('.')[^1])) + ">") + .ToArray(); + var api = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Api/Composition/PersistenceCompositionExtensions.cs")); + Registrations(api).Should().Equal("TryAddScoped"); + var dirty = api + "\nclass Rogue { void Add(dynamic services) { services.AddSingleton(); } }"; + Registrations(dirty).Should().HaveCount(2, "an extra witness source must remain visible to the registration census"); + var seeder = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Tools.Seeder/SeedComposition.cs")); + Registrations(seeder).Should().BeEmpty("the seeder dispatches no data request"); + } + + private static IEnumerable Flatten(TypeDefinition type) => new[] { type }.Concat(type.NestedTypes.SelectMany(Flatten)); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs index 362ea69e..46b32272 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs @@ -27,7 +27,7 @@ private static string WithoutOperationReadAnnouncement(string relative, string s if (core.Length != 1 || !core[0].Modifiers.Any(SyntaxKind.PrivateKeyword) || !core[0].Modifiers.Any(SyntaxKind.AsyncKeyword) || core[0].Modifiers.Any(SyntaxKind.StaticKeyword) || !SyntaxFactory.AreEquivalent(core[0].ParameterList, SyntaxFactory.ParseParameterList( - "(ITenantContext context, OperationReadWitness? readWitness, bool tenantWideRead, CancellationToken cancellationToken, InvitationEntryScopeWitness? invitationWitness = null, ConsentSubjectScopeWitness? consentWitness = null)")) + "(ITenantContext context, OperationReadWitness? readWitness, bool tenantWideRead, CancellationToken cancellationToken, InvitationEntryScopeWitness? invitationWitness = null, ConsentSubjectScopeWitness? consentWitness = null, OwnDataRequestScopeWitness? dataRequestWitness = null)")) || forwarders.Length != 2 || forwarders.Count(method => Forwarder(method, "(ITenantContext context, CancellationToken cancellationToken = default)", diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs index 9d090183..7296e733 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs @@ -28,7 +28,8 @@ public void HostScope_Is_Constructed_Only_By_The_Factory() [$"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.Create)}", $"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.CreateForConsentSubjectScope)}", $"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.CreateForInvitationOffer)}", - $"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.CreateForNativeScope)}"], + $"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.CreateForNativeScope)}", + $"{typeof(TenantContextFactory).FullName}.{nameof(TenantContextFactory.CreateForOwnDataRequestScope)}"], "Fix: only the reconciliation factory may create host provenance; scan must see its real call"); } @@ -49,7 +50,7 @@ public void Host_scope_guard_detects_mutable_public_shape_and_a_second_construct module.Types.Add(probe); HostScopeConstructors(module).Should().Contain("ReviewProbe.SecondProducer.Build"); module.Types.Remove(probe); - HostScopeConstructors(module).Should().HaveCount(4); + HostScopeConstructors(module).Should().HaveCount(5); } private static IEnumerable HostScopeShapeViolations(Type type) @@ -140,7 +141,8 @@ public void TenantContext_Is_Constructed_Only_By_The_Factory() [$"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.Create)}", $"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.CreateForNativeScope)}", $"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.CreateForInvitationOffer)}", - $"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.CreateForConsentSubjectScope)}"], + $"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.CreateForConsentSubjectScope)}", + $"{nameof(TenantContextFactory)}.{nameof(TenantContextFactory.CreateForOwnDataRequestScope)}"], "a second member handing back a TenantContext is a second entry point, " + "whatever it delegates to"); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index 5eaaea3c..79971132 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -407,9 +407,11 @@ 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(38, "the closed set includes three provider definers, one target transition guard, the federation connection guard, the operator resolver, the identity authority key guard, " - + "and the four data-request guards, their chunk completeness check and three canonical parent-scope checks"); - functions.Count(function => function.Definer).Should().Be(16); + functions.Should().HaveCount(39, "the closed set includes three provider definers, one target transition guard, the federation connection guard, the operator resolver, the identity authority key guard, " + + "the four data-request guards, their chunk completeness check, three canonical parent-scope checks and the retained own data-request scope definer"); + functions.Count(function => function.Definer).Should().Be(17); + functions.Single(function => function.Name == "fn_identity_own_data_request_scopes").Signature + .Should().Be("public.fn_identity_own_data_request_scopes(uuid,uuid,uuid,text,uuid,uuid,integer)"); 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)); @@ -424,6 +426,7 @@ private static CanonicalFunction[] CompiledFunctions() ? ProviderForbiddenFunctionBody() : function.Name.StartsWith("fn_invitation_", StringComparison.Ordinal) ? EntryForbiddenFunctionBody() : function.Name is "fn_identity_creation_attempt_admission" or "fn_identity_self_membership_scopes" or "fn_identity_invitation_entry" or "fn_tenancy_own_field_consent_scope" + or "fn_identity_own_data_request_scopes" ? EntryForbiddenFunctionBody() : globalNames.Contains(function.Name) ? ForbiddenFunctionBody() : ContextualForbiddenFunctionBody(); forbidden.IsMatch(function.Body).Should().BeFalse( diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.EntryPolicyControls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.EntryPolicyControls.cs index 91331e7b..d5cd189b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.EntryPolicyControls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.EntryPolicyControls.cs @@ -28,6 +28,15 @@ AND encode(u.subject_key,'hex') = NULLIF(current_setting('app.identity_subject_k current_user = 'learnstack_migration' AND session_user = 'learnstack_identity_ingress' AND status IN ('Active','Suspended') AND deleted_at IS NULL AND deleted_by IS NULL """; + private const string ExpectedDataRequestOwnerUsing = """ + current_user = 'learnstack_migration' AND session_user = 'learnstack_app' + AND NULLIF(current_setting('app.tenant_id',true),'') IS NULL + AND NULLIF(current_setting('app.organization_id',true),'') IS NULL + AND NULLIF(current_setting('app.scope',true),'') IS NULL + AND NULLIF(current_setting('app.identity_authority_id',true),'') IS NULL + AND NULLIF(current_setting('app.identity_subject_key',true),'') IS NULL + AND current_setting('transaction_read_only') = 'on' + """; private const string ExpectedMemberCheck = """ 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) @@ -76,7 +85,7 @@ public async Task Applied_membership_owner_policy_detects_committed_predicate_fa try { await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) - await ExecuteAsync(owner, null, $"ALTER POLICY memberships_isolation ON public.memberships USING (({ExpectedMemberAppUsing}) OR ({ExpectedProviderOwnerUsing}) OR ({ownerArm}))"); + await ExecuteAsync(owner, null, $"ALTER POLICY memberships_isolation ON public.memberships USING (({ExpectedMemberAppUsing}) OR ({ExpectedProviderOwnerUsing}) OR ({ownerArm}) OR ({ExpectedDataRequestOwnerUsing}))"); // The inspector and behavioral readers open independent physical // connections after the ALTER POLICY has committed. @@ -140,7 +149,8 @@ await ExecuteAsync(owner, null, $""" CREATE TEMP TABLE entry_policy_expected ( tenant_id uuid,organization_id uuid,user_id uuid,status text,deleted_at timestamptz,deleted_by uuid); CREATE POLICY entry_policy_expected ON entry_policy_expected - USING (({ExpectedMemberAppUsing}) OR ({ExpectedProviderOwnerUsing}) OR ({expectedOwner})) WITH CHECK ({ExpectedMemberCheck}); + USING (({ExpectedMemberAppUsing}) OR ({ExpectedProviderOwnerUsing}) OR ({expectedOwner}) OR ({ExpectedDataRequestOwnerUsing})) + WITH CHECK ({ExpectedMemberCheck}); """); var expected = await ReadMemberPolicySnapshotAsync(owner, "pg_temp.entry_policy_expected", "entry_policy_expected"); var violations = new List(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs index fa9b1d23..708811a8 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_seventy_tables_and_exactly_sixteen_confined_definers() + public async Task Applied_census_has_seventy_tables_and_exactly_seventeen_confined_definers() { await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); await SchemaTableClasses.AssertCompleteAsync(owner); @@ -66,7 +66,8 @@ public async Task Applied_census_has_seventy_tables_and_exactly_sixteen_confined """, 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_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_own_data_request_scopes", "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 +77,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(16); + """)).Should().Be(17); (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 a2aaf53b..c2b47b5e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs @@ -16,14 +16,16 @@ 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_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_own_data_request_scopes", "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_operator_resolve_user", "fn_identity_self_membership_scopes", + "fn_identity_invitation_entry", "fn_identity_operator_resolve_user", "fn_identity_own_data_request_scopes", + "fn_identity_self_membership_scopes", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", }; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 1437192b..e8da4cb3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -104,9 +104,9 @@ 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(30L, + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(31L, "current Identity also installs three provider definers, one target transition guard, the federation connection guard, the operator subject resolver, the authority key guard, " - + "and the four data-request guards with their chunk completeness check"); + + "the four data-request guards with their chunk completeness check, and the retained own data-request scope definer"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); @@ -223,6 +223,8 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() authorityRebind.Should().Throw().WithMessage("The issuer-rebind storage requires a reviewed forward migration."); Action federationProjection = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.grant_platform_federation_projection().DownOperations; federationProjection.Should().Throw().WithMessage("The platform federation projection grant requires a reviewed forward migration."); + Action dataRequests = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_data_subject_requests().DownOperations; + dataRequests.Should().Throw().WithMessage("Data request 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)[] @@ -231,8 +233,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, "20261120160000_grant_platform_federation_projection", IdentityReversibleHead, - "20261122013001_add_data_subject_requests", "Data request storage requires a reviewed forward migration."), + (identity, "20261122013001_add_data_subject_requests", IdentityReversibleHead, + "20261122140000_add_own_data_request_scopes", "The retained own data-request scope 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/OwnDataRequestScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs new file mode 100644 index 00000000..6096b0e0 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs @@ -0,0 +1,531 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using NpgsqlTypes; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0106 § 9 and ADR-0107 § 8: fn_identity_own_data_request_scopes and its two owner arms, connected as +/// learnstack_app (and, for the refusals, as every other role). The function returns exactly the subject's own +/// groups in the host's tenant — Memberships of any status and requests — and nothing of another person, tenant or +/// branch; the arms admit only the state the function itself requires. +/// +/// +/// Seeded by : in tenant A, PersonA holds the tenant-wide Membership and one in +/// each organization, with an export request in each of those three groups, and AdminA holds only the tenant-wide +/// administrator Membership; in tenant B, AdminB holds the tenant-wide Membership and PersonB the organization's, each +/// with a request. The tests that change a lifecycle run on their own disposable database. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class OwnDataRequestScopeTests(IdentityMembershipFixture fixture) : IClassFixture +{ + private const string Signature = "public.fn_identity_own_data_request_scopes(uuid,uuid,uuid,text,uuid,uuid,integer)"; + private static readonly (Guid Tenant, Guid? Organization) TenantWideA = (SchemaFixture.TenantA, null); + private static readonly (Guid Tenant, Guid? Organization) BranchA1 = (SchemaFixture.TenantA, SchemaFixture.OrgA1); + private static readonly (Guid Tenant, Guid? Organization) BranchA2 = (SchemaFixture.TenantA, SchemaFixture.OrgA2); + + [Fact] + public async Task The_subject_sees_exactly_their_own_groups_in_the_host_and_nothing_else() + { + var app = fixture.Postgres.AppConnectionString; + (await ListAsync(app, PersonA, SchemaFixture.TenantA, null)).Should().Equal(TenantWideA, BranchA1, BranchA2); + (await ListAsync(app, AdminA, SchemaFixture.TenantA, null)).Should().Equal(TenantWideA); + // An organization host discovers only its own branch, never the tenant-wide group or another branch. + (await ListAsync(app, PersonA, SchemaFixture.TenantA, SchemaFixture.OrgA1)).Should().Equal(BranchA1); + (await ListAsync(app, PersonA, SchemaFixture.TenantA, SchemaFixture.OrgA2)).Should().Equal(BranchA2); + (await ListAsync(app, AdminA, SchemaFixture.TenantA, SchemaFixture.OrgA1)).Should().BeEmpty(); + // Two tenants: the actor argument selects that subject alone, in the host's tenant alone. + (await ListAsync(app, PersonA, SchemaFixture.TenantB, null)).Should().BeEmpty(); + (await ListAsync(app, PersonB, SchemaFixture.TenantA, null)).Should().BeEmpty(); + (await ListAsync(app, PersonB, SchemaFixture.TenantB, null)).Should().Equal((SchemaFixture.TenantB, (Guid?)SchemaFixture.OrgB1)); + (await ListAsync(app, AdminB, SchemaFixture.TenantB, null)).Should().Equal((SchemaFixture.TenantB, (Guid?)null)); + (await ListAsync(app, AdminB, SchemaFixture.TenantB, SchemaFixture.OrgB1)).Should().BeEmpty(); + (await ListAsync(app, Guid.CreateVersion7(), SchemaFixture.TenantA, null)).Should().BeEmpty("an unknown person has no group"); + } + + [Fact] + public async Task List_pages_are_ordered_tenant_wide_first_and_selection_proves_one_exact_group() + { + var app = fixture.Postgres.AppConnectionString; + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "list", null, null, 1)).Should().Equal(TenantWideA); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "list", null, Guid.Empty, 1)).Should().Equal(new[] { BranchA1 }, + "the nil key is the cursor that follows the tenant-wide group"); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "list", null, SchemaFixture.OrgA1, 1)).Should().Equal(BranchA2); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "list", null, SchemaFixture.OrgA2, 20)).Should().BeEmpty(); + + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "select", null, null, 1)).Should().Equal(TenantWideA); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "select", SchemaFixture.OrgA2, null, 1)).Should().Equal(BranchA2); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, SchemaFixture.OrgA1, "select", null, null, 1)).Should().BeEmpty( + "an organization host cannot select the tenant-wide group"); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, SchemaFixture.OrgA1, "select", SchemaFixture.OrgA2, null, 1)).Should().BeEmpty( + "an organization host cannot select another branch"); + (await CallAsync(app, PersonA, SchemaFixture.TenantA, null, "select", SchemaFixture.OrgB1, null, 1)).Should().BeEmpty(); + (await CallAsync(app, AdminA, SchemaFixture.TenantA, null, "select", SchemaFixture.OrgA1, null, 1)).Should().BeEmpty( + "another person's group is not this subject's"); + } + + public static TheoryData Refusals() => new() + { + "read-write", "repeatable-read", "tenant-announced", "organization-announced", "scope-announced", + "identity-announced", "null-actor", "nil-actor", "system-actor", "null-host", "nil-host", "sentinel-host", + "nil-host-organization", "nil-organization", "null-mode", "unknown-mode", "null-limit", "zero-limit", "over-limit", + "list-with-organization", "select-with-after", "select-limit-two", + }; + + [Theory] + [MemberData(nameof(Refusals))] + public async Task Every_state_and_argument_outside_the_two_modes_is_refused(string label) + { + var start = label switch + { + "read-write" => "SET TRANSACTION READ WRITE", + "repeatable-read" => "SET TRANSACTION READ ONLY, ISOLATION LEVEL REPEATABLE READ", + _ => "SET TRANSACTION READ ONLY", + }; + var setup = label switch + { + "tenant-announced" => $"SELECT set_config('app.tenant_id','{SchemaFixture.TenantA:D}',true)", + "organization-announced" => $"SELECT set_config('app.organization_id','{SchemaFixture.OrgA1:D}',true)", + "scope-announced" => "SELECT set_config('app.scope','tenant',true)", + "identity-announced" => $"SELECT set_config('app.identity_authority_id','{Authority.AuthorityId.Value:D}',true)", + _ => null, + }; + Guid? actor = label switch + { + "null-actor" => null, + "nil-actor" => Guid.Empty, + "system-actor" => UserId.SystemActor.Value, + _ => PersonA, + }; + Guid? host = label switch + { + "null-host" => null, + "nil-host" => Guid.Empty, + "sentinel-host" => TenantId.PlatformSentinel.Value, + _ => SchemaFixture.TenantA, + }; + var mode = label switch { "null-mode" => null, "unknown-mode" => "selectall", "select-with-after" or "select-limit-two" => "select", _ => "list" }; + int? limit = label switch { "null-limit" => null, "zero-limit" => 0, "over-limit" => 21, "select-limit-two" => 2, _ => 1 }; + var call = () => CallAsync(fixture.Postgres.AppConnectionString, actor, host, + label == "nil-host-organization" ? Guid.Empty : null, mode, + label switch { "nil-organization" => Guid.Empty, "list-with-organization" => SchemaFixture.OrgA1, _ => null }, + label == "select-with-after" ? SchemaFixture.OrgA1 : null, limit, start, setup); + (await call.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + } + + [Theory] + [InlineData("platform")] + [InlineData("outbox")] + public async Task No_other_role_executes_the_function_or_reads_the_tables_it_reads(string role) + { + var connection = role == "platform" ? fixture.Postgres.PlatformConnectionString : fixture.Postgres.OutboxConnectionString; + var call = () => CallAsync(connection, PersonA, SchemaFixture.TenantA, null, "list", null, null, 20); + (await call.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + await using var other = (NpgsqlConnection)await PostgresFixture.OpenAsync(connection); + var read = () => ScalarAsync(other, null, "SELECT count(*) FROM public.memberships"); + (await read.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + if (role == "outbox") + { + var requests = () => ScalarAsync(other, null, "SELECT count(*) FROM public.data_subject_requests"); + (await requests.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + } + } + + [Fact] + public async Task The_function_acl_is_exactly_the_application_role_and_the_arms_open_nothing_to_a_session() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + (await SchemaQueries.ReadStringsAsync(owner, $""" + SELECT CASE WHEN a.grantee=0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee)::text END || ':' || a.privilege_type + FROM pg_proc p, aclexplode(p.proacl) a + WHERE p.oid='{Signature}'::regprocedure AND a.grantee<>p.proowner ORDER BY 1 + """, null)).Should().Equal("learnstack_app:EXECUTE"); + (await ScalarAsync(owner, null, $"SELECT pg_get_userbyid(proowner)::text FROM pg_proc WHERE oid='{Signature}'::regprocedure")) + .Should().Be("learnstack_migration"); + foreach (var role in new[] { "learnstack_platform", "learnstack_outbox_admin", "learnstack_identity_ingress", "learnstack_identity_rebind" }) + (await ScalarAsync(owner, null, $"SELECT has_function_privilege('{role}','{Signature}','EXECUTE')")) + .Should().BeFalse(role + " has no path to the retained scope"); + + // In exactly the function's own state, but as a session rather than a definer body: both arms stay shut, + // for the application login (current_user is not the owner) and for the owner login (session_user is not + // the application role) alike. + foreach (var connection in new[] { fixture.Postgres.AppConnectionString, fixture.Postgres.MigrationConnectionString }) + { + await using var session = (NpgsqlConnection)await PostgresFixture.OpenAsync(connection); + await using var transaction = await session.BeginTransactionAsync(); + await ExecuteAsync(session, transaction, "SET TRANSACTION READ ONLY"); + (await ScalarAsync(session, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(0); + (await ScalarAsync(session, transaction, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0); + } + } + + /// + /// The arms are state-bound, not caller-bound, so this dirty probe states exactly what they admit: a second + /// owner-run definer sees every Membership and request in the function's own pre-context read-only state and + /// nothing in any other. That breadth is why the definer census pins every body that may run as the owner. + /// + [Fact] + public async Task The_owner_arms_admit_only_the_functions_own_state_and_restore_cleanly() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, """ + CREATE FUNCTION public.own_data_request_arm_probe() RETURNS TABLE (members bigint, requests bigint) + LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog AS $probe$ + SELECT (SELECT count(*) FROM public.memberships), (SELECT count(*) FROM public.data_subject_requests) $probe$; + REVOKE ALL ON FUNCTION public.own_data_request_arm_probe() FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.own_data_request_arm_probe() TO learnstack_app; + """); + async Task<(long Members, long Requests)> ProbeAsync(string start, string? setup) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ExecuteAsync(app, transaction, start); + if (setup is not null) await ExecuteAsync(app, transaction, setup); + await using var command = new NpgsqlCommand("SELECT members, requests FROM public.own_data_request_arm_probe()", app, transaction); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return (reader.GetInt64(0), reader.GetInt64(1)); + } + (await ProbeAsync("SET TRANSACTION READ ONLY", null)).Should().Be((6L, 5L), "the function's own state sees every row it filters"); + (await ProbeAsync("SET TRANSACTION READ WRITE", null)).Should().Be((0L, 0L)); + (await ProbeAsync("SET TRANSACTION READ ONLY", $"SELECT set_config('app.tenant_id','{SchemaFixture.TenantB:D}',true)")) + .Should().Be((1L, 1L), "an announced tenant leaves only the application arm: tenant B's tenant-wide rows"); + (await ProbeAsync("SET TRANSACTION READ ONLY", "SELECT set_config('app.scope','tenant',true)")).Should().Be((0L, 0L)); + (await ProbeAsync("SET TRANSACTION READ ONLY", "SELECT set_config('app.organization_id','" + SchemaFixture.OrgA1.ToString("D") + "',true)")) + .Should().Be((0L, 0L)); + (await ProbeAsync("SET TRANSACTION READ ONLY", "SELECT set_config('app.identity_subject_key',repeat('0',64),true)")) + .Should().Be((0L, 0L)); + } + + /// The policy is the independent oracle, canonicalized by PostgreSQL itself, not loaded from the migration. + [Fact] + public async Task The_request_policy_is_the_canonical_template_plus_exactly_the_one_owner_arm() + { + const string ExpectedAppUsing = """ + tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid + AND (organization_id IS NULL + OR organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid + OR NULLIF(current_setting('app.scope', true), '') = 'tenant') + """; + const string ExpectedOwnerUsing = """ + current_user = 'learnstack_migration' AND session_user = 'learnstack_app' + AND NULLIF(current_setting('app.tenant_id', true), '') IS NULL + AND NULLIF(current_setting('app.organization_id', true), '') IS NULL + AND NULLIF(current_setting('app.scope', true), '') IS NULL + AND NULLIF(current_setting('app.identity_authority_id', true), '') IS NULL + AND NULLIF(current_setting('app.identity_subject_key', true), '') IS NULL + AND current_setting('transaction_read_only') = 'on' + """; + const string ExpectedCheck = """ + 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) + """; + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, $""" + CREATE TEMP TABLE request_policy_expected (tenant_id uuid, organization_id uuid); + CREATE POLICY request_policy_expected ON request_policy_expected + USING (({ExpectedAppUsing}) OR ({ExpectedOwnerUsing})) WITH CHECK ({ExpectedCheck}); + """); + const string Read = """ + SELECT pg_get_expr(polqual,polrelid) || ' | ' || pg_get_expr(polwithcheck,polrelid) || ' | ' || polcmd::text + || ' | ' || polpermissive::text + FROM pg_policy WHERE polrelid=to_regclass(@relation) AND polname=@policy + """; + var expected = await ScalarAsync(owner, null, Read, ("relation", "pg_temp.request_policy_expected"), ("policy", "request_policy_expected")); + var actual = await ScalarAsync(owner, null, Read, ("relation", "public.data_subject_requests"), ("policy", "data_subject_requests_isolation")); + actual.Should().Be(expected); + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT polname::text FROM pg_policy WHERE polrelid='public.data_subject_requests'::regclass ORDER BY polname + """, null)).Should().Equal("data_subject_requests_isolation", "data_subject_requests_org_delete_guard", "data_subject_requests_org_write_guard"); + foreach (var table in new[] { "data_export_artifacts", "data_export_tickets", "data_export_chunks" }) + (await ScalarAsync(owner, null, "SELECT pg_get_expr(polqual,polrelid) FROM pg_policy WHERE polrelid=to_regclass(@relation) AND polname=@policy", + ("relation", "public." + table), ("policy", table + "_isolation"))).Should().NotContain("learnstack_migration", + "only data_subject_requests gains an owner arm; the artifact, ticket and chunk tables keep the bare template"); + } + + [Fact] + public async Task Suspended_and_revoked_memberships_and_a_request_only_group_are_retained() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString)) + { + await SchemaQueries.AssertApplicationRoleAsync(app); + foreach (var (organization, member, status) in new[] + { + (SchemaFixture.OrgA2, BranchMembershipA2, "Suspended"), + (SchemaFixture.OrgA1, BranchMembershipA1, "Revoked"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, organization); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, status == "Revoked" + ? """ + UPDATE public.memberships SET status='Revoked',deleted_at=clock_timestamp(),deleted_by=@actor, + row_version=row_version+1 WHERE id=@member; + SET CONSTRAINTS ALL IMMEDIATE; + """ + : "UPDATE public.memberships SET status='Suspended',row_version=row_version+1 WHERE id=@member; SET CONSTRAINTS ALL IMMEDIATE;", + ("member", member), ("actor", AdminA)); + await transaction.CommitAsync(); + } + } + // A request whose group holds no Membership row: the application guard refuses to write one, so the owner + // writes it with that guard disabled, the way a group could otherwise only be reached by retained evidence. + var requestOnly = Guid.CreateVersion7(); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + { + await using var transaction = await owner.BeginTransactionAsync(); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests DISABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await ScopeAsync(owner, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await ExecuteAsync(owner, transaction, """ + INSERT INTO public.data_subject_requests(id,tenant_id,organization_id,kind,origin,subject_user_id,requester_user_id, + status,membership_snapshot,execute_at,created_at,created_by) + VALUES(@id,@tenant,@organization,'export','self',@subject,@subject,'requested',@snapshot::jsonb,NULL,now(),@subject) + """, ("id", requestOnly), ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), + ("subject", PersonB), ("snapshot", DataRequestSchemaSeed.Snapshot(Guid.CreateVersion7()))); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + (await ListAsync(database.AppConnectionString, PersonA, SchemaFixture.TenantA, null)).Should().Equal(new[] { TenantWideA, BranchA1, BranchA2 }, + "a Revoked tombstone and a Suspended Membership keep their groups"); + (await ListAsync(database.AppConnectionString, PersonB, SchemaFixture.TenantA, null)).Should().Equal(new[] { BranchA1 }, + "a request alone keeps its group"); + (await ListAsync(database.AppConnectionString, PersonB, SchemaFixture.TenantA, SchemaFixture.OrgA2)).Should().BeEmpty(); + (await ListAsync(database.AppConnectionString, AdminA, SchemaFixture.TenantA, null)).Should().Equal(new[] { TenantWideA }, + "another person's request in a group never lends that group to a bystander"); + + } + + [Fact] + public async Task The_confined_lookup_rechecks_the_function_and_runs_on_its_own_read_only_owner() + { + await using var dataSource = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(dataSource); + services.AddScoped(); + services.AddScoped(); + await using var provider = services.BuildServiceProvider(); + await using var scope = provider.CreateAsyncScope(); + var lookup = scope.ServiceProvider.GetRequiredService(); + var ambient = scope.ServiceProvider.GetRequiredService(); + var actor = UserId.From(PersonA); + var tenant = TenantId.From(SchemaFixture.TenantA); + var branch = OrganizationId.From(SchemaFixture.OrgA2); + + var listed = await lookup.LookupAsync(actor, tenant, null, OwnDataRequestLookupMode.List, null, null, 20); + listed.Should().Equal(new DataRequestScopeGroup(tenant, null), new DataRequestScopeGroup(tenant, OrganizationId.From(SchemaFixture.OrgA1)), + new DataRequestScopeGroup(tenant, branch)); + ambient.HasActiveTransaction.Should().BeFalse("the preliminary owner is disposed before any observation escapes"); + (await lookup.LookupAsync(actor, tenant, null, OwnDataRequestLookupMode.List, null, listed[0], 1)) + .Should().Equal(listed[1]); + (await lookup.LookupAsync(actor, tenant, branch, OwnDataRequestLookupMode.Select, new DataRequestScopeGroup(tenant, branch), null, 1)) + .Should().Equal(new DataRequestScopeGroup(tenant, branch)); + (await lookup.LookupAsync(UserId.From(PersonB), tenant, null, OwnDataRequestLookupMode.List, null, null, 20)).Should().BeEmpty(); + + var foreignSelection = () => lookup.LookupAsync(actor, tenant, null, OwnDataRequestLookupMode.Select, + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantB), null), null, 1); + await foreignSelection.Should().ThrowAsync(); + var wideList = () => lookup.LookupAsync(actor, tenant, null, OwnDataRequestLookupMode.List, null, null, 21); + await wideList.Should().ThrowAsync(); + var system = () => lookup.LookupAsync(UserId.SystemActor, tenant, null, OwnDataRequestLookupMode.List, null, null, 20); + await system.Should().ThrowAsync(); + + await using (var frame = await ambient.BeginTransactionAsync(TransactionMode.ReadOnly)) + { + var joined = () => lookup.LookupAsync(actor, tenant, null, OwnDataRequestLookupMode.List, null, null, 20); + await joined.Should().ThrowAsync("the preliminary read never joins an ambient owner"); + await frame.FailAsync(); + } + } + + /// + /// The fifteenth logical tenant setter: the witness the function's result produced announces exactly its group on a + /// fresh physical owner in the witness's mode, and nothing else. Test-only captured provenance; this claims no HTTP + /// credential admission. + /// + [Theory] + [InlineData("read")] + [InlineData("create")] + public async Task The_captured_group_is_announced_on_its_own_fresh_owner(string label) + { + var purpose = label == "read" ? OwnDataRequestPurpose.Read : OwnDataRequestPurpose.Create; + var actor = UserId.From(PersonA); + var tenant = TenantId.From(SchemaFixture.TenantA); + var group = new DataRequestScopeGroup(tenant, OrganizationId.From(SchemaFixture.OrgA2)); + await using var dataSource = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString); + using var owner = new CapturedOwner(purpose, group); + + await using var unit = new NpgsqlUnitOfWork(dataSource, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + await using (var frame = await unit.BeginOwnDataRequestTransactionAsync(owner.Witness, owner.Context)) + { + unit.IsOwnDataRequestOwner(owner.Witness).Should().BeTrue(); + unit.Mode.Should().Be(owner.Witness.Mode); + (await UnitScalarAsync(unit, "SELECT current_setting('transaction_read_only')")).Should().Be(label == "read" ? "on" : "off"); + (await UnitScalarAsync(unit, "SELECT current_setting('app.tenant_id')")).Should().Be(SchemaFixture.TenantA.ToString("D")); + (await UnitScalarAsync(unit, "SELECT current_setting('app.organization_id')")).Should().Be(SchemaFixture.OrgA2.ToString("D")); + (await UnitScalarAsync(unit, "SELECT COALESCE(NULLIF(current_setting('app.scope',true),''),'none')")).Should().Be("none"); + // The canonical policy shows the group's rows and the tenant-wide group's, never a sibling branch or another + // tenant: a handler still filters to the exact group. + (await UnitScalarAsync(unit, "SELECT array_agg(id ORDER BY id) FROM public.data_subject_requests")) + .Should().BeEquivalentTo([DataRequestSchemaSeed.TenantWideA.Request, DataRequestSchemaSeed.BranchA2.Request]); + var nested = () => unit.BeginTransactionAsync(TransactionMode.ReadOnly); + await nested.Should().ThrowAsync(); + unit.IsOwnDataRequestOwner(owner.Witness).Should().BeFalse("a refused join poisons the owner"); + await frame.FailAsync(); + } + unit.IsOwnDataRequestOwner(owner.Witness).Should().BeFalse(); + await using (var fresh = new NpgsqlUnitOfWork(dataSource, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance)) + { + var reuse = () => fresh.BeginOwnDataRequestTransactionAsync(owner.Witness, owner.Context); + await reuse.Should().ThrowAsync("a witness binds to one physical transaction once"); + fresh.IsOwnDataRequestOwner(owner.Witness).Should().BeFalse(); + } + + await using var pooled = await dataSource.OpenConnectionAsync(); + await using var check = new NpgsqlCommand(""" + SELECT NULLIF(current_setting('app.tenant_id',true), '') IS NULL + AND NULLIF(current_setting('app.organization_id',true), '') IS NULL + AND NULLIF(current_setting('app.scope',true), '') IS NULL + """, pooled); + (await check.ExecuteScalarAsync()).Should().Be(true, "a returned pooled connector keeps no group authority"); + } + + [Theory] + [InlineData("http-entry")] + [InlineData("other-context")] + [InlineData("closed-source")] + [InlineData("ambient-owner")] + public async Task The_setter_refuses_any_witness_that_is_not_its_own_fresh_application_owner(string label) + { + var tenant = TenantId.From(SchemaFixture.TenantA); + var group = new DataRequestScopeGroup(tenant, OrganizationId.From(SchemaFixture.OrgA1)); + await using var dataSource = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString); + using var owner = new CapturedOwner(OwnDataRequestPurpose.Read, group, http: label == "http-entry"); + var context = label == "other-context" + ? LearnStack.SharedKernel.Tenancy.TenantContextFactory.CreateForOwnDataRequestScope(tenant, null, UserId.From(PersonA), group, null).Value! + : owner.Context; + if (label == "closed-source") owner.Close(); + await using var unit = new NpgsqlUnitOfWork(dataSource, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + IUnitOfWorkScope? ambient = label == "ambient-owner" ? await unit.BeginTransactionAsync(TransactionMode.ReadOnly) : null; + var begin = () => unit.BeginOwnDataRequestTransactionAsync(owner.Witness, context); + await begin.Should().ThrowAsync(); + unit.IsOwnDataRequestOwner(owner.Witness).Should().BeFalse(); + unit.IsRollbackOnly.Should().BeTrue(); + if (ambient is not null) { await ambient.FailAsync(); await ambient.DisposeAsync(); } + } + + private static async Task UnitScalarAsync(NpgsqlUnitOfWork unit, string sql) + { + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!); + return (T)(await command.ExecuteScalarAsync())!; + } + + private sealed record ReadProbe; + + /// One captured invocation, its context and its witness, built exactly as the source would. + private sealed class CapturedOwner : IDisposable + { + private readonly CandidateSource _candidates; + private readonly InvocationSource _invocations = new(); + private readonly WitnessSource _witnesses = new(); + + public CapturedOwner(OwnDataRequestPurpose purpose, DataRequestScopeGroup group, bool http = false) + { + var actor = UserId.From(PersonA); + Context = LearnStack.SharedKernel.Tenancy.TenantContextFactory.CreateForOwnDataRequestScope(group.TenantId, null, actor, group, null).Value!; + _candidates = new CandidateSource(Context); + var policy = LearnStack.SharedKernel.Permissions.OperationPolicy.ForOwnDataRequestEntry("identity.data_request.read"); + var invocation = _invocations.Open(new ReadProbe(), policy, Context, _candidates.Create(), + http ? LearnStack.SharedKernel.Permissions.OperationEntryKind.Http : LearnStack.SharedKernel.Permissions.OperationEntryKind.Application); + Witness = _witnesses.Capture(invocation, actor, group.TenantId, purpose, group); + } + + public LearnStack.SharedKernel.Tenancy.TenantContext Context { get; } + public OwnDataRequestScopeWitness Witness { get; } + public void Close() => _witnesses.Dispose(); + public void Dispose() { _witnesses.Dispose(); _candidates.Dispose(); } + } + + private sealed class CandidateSource(LearnStack.SharedKernel.Tenancy.TenantContext context) + : LearnStack.SharedKernel.Permissions.AuthorizationCandidate.MintingSource + { + internal LearnStack.SharedKernel.Permissions.AuthorizationCandidate Create() => + ForCandidate(LearnStack.SharedKernel.Permissions.AuthorizationSourceKind.Http, context.UserId!.Value, context.TenantId, context.OrganizationId); + } + + private sealed class InvocationSource : LearnStack.SharedKernel.Permissions.OperationInvocation.MintingSource + { + private LearnStack.SharedKernel.Permissions.OperationInvocation? _current; + internal LearnStack.SharedKernel.Permissions.OperationInvocation Open(object operation, + LearnStack.SharedKernel.Permissions.OperationPolicy policy, LearnStack.SharedKernel.Tenancy.TenantContext context, + LearnStack.SharedKernel.Permissions.AuthorizationCandidate candidate, LearnStack.SharedKernel.Permissions.OperationEntryKind kind) => + _current = ForInvocation(operation, policy, context, candidate, null, CancellationToken.None, kind); + protected override bool IsCurrent(LearnStack.SharedKernel.Permissions.OperationInvocation invocation) => ReferenceEquals(_current, invocation); + } + + private sealed class WitnessSource : OwnDataRequestScopeWitness.MintingSource + { + private static readonly GlobalIdentitySubject Subject = new(Authority.AuthorityId, Authority.Issuer, + "fixture-subject-" + PersonA.ToString("N")); + private readonly object _evidence = new(); + private LearnStack.SharedKernel.Permissions.OperationInvocation? _current; + + internal OwnDataRequestScopeWitness Capture(LearnStack.SharedKernel.Permissions.OperationInvocation invocation, UserId actor, + TenantId tenant, OwnDataRequestPurpose purpose, DataRequestScopeGroup group) + { + _current = invocation; + return Capture(_evidence, invocation, Subject, actor, tenant, null, "data-request-fixture.invalid", purpose, group, null); + } + + protected override bool IsEvidenceCurrent(object evidence, LearnStack.SharedKernel.Permissions.OperationInvocation invocation) => + ReferenceEquals(evidence, _evidence) && ReferenceEquals(invocation, _current); + } + + private static Task<(Guid Tenant, Guid? Organization)[]> ListAsync(string connection, Guid actor, Guid hostTenant, Guid? hostOrganization) => + CallAsync(connection, actor, hostTenant, hostOrganization, "list", null, null, 20); + + internal static async Task<(Guid Tenant, Guid? Organization)[]> CallAsync(string connectionString, Guid? actor, Guid? hostTenant, + Guid? hostOrganization, string? mode, Guid? organization, Guid? after, int? limit, + string start = "SET TRANSACTION READ ONLY", string? setup = null) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await ExecuteAsync(connection, transaction, start); + if (setup is not null) await ExecuteAsync(connection, transaction, setup); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, organization_id + FROM public.fn_identity_own_data_request_scopes(@actor,@tenant,@host_organization,@mode,@organization,@after,@limit) + """, connection, transaction); + command.Parameters.Add(new NpgsqlParameter("actor", NpgsqlDbType.Uuid) { Value = (object?)actor ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("tenant", NpgsqlDbType.Uuid) { Value = (object?)hostTenant ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("host_organization", NpgsqlDbType.Uuid) { Value = (object?)hostOrganization ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("mode", NpgsqlDbType.Text) { Value = (object?)mode ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("organization", NpgsqlDbType.Uuid) { Value = (object?)organization ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("after", NpgsqlDbType.Uuid) { Value = (object?)after ?? DBNull.Value }); + command.Parameters.Add(new NpgsqlParameter("limit", NpgsqlDbType.Integer) { Value = (object?)limit ?? DBNull.Value }); + var rows = new List<(Guid, Guid?)>(); + await using (var reader = await command.ExecuteReaderAsync()) + while (await reader.ReadAsync()) rows.Add((reader.GetGuid(0), reader.IsDBNull(1) ? null : reader.GetGuid(1))); + await transaction.RollbackAsync(); + return [.. rows]; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs new file mode 100644 index 00000000..46b4a5db --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs @@ -0,0 +1,492 @@ +using FluentAssertions; +using LearnStack.Application.Audit; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Application.Authorization; +using LearnStack.Modules.Identity.Application.Contracts.Authorization; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// ADR-0106 § 4 and § 9: is the subject's Active Membership in +/// exactly the announced group through a live session, and is +/// the retained own scope, admitted only by its witness and only under its own origin. Both are driven through the +/// real coordinator and the real Identity evaluator; the reader and the witness source are the only doubles. +/// +public sealed class OwnDataRequestPolicyTests +{ + private static readonly UserId Actor = UserId.From(Guid.CreateVersion7()); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly OrganizationId Branch = OrganizationId.From(Guid.CreateVersion7()); + private static readonly OrganizationId OtherBranch = OrganizationId.From(Guid.CreateVersion7()); + private static readonly Guid Member = Guid.CreateVersion7(); + private static readonly GlobalIdentitySubject Subject = new(IdentityAuthorityId.From(Guid.CreateVersion7()), + "https://data-request.invalid/realms/learnstack", "data-request-subject"); + + // ---- OwnDataRequest: the live-session kind ------------------------------------------------------------ + + [Theory] + [InlineData("branch-member-in-branch", "allowed")] + [InlineData("tenant-member-in-tenant", "allowed")] + [InlineData("tenant-member-in-branch", "lockey_not_found")] + [InlineData("no-active-membership", "lockey_not_found")] + [InlineData("foreign-branch-fact", "lockey_dependency_unavailable")] + public async Task Own_data_request_needs_an_active_membership_in_exactly_the_announced_group(string label, string outcome) + { + var (context, member) = label switch + { + "branch-member-in-branch" => (Branch, (OrganizationId?)Branch), + "tenant-member-in-tenant" => ((OrganizationId?)null, (OrganizationId?)null), + "tenant-member-in-branch" => (Branch, (OrganizationId?)null), + "foreign-branch-fact" => (Branch, OtherBranch), + _ => (Branch, (OrganizationId?)Branch), + }; + using var rig = new Rig(TenantContextOrigin.HostAndClaim, context); + // The committed reader returns only Active, undeleted Memberships covering the announced scope: a Suspended or + // Revoked person, or one with no Membership at all, reaches the evaluator as NotCovered. + rig.Reader.ReadAsync(Arg.Any(), Arg.Any()).Returns(label == "no-active-membership" + ? new IdentityAuthorizationResult(IdentityAuthorizationOutcome.NotCovered, Actor, Tenant, context, []) + : new IdentityAuthorizationResult(IdentityAuthorizationOutcome.Covered, Actor, Tenant, context, + [new AuthorizationMembershipFacts(Member, member, [])])); + + var result = await rig.RunAsync(new CreateProbe()); + + if (outcome == "allowed") + { + result.IsSuccess.Should().BeTrue(); + rig.Decision!.MembershipIds.Should().Equal(Member); + rig.Decision.DataRequestWitness.Should().BeNull(); + } + else if (outcome == "lockey_not_found") + { + result.IsFailure.Should().BeTrue(); + result.Error.Should().BeSameAs(TenantContextFactory.Refused, + "a person outside the group is not covered: the not-found shape, never a forbidden that names the group"); + } + else + { + // The committed reader never returns a Membership outside the announced scope; one that does is an + // inconsistent read, which fails closed as unavailable rather than as a coverage answer. + result.Error!.Message.Key.Should().Be(outcome); + } + } + + [Fact] + public async Task Own_data_request_storage_failure_is_unavailable_not_a_refusal() + { + using var rig = new Rig(TenantContextOrigin.HostAndClaim, Branch); + rig.Reader.ReadAsync(Arg.Any(), Arg.Any()) + .Returns(new IdentityAuthorizationResult(IdentityAuthorizationOutcome.Unavailable, Actor, Tenant, Branch, [])); + + var result = await rig.RunAsync(new CreateProbe()); + + result.Error!.Message.Key.Should().Be("lockey_dependency_unavailable"); + } + + [Theory] + [InlineData("retained-origin")] + [InlineData("seed-candidate")] + [InlineData("foreign-policy-id")] + public async Task Own_data_request_refuses_the_retained_origin_a_non_http_candidate_and_a_foreign_operation(string label) + { + using var rig = new Rig(label == "retained-origin" ? TenantContextOrigin.HostAndOwnDataRequestScope : TenantContextOrigin.HostAndClaim, + Branch, candidateKind: label == "seed-candidate" ? AuthorizationSourceKind.Seed : AuthorizationSourceKind.Http); + rig.Reader.ReadAsync(Arg.Any(), Arg.Any()) + .Returns(new IdentityAuthorizationResult(IdentityAuthorizationOutcome.Covered, Actor, Tenant, Branch, + [new AuthorizationMembershipFacts(Member, Branch, [])])); + + var result = label == "foreign-policy-id" ? await rig.RunAsync(new ForeignOwnProbe()) : await rig.RunAsync(new CreateProbe()); + + result.IsFailure.Should().BeTrue(); + result.Error.Should().BeSameAs(TenantContextFactory.Refused); + if (label == "retained-origin") + await rig.Reader.DidNotReceive().ReadAsync(Arg.Any(), Arg.Any()); + } + + // ---- OwnDataRequestEntry: the retained own scope ------------------------------------------------------ + + [Theory] + [InlineData("tenant-wide-group")] + [InlineData("organization-group")] + public async Task Entry_is_admitted_by_its_witness_alone_without_reading_a_membership(string label) + { + var group = new DataRequestScopeGroup(Tenant, label == "organization-group" ? Branch : null); + using var rig = new Rig(TenantContextOrigin.HostAndOwnDataRequestScope, group.OrganizationId, withWitness: true); + rig.Witnesses.Purpose = OwnDataRequestPurpose.Read; + rig.Witnesses.Group = group; + + var result = await rig.RunAsync(new ReadProbe()); + + result.IsSuccess.Should().BeTrue("a Suspended person and one whose Membership is gone are served by the witness"); + rig.Decision!.DataRequestWitness.Should().NotBeNull(); + rig.Decision.MembershipIds.Should().BeEmpty("the retained scope supplies no Membership authority"); + rig.Decision.DataRequestWitness!.Group.Should().Be(group); + await rig.Reader.DidNotReceive().ReadAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("no-source")] + [InlineData("closed-source")] + [InlineData("two-sources")] + [InlineData("live-session-origin")] + [InlineData("seed-candidate")] + public async Task Entry_without_exactly_one_live_witness_in_its_own_origin_is_not_found(string label) + { + using var rig = new Rig(label == "live-session-origin" ? TenantContextOrigin.HostAndClaim : TenantContextOrigin.HostAndOwnDataRequestScope, + Branch, withWitness: label != "no-source", twoSources: label == "two-sources", + candidateKind: label == "seed-candidate" ? AuthorizationSourceKind.Seed : AuthorizationSourceKind.Http); + rig.Witnesses.Purpose = OwnDataRequestPurpose.Read; + rig.Witnesses.Group = new DataRequestScopeGroup(Tenant, Branch); + if (label == "closed-source") rig.Witnesses.Dispose(); + + var result = await rig.RunAsync(new ReadProbe()); + + result.IsFailure.Should().BeTrue(); + result.Error.Should().BeSameAs(TenantContextFactory.Refused); + await rig.Reader.DidNotReceive().ReadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task The_entry_witness_never_reaches_a_live_session_operation() + { + using var rig = new Rig(TenantContextOrigin.HostAndOwnDataRequestScope, Branch, withWitness: true); + rig.Witnesses.Purpose = OwnDataRequestPurpose.Create; + rig.Witnesses.Group = new DataRequestScopeGroup(Tenant, Branch); + + var result = await rig.RunAsync(new CreateProbe()); + + result.Error.Should().BeSameAs(TenantContextFactory.Refused, + "an OwnDataRequest operation needs an ordinary authenticated context, which the retained origin is not"); + rig.Witnesses.Captured.Should().Be(0); + } + + // ---- The origin's ceiling ------------------------------------------------------------------------------ + + /// + /// The retained-entry path reaches nothing outside its own set: its origin admits only an + /// request, and the consent origin never admits one. + /// + [Theory] + [InlineData("retained-origin-entry-kind", true)] + [InlineData("retained-origin-live-kind", false)] + [InlineData("retained-origin-consent-kind", false)] + [InlineData("retained-origin-unregistered", false)] + [InlineData("consent-origin-entry-kind", false)] + [InlineData("live-origin-entry-kind", true)] + public async Task The_retained_origin_reaches_only_its_own_policy_kind(string label, bool reaches) + { + var catalog = new OperationPolicyCatalog([new ProbePolicies()]); + ITenantContext context = label switch + { + "consent-origin-entry-kind" => TenantContextFactory.CreateForConsentSubjectScope(Tenant, null, Actor, null, null).Value!, + "live-origin-entry-kind" => TenantContextFactory.Create(new TenantResolutionAttempt + { + HostTenantId = Tenant, + ClaimTenantId = Tenant, + HasValidatedPrincipal = true, + UserId = Actor, + MembershipCovers = true, + }).Value!, + _ => TenantContextFactory.CreateForOwnDataRequestScope(Tenant, null, Actor, new DataRequestScopeGroup(Tenant, null), null).Value!, + }; + var called = label switch + { + "retained-origin-live-kind" => await ReachesAsync(context, catalog), + "retained-origin-consent-kind" => await ReachesAsync(context, catalog), + "retained-origin-unregistered" => await ReachesAsync(context, catalog), + _ => await ReachesAsync(context, catalog), + }; + // An ordinary authenticated origin reaches an unmarked request at this gate; authorization at step 5 then + // refuses the entry kind outside its origin (Entry_without_exactly_one_live_witness_in_its_own_origin_is_not_found). + called.Should().Be(reaches); + } + + private static async Task ReachesAsync(ITenantContext context, IOperationPolicyCatalog catalog) + where TRequest : MediatR.IRequest>, new() + { + var behavior = new LearnStack.Application.Pipeline.TenantContextBehavior>(context, catalog); + var called = false; + await behavior.Handle(new TRequest(), () => { called = true; return Task.FromResult(Result.Ok(None.Value)); }, CancellationToken.None); + return called; + } + + // ---- Witness, factory and decision shapes ------------------------------------------------------------- + + [Theory] + [InlineData("list", "ReadOnly")] + [InlineData("read", "ReadOnly")] + [InlineData("create", "ReadWrite")] + [InlineData("cancel", "ReadWrite")] + [InlineData("ticket", "ReadWrite")] + [InlineData("chunk", "ReadWrite")] + public void Each_purpose_has_its_fixed_transaction_mode_and_shape(string label, string mode) + { + var purpose = Enum.Parse(label, ignoreCase: true); + var group = purpose == OwnDataRequestPurpose.List ? null : new DataRequestScopeGroup(Tenant, Branch); + var witness = WitnessFor(purpose, group, purpose == OwnDataRequestPurpose.List ? Page() : null); + witness.Mode.Should().Be(Enum.Parse(mode)); + witness.TenantId.Should().Be(Tenant); + witness.OrganizationId.Should().Be(purpose == OwnDataRequestPurpose.List ? null : Branch); + witness.ToString().Should().Be(nameof(OwnDataRequestScopeWitness), "no subject or scope reaches a log through the witness"); + } + + [Theory] + [InlineData("list-without-page")] + [InlineData("list-with-group")] + [InlineData("read-without-group")] + [InlineData("read-with-page")] + [InlineData("foreign-tenant-group")] + [InlineData("other-branch-on-branch-host")] + [InlineData("tenant-wide-group-on-branch-host")] + [InlineData("page-outside-host")] + [InlineData("page-duplicate")] + [InlineData("page-too-long")] + [InlineData("system-actor")] + [InlineData("sentinel-host")] + [InlineData("blank-host")] + public void The_witness_refuses_every_shape_outside_its_host_and_purpose(string label) + { + var branchHost = label is "other-branch-on-branch-host" or "tenant-wide-group-on-branch-host" or "page-outside-host"; + var foreign = TenantId.From(Guid.CreateVersion7()); + var (purpose, group, page) = label switch + { + "list-without-page" => (OwnDataRequestPurpose.List, (DataRequestScopeGroup?)null, (OwnDataRequestScopePage?)null), + "list-with-group" => (OwnDataRequestPurpose.List, new DataRequestScopeGroup(Tenant, null), Page()), + "read-without-group" => (OwnDataRequestPurpose.Read, null, null), + "read-with-page" => (OwnDataRequestPurpose.Read, new DataRequestScopeGroup(Tenant, null), Page()), + "foreign-tenant-group" => (OwnDataRequestPurpose.Read, new DataRequestScopeGroup(foreign, null), null), + "other-branch-on-branch-host" => (OwnDataRequestPurpose.Read, new DataRequestScopeGroup(Tenant, OtherBranch), null), + "tenant-wide-group-on-branch-host" => (OwnDataRequestPurpose.Read, new DataRequestScopeGroup(Tenant, null), null), + "page-outside-host" => (OwnDataRequestPurpose.List, null, Page(new DataRequestScopeGroup(Tenant, OtherBranch))), + "page-duplicate" => (OwnDataRequestPurpose.List, null, Page(new DataRequestScopeGroup(Tenant, null), new DataRequestScopeGroup(Tenant, null))), + "page-too-long" => (OwnDataRequestPurpose.List, null, new OwnDataRequestScopePage([.. Enumerable.Range(0, 21) + .Select(_ => new DataRequestScopeGroup(Tenant, OrganizationId.From(Guid.CreateVersion7())))], null)), + _ => (OwnDataRequestPurpose.Read, new DataRequestScopeGroup(Tenant, null), null), + }; + var actor = label == "system-actor" ? UserId.SystemActor : Actor; + var host = label == "sentinel-host" ? TenantId.PlatformSentinel : Tenant; + var hostName = label == "blank-host" ? " " : "school.invalid"; + var build = () => WitnessFor(purpose, group, page, branchHost ? Branch : null, actor, host, hostName); + build.Should().Throw(); + } + + [Theory] + [InlineData("tenant-host-tenant-wide")] + [InlineData("tenant-host-organization")] + [InlineData("branch-host-branch")] + [InlineData("tenant-host-list")] + public void The_factory_admits_the_retained_group_within_its_host(string label) + { + var (hostOrganization, selected) = label switch + { + "tenant-host-tenant-wide" => ((OrganizationId?)null, new DataRequestScopeGroup(Tenant, null)), + "tenant-host-organization" => (null, new DataRequestScopeGroup(Tenant, Branch)), + "branch-host-branch" => (Branch, new DataRequestScopeGroup(Tenant, Branch)), + _ => ((OrganizationId?)null, (DataRequestScopeGroup?)null), + }; + var context = TenantContextFactory.CreateForOwnDataRequestScope(Tenant, hostOrganization, Actor, selected, "trace").Value!; + context.Origin.Should().Be(TenantContextOrigin.HostAndOwnDataRequestScope); + context.TenantId.Should().Be(Tenant); + context.OrganizationId.Should().Be(selected is null ? hostOrganization : selected.OrganizationId); + context.UserId.Should().Be(Actor); + context.HostScope!.TenantId.Should().Be(Tenant); + context.HostScope.OrganizationId.Should().Be(hostOrganization); + } + + [Theory] + [InlineData("foreign-tenant")] + [InlineData("other-branch")] + [InlineData("tenant-wide-on-branch-host")] + [InlineData("system-actor")] + [InlineData("sentinel-host")] + public void The_factory_refuses_a_group_outside_its_host_and_a_non_person(string label) + { + var refused = label switch + { + "foreign-tenant" => TenantContextFactory.CreateForOwnDataRequestScope(Tenant, null, Actor, + new DataRequestScopeGroup(TenantId.From(Guid.CreateVersion7()), null), null), + "other-branch" => TenantContextFactory.CreateForOwnDataRequestScope(Tenant, Branch, Actor, + new DataRequestScopeGroup(Tenant, OtherBranch), null), + "tenant-wide-on-branch-host" => TenantContextFactory.CreateForOwnDataRequestScope(Tenant, Branch, Actor, + new DataRequestScopeGroup(Tenant, null), null), + "system-actor" => TenantContextFactory.CreateForOwnDataRequestScope(Tenant, null, UserId.SystemActor, null, null), + _ => TenantContextFactory.CreateForOwnDataRequestScope(TenantId.PlatformSentinel, null, Actor, null, null), + }; + refused.IsFailure.Should().BeTrue(); + refused.Error.Should().BeSameAs(TenantContextFactory.Refused); + } + + [Fact] + public void Policies_of_both_kinds_carry_no_permission_and_no_alternatives() + { + foreach (var policy in new[] { OperationPolicy.ForOwnDataRequest("identity.data_request.create"), + OperationPolicy.ForOwnDataRequestEntry("identity.data_request.read") }) + { + policy.RequiredPermission.Should().BeNull(); + policy.Alternatives.Should().BeEmpty(); + policy.AllowedSources.Should().BeEmpty(); + policy.ReadScope.Should().Be(OperationReadScope.Scoped); + policy.RequiresOrglessWrite.Should().BeFalse(); + } + } + + // ---- Doubles ------------------------------------------------------------------------------------------ + + private static OwnDataRequestScopePage Page(params DataRequestScopeGroup[] groups) => + new(groups.Length == 0 ? [new DataRequestScopeGroup(Tenant, null)] : [.. groups], null); + + private static OwnDataRequestScopeWitness WitnessFor(OwnDataRequestPurpose purpose, DataRequestScopeGroup? group, + OwnDataRequestScopePage? page, OrganizationId? hostOrganization = null, UserId? actor = null, TenantId? host = null, + string hostName = "school.invalid") + { + var context = Substitute.For(); + context.IsResolved.Returns(true); + context.TenantId.Returns(Tenant); + context.UserId.Returns(Actor); + context.Origin.Returns(TenantContextOrigin.HostAndOwnDataRequestScope); + var invocations = new InvocationSource(); + var invocation = invocations.Open(new ReadProbe(), OperationPolicy.ForOwnDataRequestEntry("identity.data_request.read"), context); + using var source = new WitnessSource + { + Purpose = purpose, + Group = group, + Page = page, + HostOrganization = hostOrganization, + Actor = actor ?? Actor, + HostTenant = host ?? Tenant, + HostName = hostName + }; + return source.ForInvocation(invocation)!; + } + + private sealed record CreateProbe : MediatR.IRequest>; + private sealed record ReadProbe : MediatR.IRequest>; + private sealed record ForeignOwnProbe : MediatR.IRequest>; + private sealed record ConsentProbe : MediatR.IRequest>; + private sealed record UnregisteredProbe : MediatR.IRequest>; + + private sealed class ProbePolicies : IOperationPolicySource + { + public IEnumerable Definitions => []; + public IEnumerable Policies => + [ + OperationPolicy.ForOwnDataRequest("identity.data_request.create"), + OperationPolicy.ForOwnDataRequestEntry("identity.data_request.read"), + OperationPolicy.ForOwnDataRequest("identity.membership.read_own_probe"), + OperationPolicy.ForOwnConsentEntry("tenancy.membership_field_consent.probe"), + ]; + } + + private sealed class Rig : IDisposable + { + private readonly OperationAuthorizationCoordinator _coordinator; + private readonly CandidateSource _candidates; + private readonly WitnessSource _second = new(); + + public Rig(TenantContextOrigin origin, OrganizationId? organization, bool withWitness = false, bool twoSources = false, + AuthorizationSourceKind candidateKind = AuthorizationSourceKind.Http) + { + Context = origin == TenantContextOrigin.HostAndOwnDataRequestScope + ? TenantContextFactory.CreateForOwnDataRequestScope(Tenant, null, Actor, + new DataRequestScopeGroup(Tenant, organization), null).Value! + : LiveContext(origin, organization); + _candidates = new CandidateSource(Context, candidateKind); + var catalog = new OperationPolicyCatalog([new ProbePolicies()]); + _second.Group = new DataRequestScopeGroup(Tenant, organization); + IOwnDataRequestScopeSource[] sources = !withWitness ? [] : twoSources ? [Witnesses, _second] : [Witnesses]; + var authorizer = new IdentityOperationAuthorizer(() => Reader, catalog, dataRequestSources: sources); + var clock = Substitute.For(); + clock.UtcNow.Returns(DateTimeOffset.UtcNow); + OperationAuthorizationCoordinator? current = null; + var evidence = new AuthorizationEvidenceCoordinator(Substitute.For(), new AuditStateCapture(), + Substitute.For(), clock, new SystemGuidFactory(), () => current!, [], + NullLogger.Instance); + _coordinator = current = new OperationAuthorizationCoordinator(catalog, authorizer, Context, [_candidates], [], evidence); + } + + public ITenantContext Context { get; } + public IIdentityAuthorizationReader Reader { get; } = Substitute.For(); + public WitnessSource Witnesses { get; } = new(); + public ProtectedOperationDecision? Decision { get; private set; } + + public Task> RunAsync(TRequest request) where TRequest : notnull => + _coordinator.ExecuteRequestAsync(request, () => + { + Decision = _coordinator.CurrentDecision; + return Task.FromResult(Result.Ok(None.Value)); + }); + + public void Dispose() + { + _coordinator.Dispose(); + _candidates.Dispose(); + Witnesses.Dispose(); + _second.Dispose(); + } + + private static ITenantContext LiveContext(TenantContextOrigin origin, OrganizationId? organization) + { + var context = Substitute.For(); + context.IsResolved.Returns(true); + context.TenantId.Returns(Tenant); + context.OrganizationId.Returns(organization); + context.UserId.Returns(Actor); + context.Origin.Returns(origin); + return context; + } + } + + private sealed class CandidateSource(ITenantContext context, AuthorizationSourceKind kind) + : AuthorizationCandidate.MintingSource, IAuthorizationCandidateSource + { + public AuthorizationCandidate? ForValidatedScope(TenantId tenant, OrganizationId? organization) => + tenant == context.TenantId && organization == context.OrganizationId + ? ForCandidate(kind, context.UserId!.Value, tenant, organization) : null; + } + + private sealed class InvocationSource : OperationInvocation.MintingSource + { + private OperationInvocation? _current; + public OperationInvocation Open(object operation, OperationPolicy policy, ITenantContext context) => + _current = ForInvocation(operation, policy, context, null, null, CancellationToken.None); + protected override bool IsCurrent(OperationInvocation invocation) => ReferenceEquals(_current, invocation); + } + + /// Test-only captured provenance; it claims no HTTP credential admission. + private sealed class WitnessSource : OwnDataRequestScopeWitness.MintingSource, IOwnDataRequestScopeSource + { + private readonly object _evidence = new(); + private OperationInvocation? _current; + public OwnDataRequestPurpose Purpose { get; set; } = OwnDataRequestPurpose.Read; + public DataRequestScopeGroup? Group { get; set; } + public OwnDataRequestScopePage? Page { get; set; } + public OrganizationId? HostOrganization { get; set; } + public UserId Actor { get; set; } = OwnDataRequestPolicyTests.Actor; + public TenantId HostTenant { get; set; } = Tenant; + public string HostName { get; set; } = "school.invalid"; + public int Captured { get; private set; } + + public OwnDataRequestScopeWitness? ForInvocation(OperationInvocation invocation) + { + if (!IsOpen || invocation.Policy.Kind != OperationPolicyKind.OwnDataRequestEntry) return null; + _current = invocation; + Captured++; + return Capture(_evidence, invocation, Subject, Actor, HostTenant, HostOrganization, HostName, Purpose, Group, Page); + } + + protected override bool IsEvidenceCurrent(object evidence, OperationInvocation invocation) => + ReferenceEquals(evidence, _evidence) && ReferenceEquals(invocation, _current); + } +} diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 166a066d..b09a069c 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -5711,7 +5711,10 @@ writers; qualification remains source-bound in the phase Status. SMTP adds no te 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 +adds no logical tenant setter. The +[retained own data-request scope](#retained-own-data-request-scope) is the seventeenth +definer and the fifteenth logical tenant setter, implemented by the same four physical +writers. The operator act executor that installs an operator act's 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 @@ -6602,3 +6605,94 @@ Real PostgreSQL as each role: retryable outage. - `PlatformOperatorHttpTests` and `PlatformAdminGateTests`: the routes, their statuses and contract, and the pair of permissions, each held alone. + +## Retained own data-request scope + +**Derives from:** +[ADR-0106 § 9](../decisions/0106-subject-data-requests-authority-and-status.md), +[ADR-0107 § 8](../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0095 Amendment 5](../decisions/0095-revision-pinned-membership-custom-fields.md). +A person reads and files data requests after their Membership is gone, and a Suspended +person does so at all, through the consent subject's model. This section owns the one +definer, its two owner arms and the setter that consumes its result; the +[phase Status](../roadmap/phase-03-identity-admin.md) owns the native operations that call +it and their qualification. + +### The function + +`public.fn_identity_own_data_request_scopes(p_actor uuid, p_host_tenant uuid, +p_host_organization uuid, p_mode text, p_organization uuid, p_after_organization uuid, +p_limit integer)` → rows of `(tenant_id uuid, organization_id uuid)`. + +- **Answer.** The scope groups in the host's tenant in which the actor holds a Membership + of any status, a Revoked tombstone included, or has any data request; on an + organization host only that organization's group, never the tenant-wide group or a + sibling branch. Distinct, at most twenty, ordered by organization with the tenant-wide + group first under the nil key. No Membership, request, status, profile or provider + data, and no write. +- **Modes.** `list` requires a NULL `p_organization`; its optional + `p_after_organization` is the last key of the previous page, the nil UUID standing for + the tenant-wide group. `select` proves one exact group (`p_organization` NULL for the + tenant-wide group), takes no cursor and a limit of exactly one. +- **Refusals,** all `23514`: a session user other than `learnstack_app`; any announced + `app.tenant_id`, `app.organization_id`, `app.scope`, `app.identity_authority_id` or + `app.identity_subject_key`; a transaction that is not READ ONLY and READ COMMITTED; a + NULL, nil or SystemActor actor; a NULL, nil or sentinel host tenant; a nil host or + selected organization; any mode, limit or argument combination outside the two modes. +- **Confinement.** `LANGUAGE plpgsql VOLATILE SECURITY DEFINER`, owned by the NOBYPASSRLS + `learnstack_migration`, fixed `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, + `EXECUTE` to `learnstack_app` only. The actor is not authenticated by SQL: as for the + consent definer, only normalized verified binding state supplies `p_actor`, and the + caller census confines the one caller, `OwnDataRequestScopeLookup`, which runs it on a + physically READ ONLY owner in a child scope and closes that owner before any + observation escapes. + +### The two owner arms + +`memberships_isolation` and `data_subject_requests_isolation` each gain one USING arm, +beside their unchanged application arm and unchanged WITH CHECK; the Membership policy +keeps its provider-ingress and self-discovery arms. Both arms are written identically: + +```sql +current_user='learnstack_migration' AND session_user='learnstack_app' +AND NULLIF(current_setting('app.tenant_id',true),'') IS NULL +AND NULLIF(current_setting('app.organization_id',true),'') IS NULL +AND NULLIF(current_setting('app.scope',true),'') IS NULL +AND NULLIF(current_setting('app.identity_authority_id',true),'') IS NULL +AND NULLIF(current_setting('app.identity_subject_key',true),'') IS NULL +AND current_setting('transaction_read_only')='on' +``` + +An arm admits exactly the state the function requires on entry, and only to code that +runs as the owner, that is, to a definer body. It is state-bound, not caller-bound: a +policy cannot see which function is running. No other definer reads either table in that +state: the self-discovery and creation definers require an identity announcement, the +Membership guards run inside a tenant's write, the provider definers run for their own +login role, the consent definer reads only its own table, and no other definer body names +`data_subject_requests`. The definer census pins every body, so a new definer that would +read through these arms is a reviewed change. The arms are read-only by their own +predicate; the artifact, ticket and chunk tables gain none. + +### The setter + +`OwnDataRequestScope` is the fifteenth logical tenant setter +([Security § The out-of-band setters](11-security.md#the-out-of-band-setters)). It +consumes a single-use immutable operation/actor/subject/real-host/group/mode witness +(`OwnDataRequestScopeWitness`) on a fresh physical owner: `list` and `read` are physical +READ ONLY, `create`, `cancel`, `ticket` and `chunk` ordinary READ WRITE. It announces +exactly the witness's group through the one witness-aware core, never joins or +retargets an owner, and supplies no Membership, ordinary native session or tenant-wide +`app.scope`. Its context origin, `HostAndOwnDataRequestScope`, reaches only operations +of the `OwnDataRequestEntry` policy kind. + +### Proof + +Real PostgreSQL as `learnstack_app` and as each other role, in `OwnDataRequestScopeTests`: +the subject's exact groups on a tenant and an organization host, paging and selection, +two tenants and two organizations, Suspended and Revoked Memberships and a +request-only group retained, every refused state and argument, the function's ACL and +owner, the two arms shut to a session and to every other role, a dirty probe that states +exactly what the arms admit, the request policy against an independent canonicalized +oracle, the confined lookup, and the setter's captured owner. The Membership policy +oracle is in `GlobalIdentitySchemaTests`, and the census counts are there too +(thirty-nine functions, seventeen definers); the head pin is in `MigrationRollbackTests`. diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index d5b94c2a..1c91ef3e 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -768,10 +768,12 @@ context writer, factory privilege or tenant retargeting authority. ### The out-of-band setters `TransactionBehavior` delegates the general announcement path to -`TransactionExecutionCoordinator`. The accepted fourteen logical setter paths are -enumerated below; ADR-0097 adds only the machine provider-recipient owner, and +`TransactionExecutionCoordinator`. The accepted fifteen logical setter paths are +enumerated below; ADR-0097 adds only the machine provider-recipient owner, [ADR-0099 Amendment 6](../decisions/0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) -only the federation host-alias reader. +only the federation host-alias reader, and +[ADR-0106 § 9](../decisions/0106-subject-data-requests-authority-and-status.md) only the +retained own data-request scope owner. Implementation and source-bound proof are recorded in the [phase Status](../roadmap/phase-03-identity-admin.md). ADR-0076 adds the ninth candidate reader and ADR-0078 the tenth own-context @@ -803,6 +805,7 @@ physical unit-of-work writer with the exact operation mode below: | `ConsentSubjectScope` | operation-bound existing owner, physical ReadOnly for retained discovery/history or ordinary ReadWrite for withdrawal | Single-use exact operation/actor/subject/real-host/retained-scope/mode witness; no Membership, ordinary native session, custom value or `app.scope` | | `ProviderEventRecipient` | actual claimed-target owner, ordinary app ReadWrite | Private source-validated single-use target/EventId/tenant/token/lease witness; only its outbox production; no HTTP, Platform, profile or ordinary protected command authority | | `FederationHostAliasReader` | its own short read-only one | The native self read ends before tenant resolution; it announces only the classified host tenant and reads only that tenant's Active federation alias ([Database Standards § Federation host-alias read](05-database.md#federation-host-alias-read)) | +| `OwnDataRequestScope` | operation-bound fresh owner, physical ReadOnly for list/read or ordinary ReadWrite for create/cancel/ticket/chunk | Single-use exact operation/actor/subject/real-host/retained-group/mode witness built from `fn_identity_own_data_request_scopes`; no Membership, ordinary native session or `app.scope` ([Database Standards § Retained own data-request scope](05-database.md#retained-own-data-request-scope)) | > **`IOrganizationScopeValidator` performs row-7 organization narrowing after > affirmative live Membership admission.** `TenantAssertionMiddleware` separately @@ -827,7 +830,7 @@ variable is unset fails `WITH CHECK` ([ADR-0033 Amendment 2 § 5](../decisions/0033-audit-durability-model.md), [ADR-0044 § 9](../decisions/0044-audit-write-path.md)). -Every one of the fourteen admitted setters connects as `learnstack_app`. A setter that reached +Every one of the fifteen admitted setters connects as `learnstack_app`. A setter that reached for `learnstack_platform` would be invisible to the isolation suite, which is the failure mode [ADR-0003](../decisions/0003-tenant-isolation-defense-in-depth.md) names by hand. @@ -844,7 +847,7 @@ runs on it. unit's announcement seam. Matching `[TenantOwned]` table names would put a parser between every query and the database to decide something the transaction already answers. -Of the fourteen admitted logical paths, the MediatR transaction owner and P02b-3's integration +Of the fifteen admitted logical paths, the MediatR transaction owner and P02b-3's integration transport mark the ambient transaction through sanctioned `IUnitOfWork` announcement methods. Durable acceptance and prepared subscriber execution both announce before their first app-role command; the production call-site census @@ -862,7 +865,10 @@ consumes its distinct consent-subject witness after its preliminary owner closes its retained history/withdrawal modes cannot be exchanged or reused. The fourteenth, `FederationHostAliasReader`, issues raw `NpgsqlCommand`s on a READ ONLY connection of its own, like the cached-projection loaders, and announces only the host -tenant for its one alias read. +tenant for its one alias read. The fifteenth, `OwnDataRequestScope`, consumes its distinct +retained data-request witness through the same physical unit-of-work writer after the +preliminary `fn_identity_own_data_request_scopes` owner closes; it announces exactly the +witness's group and its list/read and write modes cannot be exchanged or reused. `CachedHostToTenantResolver` is not in this set at all: it sets `app.resolving_host`, not `app.tenant_id`. That is also why the exemption list is empty, and why `PlatformAdminScope`, whose `BYPASSRLS` connection diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 1268a56b..56df123e 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -659,6 +659,19 @@ OwnMembershipRead remains read-only; these two exact commands confer no general own-mutation authority. Same-key receipts reauthorize the original actor/target; stale different-key predecessor conflicts and never silently retries. +A subject's own data requests use two key-less policy kinds +([ADR-0106 § 4](../decisions/0106-subject-data-requests-authority-and-status.md)). +`OwnDataRequest` requires the actor's own Active Membership in exactly the announced +group (a tenant-wide Membership does not cover an organization's group, nor the +reverse), through a live session, and consults no grant or Role. +`OwnDataRequestEntry` is the retained own scope: it is admitted only by the subject's +own scope witness under the `HostAndOwnDataRequestScope` origin +([Database Standards § Retained own data-request scope](05-database.md#retained-own-data-request-scope)), +so it also serves a Suspended person and a person whose Membership is gone, and it +supplies no Membership authority. Administrator requests are `Protected` with the +existing `[identity.membership.admin at Tenant, at Organization]` alternatives. No +assignable key is added and the grant union is unchanged. + `canManageCustomFields` is the tenth advisory administration capability: current Tenant definition-admin authority in applicable orgless write context. Identity's projection evaluates the registered SharedKernel pair with fresh facts/catalogue diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index f42b9b1a..b20b3538 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 -**393 test methods run in +**397 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,8 +217,8 @@ 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. -**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 +**294 rules in this catalogue are Implemented, and 175 of them are in that assembly.** +The other 119 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 that holds ten. @@ -7973,3 +7973,37 @@ sign-in read). The [FederationHttpTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/FederationHttpTests.cs), [IdentitySelfEntryHttpTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/IdentitySelfEntryHttpTests.cs). - **Phase:** 03 (P03-8 Step 4, review round 2). + +## P03-10 data request controls + +**Derives from:** [ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) +and [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md). Canonical +names for the package's obligations are assigned with the step that introduces them. + +#### `Own_Data_Request_Scope_Is_Host_And_Subject_Confined` + +- **Asserts:** `fn_identity_own_data_request_scopes` returns only the verified actor's + scope groups in the host's tenant (on an organization host, only that organization's + group), from Memberships of any status and from requests, and nothing of another + person, tenant or branch; it refuses every state and argument outside its two closed + modes, executes for `learnstack_app` alone, and has one caller, the confined lookup on + its own read-only owner. Its two owner arms admit only the function's own entry state + and stay shut to every session and every other role. The `OwnDataRequestEntry` kind is + admitted only by a live `OwnDataRequestScopeWitness` under the + `HostAndOwnDataRequestScope` origin, which the fifteenth logical tenant setter consumes + on a fresh owner announcing exactly the witness's group; the `OwnDataRequest` kind + requires the actor's Active Membership in exactly the announced group. Until the + native retained-entry operations land with their endpoints, no production type mints + the witness, builds the context, observes the groups or registers either kind. +- **Source:** [ADR-0106 § 4 and § 9](../decisions/0106-subject-data-requests-authority-and-status.md), + [Database Standards § Retained own data-request scope](05-database.md#retained-own-data-request-scope), + [Security § The out-of-band setters](11-security.md#the-out-of-band-setters). +- **Type:** real app-role PostgreSQL behaviour, refusals, ACL and policy oracle with a + dirty probe of the arms; compiled minter, binder, owner and caller censuses with planted + minters and binders; coordinator and evaluator behaviour for both kinds. **Kind:** both. +- **Status:** **Implemented** (`OwnDataRequestScopeTests`); companion owners below. +- **Test owners:** + [OwnDataRequestScopeTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs), + [OwnDataRequestScopeConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs), + [OwnDataRequestPolicyTests.cs](../../backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs). +- **Phase:** 03 (P03-10, retained own scope). diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 49fa85c0..8ab362ea 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -160,6 +160,7 @@ "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests", "LearnStack.Tests.Integration.Database.OutboxProcessorTests", "LearnStack.Tests.Integration.Database.OutboxProducerTests", + "LearnStack.Tests.Integration.Database.OwnDataRequestScopeTests", "LearnStack.Tests.Integration.Database.P02d2FoundationTests", "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests", "LearnStack.Tests.Integration.Database.PlatformOperatorOnboardingTests", From 889245c4f06a6077fb5ff47b85be7bb10de5b862 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 07:26:33 +0300 Subject: [PATCH 06/61] feat(identity): add the data export engine P03-10 Step 1, unit 2: AES-256-GCM export cipher and key ring, the Postgres artifact store, the bounded bundle builder, the Identity, Tenancy, Customization, Education and Audit user-data participants, the export and purge jobs, the fulfilment scheduler and the failed-request reconciler, with the artifact truncation record. ADR: 0106, 0107 Module: Identity, Tenancy, Customization, Education, Audit, Application Co-Authored-By: Claude Sonnet 5.5 --- .../Composition/DataExportComposition.cs | 45 ++ .../PersistenceCompositionExtensions.cs | 6 +- .../DataProtection/DataExportBundleBuilder.cs | 328 ++++++++++ .../DataProtection/DataExportOptions.cs | 52 ++ .../DataProtection/PlaintextSegmentBuffer.cs | 121 ++++ .../UserDataProtectionRegistration.cs | 7 +- .../AttributionReferenceCounter.cs | 96 +++ .../DataProtection/DataExportCipher.cs | 229 +++++++ .../DataProtection/DataExportTruncation.cs | 57 ++ .../DataProtection/DataRequestLimits.cs | 43 ++ .../IDataExportArtifactStore.cs | 35 +- .../IDataExportBundleBuilder.cs | 68 +++ .../DataProtection/IUserDataParticipant.cs | 8 + .../DataProtection/UserDataExportRecord.cs | 42 ++ .../DataRequests/AuditPayloadProjection.cs | 83 +++ .../DataRequests/AuditUserDataParticipant.cs | 326 ++++++++++ .../CustomizationUserDataParticipant.cs | 62 ++ .../EducationUserDataParticipant.cs | 61 ++ .../DataRequests/DataExportJobContracts.cs | 13 + .../Audit/IdentityAuditCatalogSource.cs | 10 + .../DataRequests/DataExportJobs.cs | 214 +++++++ .../DataRequestFailureReconciler.cs | 90 +++ .../DataRequestFulfillmentScheduler.cs | 79 +++ .../DataRequests/IDataRequestStore.cs | 61 ++ .../MembershipFieldRevisionReader.cs | 40 ++ .../IdentityOperationPolicySource.cs | 5 + .../DataExportArtifact.cs | 23 +- .../DataRequestDocuments.cs | 55 ++ .../IdentityFoundationRegistration.cs | 27 + .../DataRequests/DataExportJobRegistration.cs | 38 ++ .../DataRequests/DataRequestJobPhaseReader.cs | 84 +++ .../DataRequests/DataRequestStore.cs | 126 ++++ .../IdentityUserDataParticipant.cs | 331 ++++++++++ .../PostgresDataExportArtifactStore.cs | 319 ++++++++++ .../InvitationEmailRegistration.cs | 9 +- .../Persistence/DataRequestConfigurations.cs | 22 +- .../Persistence/DataRequestStorageDdl.cs | 6 +- ...3001_add_data_subject_requests.Designer.cs | 23 +- ...0261122013001_add_data_subject_requests.cs | 2 + .../IdentityDbContextModelSnapshot.cs | 23 +- .../TenancyUserDataParticipant.cs | 124 ++++ .../InvitationEmailFixtureConfiguration.cs | 2 + .../BackgroundJobAdmissionBoundaryTests.cs | 2 + .../BackgroundJobManifestBoundaryTests.cs | 78 ++- .../IdentityAuditConventionTests.cs | 13 +- .../IdentityFoundationConventionTests.cs | 4 + .../UserDataParticipantCensusTests.cs | 164 +++++ .../BackgroundJobProductionManifestTests.cs | 12 +- .../Database/DataExportArtifactStoreTests.cs | 209 +++++++ .../Database/DataExportExecutionTests.cs | 566 ++++++++++++++++++ .../Database/DataExportParticipantTests.cs | 136 +++++ .../Database/DataExportTestKit.cs | 76 +++ .../Database/DataRequestStorageTests.cs | 24 + .../DataExportBundleBuilderTests.cs | 299 +++++++++ .../Audit/AuditUserDataParticipantTests.cs | 142 +++++ .../Identity/DataExportTruncationTests.cs | 69 +++ .../DataRequestFulfillmentSchedulerTests.cs | 111 ++++ .../DataProtection/DataExportCipherTests.cs | 245 ++++++++ .../InvitationEmailRegistryTests.cs | 68 ++- docs/architecture/23-data-protection.md | 9 +- docs/modules/identity/audit.md | 3 + docs/modules/identity/providers.md | 9 + .../21-architecture-tests-catalogue.md | 33 +- frontend/apps/web/src/server/ingress.ts | 22 + .../src/test/public-api-environment.test.ts | 24 + scripts/ci-test-shards-plan.json | 3 + scripts/demo.mjs | 5 + scripts/public-runtime.mjs | 14 + 68 files changed, 5688 insertions(+), 47 deletions(-) create mode 100644 backend/src/LearnStack.Api/Composition/DataExportComposition.cs create mode 100644 backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs create mode 100644 backend/src/LearnStack.Application/DataProtection/DataExportOptions.cs create mode 100644 backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs create mode 100644 backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs create mode 100644 backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/IDataExportBundleBuilder.cs create mode 100644 backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs create mode 100644 backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditPayloadProjection.cs create mode 100644 backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditUserDataParticipant.cs create mode 100644 backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserDataParticipant.cs create mode 100644 backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserDataParticipant.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataExportJobContracts.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/MembershipFieldRevisionReader.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportJobRegistration.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserDataParticipant.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PostgresDataExportArtifactStore.cs create mode 100644 backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserDataParticipant.cs create mode 100644 backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataExportArtifactStoreTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataExportTestKit.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Application/DataProtection/DataExportBundleBuilderTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Audit/AuditUserDataParticipantTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataExportTruncationTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/DataExportCipherTests.cs diff --git a/backend/src/LearnStack.Api/Composition/DataExportComposition.cs b/backend/src/LearnStack.Api/Composition/DataExportComposition.cs new file mode 100644 index 00000000..3b1d799c --- /dev/null +++ b/backend/src/LearnStack.Api/Composition/DataExportComposition.cs @@ -0,0 +1,45 @@ +using LearnStack.Application.DataProtection; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Audit.Infrastructure.DataRequests; +using LearnStack.Modules.Customization.Infrastructure.DataRequests; +using LearnStack.Modules.Education.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Infrastructure.DataRequests; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Api.Composition; + +/// +/// The composition root's half of subject data requests +/// (ADR-0107 § 1, § 4): +/// the bundle ceiling, the export key ring, its startup check and the participants of the modules that register +/// through this root. Identity's participant and artifact store come with its contextual foundation. +/// +internal static class DataExportComposition +{ + internal static IServiceCollection AddDataExportCustody(this IServiceCollection services, IConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + // Fail fast: an invalid ceiling refuses composition, and the key ring is checked before workers start. + services.AddLearnStackUserDataProtection(DataExportOptions.FromSetting(configuration[DataExportOptions.MaxBytesKey])); + services.TryAddSingleton(); + services.AddHostedService(); + services.AddTenancyUserDataParticipant(); + services.AddCustomizationUserDataParticipant(); + services.AddEducationUserDataParticipant(); + services.AddAuditUserDataParticipant(); + return services; + } +} + +/// The export key ring is fixed and validated before workers start, like the invitation key ring. +internal sealed class DataExportStartupService(DataExportCipher cipher) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) + { + // Construction validates the complete key ring; nothing is sealed here. + ArgumentNullException.ThrowIfNull(cipher); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index 18548934..f6196b25 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -189,9 +189,9 @@ public static IServiceCollection AddLearnStackPersistence( PlatformAdminScope.PlatformDataSourceKey, (_, _) => new PrivilegedDataSource(() => BuildPlatformDataSource(platformConnectionString))); services.AddLearnStackBackgroundJobContracts(); - // ADR-0107 § 1: the participant collection and the hold-source default. No participant - // is registered yet; each module adds its own from its registration. - services.AddLearnStackUserDataProtection(); + // ADR-0107 § 1 and § 4: the participant collection, the hold-source default, the bundle + // ceiling, the export key ring and the participants each module registers from its own boundary. + services.AddDataExportCustody(configuration); services.AddInvitationEmailDelivery(configuration); // The scope is a stateless singleton. Admission is not its concern any more: the diff --git a/backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs b/backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs new file mode 100644 index 00000000..2631a919 --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs @@ -0,0 +1,328 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Application.DataProtection; + +/// +/// Builds one export bundle as a single JSON document streamed into chunk-sized plaintext segments +/// (ADR-0107 § 3). +/// +/// +/// The document is, in this order: +/// +/// { "schema_version": 1, +/// "request": { "id", "kind", "origin", "scope" }, +/// "generated_at": "…Z", +/// "sections": { "<participant>": { "<collection>": [ record, … ], … }, … }, +/// "truncated": { "<participant>.<collection>": { "included": n, "total": m } } } +/// +/// +/// Every registered participant has a section, an empty one included, in registry order. A section writes its +/// collections one after another: returning to a collection it has left is a programming error, because the +/// document is streamed and never reordered. +/// +/// +/// Bounds. A record is admitted only if it fits both its section's cap and the bundle ceiling less a +/// fixed reserve for the closing structure, so the finished document never passes DataExport:MaxBytes. +/// The section cap is checked first: a record that would pass both is a truncation of its section, which the +/// participant declares, not a failure of the request. A record is validated as exactly one JSON value before +/// any byte of it is written, so the bundle never holds a partial record. +/// +/// +public sealed class DataExportBundleBuilder(IUserDataParticipantRegistry registry, DataExportOptions options) : IDataExportBundleBuilder +{ + /// The bundle schema version; a change to the document's shape is a new version. + public const int SchemaVersion = 1; + + private const string InstantFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'"; + + public async Task BuildAsync(UserDataSubject subject, DateTimeOffset generatedAt, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + if (generatedAt == default || generatedAt.Offset != TimeSpan.Zero) + { + throw new ArgumentException("A bundle's generation time is a UTC instant.", nameof(generatedAt)); + } + + if (subject.Kind != DataRequestKind.Export) + { + throw new ArgumentException("Only an export request builds a bundle.", nameof(subject)); + } + + var buffer = new PlaintextSegmentBuffer(options.MaxBytes); + var built = false; + try + { + var state = new BundleState(buffer, options.MaxBytes - DataRequestLimits.BundleTailReserveBytes); + using (state.Json) + { + WriteHeader(state.Json, subject, generatedAt); + state.Json.WriteStartObject("sections"); + foreach (var participant in registry.Participants) + { + cancellationToken.ThrowIfCancellationRequested(); + var section = new SectionWriter(state, participant.Key, SectionCap(participant)); + state.Json.WritePropertyName(participant.Key); + state.Json.WriteStartObject(); + try + { + await participant.ExportAsync(subject, section, cancellationToken).ConfigureAwait(false); + } + finally + { + section.Close(); + } + + if (state.TooLarge) + { + return DataExportBundleResult.TooLarge; + } + + section.Finish(); + state.Json.WriteEndObject(); + } + + state.Json.WriteEndObject(); + var truncations = DataExportTruncation.Normalize(state.Truncations); + state.Json.WriteStartObject("truncated"); + foreach (var truncation in truncations) + { + state.Json.WriteStartObject(truncation.Collection); + state.Json.WriteNumber("included", truncation.Included); + state.Json.WriteNumber("total", truncation.Total); + state.Json.WriteEndObject(); + } + + state.Json.WriteEndObject(); + state.Json.WriteEndObject(); + state.Json.Flush(); + if (buffer.Overflowed || buffer.Length is < 1 || buffer.Length > options.MaxBytes) + { + return DataExportBundleResult.TooLarge; + } + + built = true; + return DataExportBundleResult.Built(new Bundle(buffer, truncations)); + } + } + finally + { + if (!built) + { + buffer.Dispose(); + } + } + } + + private static void WriteHeader(Utf8JsonWriter json, UserDataSubject subject, DateTimeOffset generatedAt) + { + json.WriteStartObject(); + json.WriteNumber("schema_version", SchemaVersion); + json.WriteStartObject("request"); + json.WriteString("id", subject.RequestId.ToString("D")); + json.WriteString("kind", DataRequestCodes.Kinds.ToCode(subject.Kind)); + json.WriteString("origin", DataRequestCodes.Origins.ToCode(subject.Origin)); + json.WriteString("scope", subject.Group.IsTenantWide ? "tenant" : "organization"); + json.WriteEndObject(); + json.WriteString("generated_at", generatedAt.UtcDateTime.ToString(InstantFormat, CultureInfo.InvariantCulture)); + } + + private static long SectionCap(IUserDataParticipant participant) => participant.ExportSectionCapBytes switch + { + null => long.MaxValue, + { } cap when cap is >= 1 and <= DataRequestLimits.MaximumBundleBytes => cap, + _ => throw new InvalidOperationException("A participant's export section cap is outside the bundle's range."), + }; + + private sealed class BundleState + { + public BundleState(PlaintextSegmentBuffer buffer, long payloadLimit) + { + Json = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = false, SkipValidation = false }); + PayloadLimit = payloadLimit; + } + + public Utf8JsonWriter Json { get; } + + /// The ceiling less the closing reserve: what records and their framing may use. + public long PayloadLimit { get; } + + public long Written => Json.BytesCommitted + Json.BytesPending; + + /// Sticky: once a record was refused for the ceiling, the bundle is refused. + public bool TooLarge { get; set; } + + public List Truncations { get; } = []; + } + + /// One participant's bounded, append-only section; unusable once its participant returned. + private sealed class SectionWriter(BundleState state, string section, long cap) : IUserDataExportWriter + { + private readonly HashSet _closedCollections = new(StringComparer.Ordinal); + private readonly HashSet _declared = new(StringComparer.Ordinal); + private string? _current; + private long _sectionBytes; + private bool _closed; + + public long RemainingBytes => _closed || state.TooLarge + ? 0 + : Math.Max(0, Math.Min(cap - _sectionBytes, state.PayloadLimit - state.Written)); + + public ValueTask AppendAsync(string collection, ReadOnlyMemory utf8JsonRecord, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(Append(collection, utf8JsonRecord.Span)); + } + + public void DeclareTruncated(string collection, long includedRecords, long totalRecords) + { + RequireOpen(); + if (!DataRequestLimits.IsCollectionName(collection)) + { + throw new ArgumentException("A truncation names a collection of its section.", nameof(collection)); + } + + if (!_declared.Add(collection)) + { + throw new InvalidOperationException("A collection's truncation is declared once."); + } + + if (state.Truncations.Count >= DataRequestLimits.MaximumTruncatedCollections) + { + throw new InvalidOperationException("A bundle states at most the bounded number of truncated collections."); + } + + state.Truncations.Add(new DataExportTruncation(section + "." + collection, includedRecords, totalRecords)); + } + + /// Refuses every later call, whether the participant returned or threw. + public void Close() => _closed = true; + + /// Closes the open collection once the participant returned normally. + public void Finish() + { + if (_current is not null) + { + state.Json.WriteEndArray(); + _current = null; + } + } + + private UserDataExportAppend Append(string collection, ReadOnlySpan record) + { + RequireOpen(); + if (!DataRequestLimits.IsCollectionName(collection)) + { + throw new ArgumentException("A record names a collection of its section.", nameof(collection)); + } + + if (state.TooLarge) + { + return UserDataExportAppend.BundleCeilingReached; + } + + var opening = !string.Equals(_current, collection, StringComparison.Ordinal); + if (opening && _closedCollections.Contains(collection)) + { + throw new InvalidOperationException("A section writes its collections one after another and never returns to one."); + } + + RequireSingleValue(record); + + // An upper bound of what the record adds: itself and its separating comma, and for a new collection + // the previous collection's closing bracket, a comma, the quoted name, the colon and the bracket. + var cost = record.Length + 1L + (opening ? collection.Length + 6L : 0L); + if (_sectionBytes + cost > cap) + { + return UserDataExportAppend.SectionCapReached; + } + + if (state.Written + cost > state.PayloadLimit) + { + state.TooLarge = true; + return UserDataExportAppend.BundleCeilingReached; + } + + if (opening) + { + if (_current is not null) + { + state.Json.WriteEndArray(); + _closedCollections.Add(_current); + } + + state.Json.WritePropertyName(collection); + state.Json.WriteStartArray(); + _current = collection; + } + + state.Json.WriteRawValue(record, skipInputValidation: true); + _sectionBytes += cost; + return UserDataExportAppend.Appended; + } + + private void RequireOpen() + { + if (_closed) + { + throw new InvalidOperationException("A section writer is used only while its participant exports."); + } + } + + private static void RequireSingleValue(ReadOnlySpan record) + { + if (record.IsEmpty) + { + throw new ArgumentException("An export record is one complete JSON value.", nameof(record)); + } + + var reader = new Utf8JsonReader(record, new JsonReaderOptions { CommentHandling = JsonCommentHandling.Disallow }); + try + { + if (!reader.Read()) + { + throw new ArgumentException("An export record is one complete JSON value.", nameof(record)); + } + + reader.Skip(); + if (reader.Read()) + { + throw new ArgumentException("An export record is one complete JSON value.", nameof(record)); + } + } + catch (JsonException) + { + throw new ArgumentException("An export record is one complete JSON value.", nameof(record)); + } + } + } + + private sealed class Bundle(PlaintextSegmentBuffer buffer, ImmutableArray truncations) : IDataExportBundle + { + public long ByteCount { get; } = buffer.Length; + + public int ChunkCount { get; } = DataRequestLimits.ChunkCountFor(buffer.Length); + + public ImmutableArray Truncations { get; } = truncations; + + public async IAsyncEnumerable> ReadChunksAsync( + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + foreach (var chunk in buffer.Chunks()) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return chunk; + await Task.CompletedTask.ConfigureAwait(false); + } + } + + public void Dispose() => buffer.Dispose(); + + public override string ToString() => nameof(IDataExportBundle); + } +} diff --git a/backend/src/LearnStack.Application/DataProtection/DataExportOptions.cs b/backend/src/LearnStack.Application/DataProtection/DataExportOptions.cs new file mode 100644 index 00000000..de475adf --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/DataExportOptions.cs @@ -0,0 +1,52 @@ +using System.Globalization; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Application.DataProtection; + +/// +/// The export bundle ceiling, DataExport:MaxBytes: 16 MiB by default and 64 MiB at most +/// (ADR-0107 § 4). +/// +/// +/// Fixed for the process and validated when the composition root builds it, so a misconfigured ceiling stops +/// the host at startup instead of failing the first export. The ceiling is not a secret. +/// +public sealed record DataExportOptions +{ + public const string MaxBytesKey = "DataExport:MaxBytes"; + + /// The ceiling is outside the supported range. + public DataExportOptions(long maxBytes) + { + if (maxBytes is < DataRequestLimits.MinimumBundleBytes or > DataRequestLimits.MaximumBundleBytes) + { + throw new ArgumentOutOfRangeException(nameof(maxBytes), "The export bundle ceiling is outside its supported range."); + } + + MaxBytes = maxBytes; + } + + /// The largest bundle, in plaintext UTF-8 bytes, an export may produce. + public long MaxBytes { get; } + + public static DataExportOptions Default { get; } = new(DataRequestLimits.DefaultMaximumBundleBytes); + + /// Reads the configured value: absent means the default; anything but a plain integer in range fails. + /// The value is present and invalid. + public static DataExportOptions FromSetting(string? value) + { + if (value is null) + { + return Default; + } + + if (!long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var maxBytes) + || maxBytes is < DataRequestLimits.MinimumBundleBytes or > DataRequestLimits.MaximumBundleBytes) + { + throw new InvalidOperationException( + $"{MaxBytesKey} must be a whole number of bytes from {DataRequestLimits.MinimumBundleBytes} to {DataRequestLimits.MaximumBundleBytes}."); + } + + return new DataExportOptions(maxBytes); + } +} diff --git a/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs b/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs new file mode 100644 index 00000000..72208673 --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs @@ -0,0 +1,121 @@ +using System.Buffers; +using System.Numerics; +using System.Security.Cryptography; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Application.DataProtection; + +/// +/// A bounded, append-only plaintext buffer of fixed chunk-sized segments, so the bundle is chunked exactly as +/// the artifact stores it and no single allocation grows with the bundle. +/// +/// +/// +/// A writer is handed one scratch buffer; copies what it wrote into the segments and +/// overwrites the scratch with zeros. Every segment is overwritten with zeros on . +/// +/// +/// The limit never throws inside a writer. Bytes past it are dropped and is set, +/// so a JSON writer flushing past the ceiling leaves the caller a refusal to read, not a half-written state. +/// +/// +internal sealed class PlaintextSegmentBuffer(long limit) : IBufferWriter, IDisposable +{ + private const int MinimumScratch = 4096; + private readonly List _segments = []; + private byte[] _scratch = []; + private int _tail = DataRequestLimits.ChunkPlaintextBytes; + private bool _disposed; + + /// The bytes stored. + public long Length { get; private set; } + + /// Whether a write passed the limit; the stored bytes are then incomplete and must not be used. + public bool Overflowed { get; private set; } + + public Memory GetMemory(int sizeHint = 0) => Scratch(sizeHint); + + public Span GetSpan(int sizeHint = 0) => Scratch(sizeHint); + + public void Advance(int count) + { + ObjectDisposedException.ThrowIf(_disposed, this); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, _scratch.Length); + try + { + if (Overflowed || Length + count > limit) + { + Overflowed = true; + return; + } + + var source = _scratch.AsSpan(0, count); + while (!source.IsEmpty) + { + if (_tail == DataRequestLimits.ChunkPlaintextBytes) + { + _segments.Add(new byte[DataRequestLimits.ChunkPlaintextBytes]); + _tail = 0; + } + + var take = Math.Min(source.Length, DataRequestLimits.ChunkPlaintextBytes - _tail); + source[..take].CopyTo(_segments[^1].AsSpan(_tail)); + _tail += take; + source = source[take..]; + } + + Length += count; + } + finally + { + CryptographicOperations.ZeroMemory(_scratch.AsSpan(0, count)); + } + } + + /// The stored bytes as chunks of exactly the chunk size but the last. + public IEnumerable> Chunks() + { + ObjectDisposedException.ThrowIf(_disposed, this); + for (var index = 0; index < _segments.Count; index++) + { + ObjectDisposedException.ThrowIf(_disposed, this); + yield return index == _segments.Count - 1 + ? _segments[index].AsMemory(0, _tail) + : _segments[index]; + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + foreach (var segment in _segments) + { + CryptographicOperations.ZeroMemory(segment); + } + + CryptographicOperations.ZeroMemory(_scratch); + _segments.Clear(); + _scratch = []; + Length = 0; + } + + private byte[] Scratch(int sizeHint) + { + ObjectDisposedException.ThrowIf(_disposed, this); + ArgumentOutOfRangeException.ThrowIfNegative(sizeHint); + var needed = Math.Max(sizeHint, MinimumScratch); + if (_scratch.Length < needed) + { + CryptographicOperations.ZeroMemory(_scratch); + _scratch = new byte[(int)Math.Min(Array.MaxLength, (long)BitOperations.RoundUpToPowerOf2((uint)needed))]; + } + + return _scratch; + } +} diff --git a/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs b/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs index 399f4ba7..47672dbe 100644 --- a/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs +++ b/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs @@ -25,12 +25,17 @@ namespace LearnStack.Application.DataProtection; /// public static class UserDataProtectionRegistration { - public static IServiceCollection AddLearnStackUserDataProtection(this IServiceCollection services) + /// The composition root's collection. + /// The validated bundle ceiling; the ADR-0107 § 4 default when absent. + public static IServiceCollection AddLearnStackUserDataProtection(this IServiceCollection services, + DataExportOptions? export = null) { ArgumentNullException.ThrowIfNull(services); services.TryAddScoped(provider => new UserDataParticipantRegistry(provider.GetServices())); services.TryAddSingleton(); + services.TryAddSingleton(export ?? DataExportOptions.Default); + services.TryAddScoped(); return services; } } diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs b/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs new file mode 100644 index 00000000..1b552812 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs @@ -0,0 +1,96 @@ +using System.Reflection; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace LearnStack.Infrastructure.DataProtection; + +/// +/// Counts a subject's creator, updater and deleter attribution on every mapped tenant-owned aggregate of one +/// module context, for the closed retained kind attribution_reference +/// (ADR-0107 § 6). +/// +/// +/// +/// Derived from the model, not listed. Every entity type the context maps that derives +/// and is tenant-owned is counted, so an aggregate a module adds later is +/// counted without a change here. +/// +/// +/// Exactly the group. An organization-scoped row counts for the group whose organization it carries, and a +/// tenant-owned row without an organization counts for the tenant-wide group only, so a person in several groups +/// is never counted twice. Reads run on the module context, inside the ambient tenant transaction and under its +/// query filter and row policy, and return a count: no row, no identifier. +/// +/// +public static class AttributionReferenceCounter +{ + private static readonly MethodInfo CountMethod = typeof(AttributionReferenceCounter) + .GetMethod(nameof(CountForAsync), BindingFlags.NonPublic | BindingFlags.Static)!; + + /// The module's own context. + /// The subject and group to count for. + /// Entity types reported under another kind, such as a request's own receipt. + /// Cancels the reads. + public static async Task CountAsync(DbContext context, UserDataSubject subject, IReadOnlySet? excluded, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(subject); + long total = 0; + foreach (var type in context.Model.GetEntityTypes() + .Where(entity => !entity.IsOwned() && !entity.HasSharedClrType) + .Select(entity => entity.ClrType) + .Where(clr => typeof(ITenantOwned).IsAssignableFrom(clr) && IsAuditable(clr) && excluded?.Contains(clr) != true) + .Distinct() + .OrderBy(clr => clr.FullName, StringComparer.Ordinal)) + { + var scoped = typeof(IOrganizationScoped).IsAssignableFrom(type); + if (!scoped && !subject.Group.IsTenantWide) + { + continue; + } + + var count = (Task)CountMethod.MakeGenericMethod(type) + .Invoke(null, [context, subject.SubjectUserId, subject.Group.OrganizationId, scoped, cancellationToken])!; + total = checked(total + await count.ConfigureAwait(false)); + } + + return total; + } + + private static bool IsAuditable(Type type) + { + for (var current = type.BaseType; current is not null; current = current.BaseType) + { + if (current.IsGenericType && current.GetGenericTypeDefinition() == typeof(AuditableEntity<>)) + { + return true; + } + } + + return false; + } + + private static async Task CountForAsync(DbContext context, UserId subject, OrganizationId? organization, + bool scoped, CancellationToken cancellationToken) + where T : class + { + IQueryable rows = context.Set().AsNoTracking(); + if (scoped) + { + rows = rows.Where(row => EF.Property(row, nameof(IOrganizationScoped.OrganizationId)) == organization); + } + + UserId? person = subject; + var created = await rows.LongCountAsync(row => EF.Property(row, "CreatedBy") == subject, cancellationToken) + .ConfigureAwait(false); + var updated = await rows.LongCountAsync(row => EF.Property(row, "UpdatedBy") == person, cancellationToken) + .ConfigureAwait(false); + var deleted = await rows.LongCountAsync(row => EF.Property(row, "DeletedBy") == person, cancellationToken) + .ConfigureAwait(false); + return checked(created + updated + deleted); + } +} diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs new file mode 100644 index 00000000..93c13387 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs @@ -0,0 +1,229 @@ +using System.Buffers.Binary; +using System.Collections.Frozen; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Secrets; + +namespace LearnStack.Infrastructure.DataProtection; + +/// What one sealed export chunk is bound to; the associated data repeats every member. +public sealed record DataExportChunkBinding +{ + /// An identity is nil or the position is outside the artifact. + public DataExportChunkBinding(Guid tenantId, Guid requestId, Guid artifactId, int index, int count) + { + if (tenantId == Guid.Empty || requestId == Guid.Empty || artifactId == Guid.Empty + || count is < 1 or > DataRequestLimits.MaximumChunkCount || index < 0 || index >= count) + { + throw new ArgumentException("A data export chunk binding needs its identities and its position.", nameof(tenantId)); + } + + TenantId = tenantId; + RequestId = requestId; + ArtifactId = artifactId; + Index = index; + Count = count; + } + + public Guid TenantId { get; } + public Guid RequestId { get; } + public Guid ArtifactId { get; } + public int Index { get; } + public int Count { get; } + + public override string ToString() => nameof(DataExportChunkBinding); +} + +/// One sealed chunk as it is stored: the key-ring label, the nonce, the ciphertext and the tag. +public sealed record DataExportSealedChunk(string KeyVersion, byte[] Nonce, byte[] Ciphertext, byte[] Tag) +{ + public override string ToString() => nameof(DataExportSealedChunk); +} + +/// +/// AES-256-GCM custody of export chunks under the DataExport:KeyRing secret +/// (ADR-0107 § 4). +/// +/// +/// +/// The key ring mirrors the invitation envelope's. One JSON secret +/// { "active": "version", "keys": { "version": "base64 of 32 bytes" } }, one to four distinct keys and an +/// active version that is one of them, read once through and fixed for the +/// process. New chunks are sealed under the active key; a chunk is opened under the key its stored label +/// names, so rotation is adding a key, making it active, and removing the old one only after every artifact +/// sealed under it has expired (seven days). Anything else refuses construction, which the host's startup +/// check turns into a refused start. +/// +/// +/// Associated data binds the format version, the key version, the tenant, the request, the artifact, +/// the chunk index and the chunk count, so a chunk moved to another position, artifact, request or tenant, a +/// truncated artifact or a relabelled key fails authentication. A fresh random 12-byte nonce is drawn for +/// every chunk. +/// +/// +/// No secret leaves. Every refusal is one fixed message with no key, label, plaintext or position; +/// prints the type name; key buffers are overwritten on , and +/// intermediate plaintext is overwritten on failure. +/// +/// +public sealed class DataExportCipher : IDisposable +{ + /// The secret name; the web launcher's allow-list carries its environment spelling. + public const string KeyRingSecret = "DataExport:KeyRing"; + + /// The format version the associated data begins with. + public const byte FormatVersion = 1; + + private readonly FrozenDictionary _keys; + private bool _disposed; + + /// The key ring is absent or malformed. + public DataExportCipher(ISecretProvider secrets) + { + ArgumentNullException.ThrowIfNull(secrets); + var keys = new Dictionary(StringComparer.Ordinal); + try + { + using var ring = JsonDocument.Parse(secrets.GetSecret(KeyRingSecret) ?? throw Refused()); + var root = ring.RootElement; + if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Count() != 2 + || !root.TryGetProperty("active", out var active) || active.ValueKind != JsonValueKind.String + || !root.TryGetProperty("keys", out var entries) || entries.ValueKind != JsonValueKind.Object) + { + throw Refused(); + } + + foreach (var entry in entries.EnumerateObject()) + { + if (!DataRequestLimits.IsKeyVersion(entry.Name) || entry.Value.ValueKind != JsonValueKind.String + || keys.Count == DataRequestLimits.MaximumKeyVersions) + { + throw Refused(); + } + + var key = Convert.FromBase64String(entry.Value.GetString()!); + if (key.Length != DataRequestLimits.KeyBytes || !keys.TryAdd(entry.Name, key) + || keys.Where(other => !ReferenceEquals(other.Value, key)) + .Any(other => CryptographicOperations.FixedTimeEquals(other.Value, key))) + { + CryptographicOperations.ZeroMemory(key); + throw Refused(); + } + } + + ActiveKeyVersion = active.GetString()!; + if (keys.Count < 1 || !keys.ContainsKey(ActiveKeyVersion)) + { + throw Refused(); + } + + _keys = keys.ToFrozenDictionary(StringComparer.Ordinal); + } + catch (Exception failure) when (failure is JsonException or FormatException or InvalidOperationException + or ArgumentException or KeyNotFoundException) + { + foreach (var key in keys.Values) + { + CryptographicOperations.ZeroMemory(key); + } + + throw Refused(); + } + } + + /// The label new chunks are sealed under; a label, never key material. + public string ActiveKeyVersion { get; } = string.Empty; + + /// Seals one chunk of at most under the active key. + /// The chunk is empty or too large, or the cipher is disposed. + public DataExportSealedChunk Seal(DataExportChunkBinding binding, ReadOnlySpan plaintext) + { + ArgumentNullException.ThrowIfNull(binding); + ObjectDisposedException.ThrowIf(_disposed, this); + if (plaintext.Length is < 1 or > DataRequestLimits.ChunkPlaintextBytes) + { + throw Refused(); + } + + var nonce = RandomNumberGenerator.GetBytes(DataRequestLimits.NonceBytes); + var ciphertext = new byte[plaintext.Length]; + var tag = new byte[DataRequestLimits.TagBytes]; + using var cipher = new AesGcm(_keys[ActiveKeyVersion], DataRequestLimits.TagBytes); + cipher.Encrypt(nonce, plaintext, ciphertext, tag, AssociatedData(binding, ActiveKeyVersion)); + return new DataExportSealedChunk(ActiveKeyVersion, nonce, ciphertext, tag); + } + + /// Opens one sealed chunk; the caller owns the returned plaintext and overwrites it when done. + /// + /// The key version is unknown, a length is wrong, or authentication failed: the chunk was moved, altered or + /// sealed under a different binding. + /// + public byte[] Open(DataExportChunkBinding binding, DataExportSealedChunk chunk) + { + ArgumentNullException.ThrowIfNull(binding); + ArgumentNullException.ThrowIfNull(chunk); + ObjectDisposedException.ThrowIf(_disposed, this); + if (chunk.KeyVersion is null || !_keys.TryGetValue(chunk.KeyVersion, out var key) + || chunk.Nonce is not { Length: DataRequestLimits.NonceBytes } || chunk.Tag is not { Length: DataRequestLimits.TagBytes } + || chunk.Ciphertext is not { Length: >= 1 and <= DataRequestLimits.ChunkPlaintextBytes }) + { + throw Refused(); + } + + var plaintext = new byte[chunk.Ciphertext.Length]; + try + { + using var cipher = new AesGcm(key, DataRequestLimits.TagBytes); + cipher.Decrypt(chunk.Nonce, chunk.Ciphertext, chunk.Tag, plaintext, AssociatedData(binding, chunk.KeyVersion)); + return plaintext; + } + catch (CryptographicException) + { + CryptographicOperations.ZeroMemory(plaintext); + throw Refused(); + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + foreach (var key in _keys.Values) + { + CryptographicOperations.ZeroMemory(key); + } + } + + public override string ToString() => nameof(DataExportCipher); + + /// The associated data: format, key version, tenant, request, artifact, index and count. + internal static byte[] AssociatedData(DataExportChunkBinding binding, string keyVersion) + { + if (!DataRequestLimits.IsKeyVersion(keyVersion)) + { + throw Refused(); + } + + var label = Encoding.ASCII.GetBytes(keyVersion); + var data = new byte[1 + 1 + label.Length + 16 + 16 + 16 + 4 + 4]; + var span = data.AsSpan(); + span[0] = FormatVersion; + span[1] = (byte)label.Length; + label.CopyTo(span[2..]); + var offset = 2 + label.Length; + binding.TenantId.TryWriteBytes(span.Slice(offset, 16), bigEndian: true, out _); + binding.RequestId.TryWriteBytes(span.Slice(offset + 16, 16), bigEndian: true, out _); + binding.ArtifactId.TryWriteBytes(span.Slice(offset + 32, 16), bigEndian: true, out _); + BinaryPrimitives.WriteInt32BigEndian(span.Slice(offset + 48, 4), binding.Index); + BinaryPrimitives.WriteInt32BigEndian(span.Slice(offset + 52, 4), binding.Count); + return data; + } + + private static InvalidOperationException Refused() => new("Data export custody unavailable."); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs new file mode 100644 index 00000000..bcef6ba1 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs @@ -0,0 +1,57 @@ +using System.Collections.Immutable; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// One collection of an export bundle that stopped at its section cap: how many records the bundle +/// holds and how many there were (ADR-0107 § 3). +/// +/// +/// The bundle states it under truncated and the artifact's receipt keeps the same statement, so a +/// capped audit section is disclosed both to the person who reads the bundle and to anyone who reads the +/// receipt. It names a collection and two counts, never a value or an identifier. +/// +public sealed record DataExportTruncation +{ + /// The key is not participant.collection or the counts are inconsistent. + public DataExportTruncation(string collection, long included, long total) + { + if (!DataRequestLimits.IsTruncationKey(collection)) + { + throw new ArgumentException("A truncation names one section collection.", nameof(collection)); + } + + if (included < 0 || total < 0 || included > total || total > DataRequestLimits.MaximumTruncationCount) + { + throw new ArgumentException("A truncation's included records are at most its total.", nameof(included)); + } + + Collection = collection; + Included = included; + Total = total; + } + + /// participant.collection. + public string Collection { get; } + + public long Included { get; } + + public long Total { get; } + + /// + /// Validates and orders a set of truncations ordinally by collection, refusing a repeated + /// collection or more than . + /// + /// The set is malformed. + public static ImmutableArray Normalize(IEnumerable? truncations) + { + var items = (truncations ?? []).ToImmutableArray(); + if (items.Any(item => item is null) || items.Length > DataRequestLimits.MaximumTruncatedCollections + || items.Select(item => item.Collection).Distinct(StringComparer.Ordinal).Count() != items.Length) + { + throw new ArgumentException("A bundle states each truncated collection once, within the bound.", nameof(truncations)); + } + + return [.. items.OrderBy(item => item.Collection, StringComparer.Ordinal)]; + } +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs index b1b08ea6..c53dd0bf 100644 --- a/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs @@ -59,6 +59,49 @@ public static class DataRequestLimits /// The longest participant key. public const int MaximumParticipantKeyLength = 32; + /// The smallest bundle ceiling the setting may name; below it the bundle envelope alone would not fit. + public const long MinimumBundleBytes = 1L * 1024 * 1024; + + /// + /// The bytes of the bundle ceiling held back for the envelope's closing structure: the remaining + /// empty sections, the truncation statement and the closing braces, so the finished document never + /// exceeds the ceiling a record was admitted under. + /// + public const int BundleTailReserveBytes = 16 * 1024; + + /// The longest collection name inside one export section. + public const int MaximumCollectionNameLength = 32; + + /// + /// The most truncated collections one bundle, and so one artifact's receipt, may state + /// (ADR-0107 § 3); the receipt column's CHECK repeats it. + /// + public const int MaximumTruncatedCollections = 32; + + /// The largest record count a truncation statement may carry: JSON's exact-integer range. + public const long MaximumTruncationCount = 9_007_199_254_740_991; + + /// Whether a collection name is a closed lower snake_case token of the bounded length. + public static bool IsCollectionName(string? name) => + name is { Length: > 0 and <= MaximumCollectionNameLength } + && name[0] is >= 'a' and <= 'z' + && name.All(character => character is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'); + + /// + /// Whether a truncation key names one collection of one section: participant.collection, each half + /// a closed token, so the receipt names a collection and never a value. + /// + public static bool IsTruncationKey(string? key) + { + if (key is null) + { + return false; + } + + var separator = key.IndexOf('.', StringComparison.Ordinal); + return separator > 0 && IsParticipantKey(key[..separator]) && IsCollectionName(key[(separator + 1)..]); + } + /// The number of chunks a bundle of plaintext bytes occupies. /// The bundle is empty or above the largest ceiling. public static int ChunkCountFor(long byteCount) => diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs index de5e92f6..f1574995 100644 --- a/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs @@ -1,3 +1,4 @@ +using System.Collections.Immutable; using LearnStack.SharedKernel.Identifiers; namespace LearnStack.SharedKernel.DataProtection; @@ -8,8 +9,8 @@ namespace LearnStack.SharedKernel.DataProtection; /// /// /// -/// A port with its default adapter still to land. The default is -/// PostgresDataExportArtifactStore in P03-10 Step 1: AES-256-GCM with a fresh 12-byte nonce +/// The default adapter is PostgresDataExportArtifactStore in the Identity module's +/// infrastructure, which owns the artifact tables: AES-256-GCM with a fresh 12-byte nonce /// per chunk, a key ring of one to four 32-byte keys under DataExport:KeyRing in /// ISecretProvider, associated data binding format and key version, tenant, request, /// artifact, chunk index and chunk count, at most @@ -40,7 +41,12 @@ Task PutAsync(DataExportArtifactPut put, Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken); /// Decrypts one chunk of an available, unexpired artifact. - Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, + /// + /// when the group holds no such artifact or chunk, or the artifact is revoked, + /// purged or past its expiry by the database clock, whether or not the purge ran. A chunk that fails + /// authentication is not an absence: it throws, because the stored ciphertext is corrupt or forged. + /// + Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, CancellationToken cancellationToken); /// @@ -48,7 +54,15 @@ Task ReadChunkAsync(DataExportArtifactLocator artifact /// (subject, administrator, newer export or erasure) or /// (expiry); the metadata row stays as the receipt. /// - Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, CancellationToken cancellationToken); + /// + /// Revocation is admitted only before the artifact's expiry and the purge only after it, both by the + /// database clock (ADR-0107 § 4). A revocation asked for once the expiry has passed purges instead, so a + /// caller that wants the chunks gone always gets them gone; a purge asked for before the expiry changes + /// nothing. Repeating either on an artifact that already holds no chunk changes nothing. + /// + /// The artifact's status afterwards, or when the group holds no such artifact. + Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken); } /// Names one artifact inside its group. @@ -78,7 +92,7 @@ public sealed record DataExportArtifactPut { /// A member is unassigned or the size is outside the supported range. public DataExportArtifactPut(Guid artifactId, Guid requestId, UserId subjectUserId, - DataRequestScopeGroup group, long byteCount) + DataRequestScopeGroup group, long byteCount, IEnumerable? truncations = null) { ArgumentNullException.ThrowIfNull(group); if (artifactId == Guid.Empty || requestId == Guid.Empty) @@ -92,6 +106,7 @@ public DataExportArtifactPut(Guid artifactId, Guid requestId, UserId subjectUser } ChunkCount = DataRequestLimits.ChunkCountFor(byteCount); + Truncations = DataExportTruncation.Normalize(truncations); ArtifactId = artifactId; RequestId = requestId; SubjectUserId = subjectUserId; @@ -110,12 +125,20 @@ public DataExportArtifactPut(Guid artifactId, Guid requestId, UserId subjectUser /// The chunk count the size implies. public int ChunkCount { get; } + /// The bundle's truncation statement, which the receipt keeps (ADR-0107 § 3); empty when nothing was capped. + public ImmutableArray Truncations { get; } + public override string ToString() => nameof(DataExportArtifactPut); } /// An artifact's receipt-safe metadata: no plaintext, no ciphertext, no key. +/// +/// is the stored lifecycle; adds the time check against the +/// database clock, so an artifact still stored available after its expiry is reported unreadable. +/// public sealed record DataExportArtifactMetadata(Guid ArtifactId, Guid RequestId, DataExportArtifactStatus Status, - long ByteCount, int ChunkCount, string KeyVersion, DateTimeOffset ExpiresAt, DateTimeOffset? PurgedAt); + long ByteCount, int ChunkCount, string KeyVersion, DateTimeOffset ExpiresAt, DateTimeOffset? PurgedAt, + ImmutableArray Truncations, bool IsReadable); /// One decrypted chunk of a ticketed download. /// The bytes are the subject's personal data; the type never prints them. diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportBundleBuilder.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportBundleBuilder.cs new file mode 100644 index 00000000..baad8221 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportBundleBuilder.cs @@ -0,0 +1,68 @@ +using System.Collections.Immutable; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// Builds one export bundle for a subject and group: one JSON document with a schema version, the request +/// identity, the generation time and one section per registered participant +/// (ADR-0107 § 3). +/// +/// +/// +/// The builder runs every participant's in registry order on the +/// caller's ambient tenant transaction, each into a bounded section writer. It holds the plaintext in fixed +/// chunk-sized segments, bounded by the bundle ceiling (DataExport:MaxBytes), because the artifact's +/// associated data binds the chunk count, which is not known until the last record is written; it never +/// encrypts, stores or logs the plaintext. +/// +/// +/// A ceiling hit is an outcome, not an exception: the result carries no bundle and the request ends +/// failed with export_too_large (ADR-0107 § 4). +/// +/// +public interface IDataExportBundleBuilder +{ + Task BuildAsync(UserDataSubject subject, DateTimeOffset generatedAt, CancellationToken cancellationToken); +} + +/// A built bundle or the ceiling refusal; exactly one is present. +public sealed record DataExportBundleResult +{ + private DataExportBundleResult(IDataExportBundle? bundle) => Bundle = bundle; + + /// The bundle passed DataExport:MaxBytes; no plaintext is retained. + public static DataExportBundleResult TooLarge { get; } = new((IDataExportBundle?)null); + + /// The bundle is missing. + public static DataExportBundleResult Built(IDataExportBundle bundle) => + new(bundle ?? throw new ArgumentNullException(nameof(bundle))); + + /// The bundle, which the caller owns and disposes; when . + public IDataExportBundle? Bundle { get; } + + public bool IsTooLarge => Bundle is null; + + public override string ToString() => IsTooLarge ? nameof(TooLarge) : nameof(Built); +} + +/// +/// A finished bundle's plaintext, held until it is stored. Disposing it overwrites every buffer with zeros. +/// +/// The plaintext is the subject's personal data; the type never prints it. +public interface IDataExportBundle : IDisposable +{ + /// The UTF-8 size of the whole document. + long ByteCount { get; } + + /// The chunk count the size implies (). + int ChunkCount { get; } + + /// The collections that stopped at their section cap, as the bundle states them. + ImmutableArray Truncations { get; } + + /// + /// The document in order, as chunks of exactly but the + /// last; each chunk is valid only until the bundle is disposed. + /// + IAsyncEnumerable> ReadChunksAsync(CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs index f12715f6..cf25a30a 100644 --- a/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs @@ -38,6 +38,14 @@ public interface IUserDataParticipant /// string Key { get; } + /// + /// The participant's own section cap in bytes, or for none beyond the bundle + /// ceiling. The audit section declares (ADR-0107 § 3); + /// a record that would pass it is refused with , and + /// the participant declares the truncation and stops. + /// + long? ExportSectionCapBytes => null; + /// Streams the participant's section of an export bundle into a bounded writer (ADR-0107 § 3). /// /// The writer belongs to this participant's section alone. A participant never builds the bundle, diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs new file mode 100644 index 00000000..bf70753d --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs @@ -0,0 +1,42 @@ +using System.Buffers; +using System.Text.Json; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// Writes one export record into a section through a short-lived pooled buffer that is overwritten with zeros +/// afterwards, so a participant never leaves a copy of the subject's data in a buffer it does not own. +/// +public static class UserDataExportRecord +{ + private static readonly JsonWriterOptions Options = new() { Indented = false, SkipValidation = false }; + + /// Serializes one JSON value with and appends it to . + /// The callback wrote no value, or more than one. + public static async ValueTask AppendAsync(IUserDataExportWriter writer, string collection, + Action write, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(write); + var buffer = new ArrayBufferWriter(1024); + try + { + using (var json = new Utf8JsonWriter(buffer, Options)) + { + write(json); + json.Flush(); + if (json.CurrentDepth != 0 || json.BytesCommitted == 0) + { + throw new InvalidOperationException("An export record is exactly one complete JSON value."); + } + } + + return await writer.AppendAsync(collection, buffer.WrittenMemory, cancellationToken).ConfigureAwait(false); + } + finally + { + // ArrayBufferWriter.Clear overwrites the written span; nothing is written beyond it. + buffer.Clear(); + } + } +} diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditPayloadProjection.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditPayloadProjection.cs new file mode 100644 index 00000000..6068c1fd --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditPayloadProjection.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace LearnStack.Modules.Audit.Infrastructure.DataRequests; + +/// +/// Rewrites a captured audit payload for a subject's export: every identifier becomes self when it is the +/// subject's own and third_party otherwise +/// (ADR-0107 § 3, +/// ADR-0106 § 5). +/// +/// +/// +/// Why every identifier. An export excludes internal identifiers, the subject's UserId included, and +/// replaces another person's reference with third_party. Without the locators of ADR-0108 § 7 (P03-10 +/// Step 2) a captured payload does not say which identifier names a person, so the projection treats each one as +/// a possible person reference: the subject's own become self, everything else third_party. It +/// discloses less than a locator-aware projection would, never more. Identifiers embedded in a longer string, the +/// instance-qualified changes paths included, are rewritten the same way, in values and in property names. +/// +/// +/// Values the capture already replaced with the redaction sentinel stay replaced; nothing else is changed. +/// +/// +public static partial class AuditPayloadProjection +{ + public const string Self = "self"; + public const string ThirdParty = "third_party"; + + /// Writes rewritten, or JSON null when there is no payload. + public static void Write(Utf8JsonWriter json, string? rawJson, IReadOnlySet own) + { + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(own); + if (rawJson is null) + { + json.WriteNullValue(); + return; + } + + using var document = JsonDocument.Parse(rawJson); + Write(json, document.RootElement, own); + } + + /// Rewrites every identifier embedded in . + public static string Rewrite(string value, IReadOnlySet own) => + Identifier().Replace(value, match => own.Contains(Guid.Parse(match.ValueSpan)) ? Self : ThirdParty); + + private static void Write(Utf8JsonWriter json, JsonElement element, IReadOnlySet own) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + json.WriteStartObject(); + foreach (var property in element.EnumerateObject()) + { + json.WritePropertyName(Rewrite(property.Name, own)); + Write(json, property.Value, own); + } + + json.WriteEndObject(); + break; + case JsonValueKind.Array: + json.WriteStartArray(); + foreach (var item in element.EnumerateArray()) + { + Write(json, item, own); + } + + json.WriteEndArray(); + break; + case JsonValueKind.String: + json.WriteStringValue(Rewrite(element.GetString()!, own)); + break; + default: + element.WriteTo(json); + break; + } + } + + [GeneratedRegex("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}", RegexOptions.CultureInvariant, 1000)] + private static partial Regex Identifier(); +} diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditUserDataParticipant.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditUserDataParticipant.cs new file mode 100644 index 00000000..4b017d77 --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditUserDataParticipant.cs @@ -0,0 +1,326 @@ +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Audit.Infrastructure.DataRequests; + +/// +/// The Audit module's part in subject data requests: it reads its own table, the subject's audit rows of the +/// request's scope, and never writes it +/// (ADR-0107 § 1, § 3, § 6). +/// +/// +/// +/// Selection. A row is the subject's when the subject is its actor, or its entity is the subject or one of +/// the request's frozen Memberships. Who asked decides the reach (ADR-0108 § 4): a self-requested export selects in +/// the whole tenant, an administrator-requested one only rows whose organization_id is the group's (none for +/// the tenant-wide group). Both read on the ambient tenant transaction as learnstack_app, so the audit row +/// policy still bounds what is visible: rows of another organization are visible only under a tenant-wide read. +/// +/// +/// What a record holds. The envelope (time, module, operation, outcome, entity type) and who acted, as +/// self, system or third_party; the address and user agent only of a row the subject acted in; +/// the payload columns only for a row about the subject's own Membership (and so its profile) or a consent the +/// subject recorded, rewritten by . Metadata, correlation, reason and every +/// identifier stay out. +/// +/// +/// Bounds. Newest first, keyset-paged on (timestamp, id), under the section's 8 MiB cap: a cap hit is +/// declared with the records included and the records in total. +/// +/// +public sealed class AuditUserDataParticipant(IUnitOfWork unit, ITenantContext tenant) : IUserDataParticipant +{ + public const string ParticipantKey = "audit"; + public const string Collection = "entries"; + private const int Page = 200; + + // One literal predicate: the subject as actor or entity, and the reach by origin. Every statement repeats it. + private const string Selection = """ + tenant_id = @tenant + AND (NOT @scoped OR organization_id IS NOT DISTINCT FROM @organization) + AND (actor_user_id = @subject + OR (entity_type = 'User' AND entity_id = @subject_text) + OR (entity_type = 'Membership' AND entity_id = ANY(@memberships))) + """; + + private const string CountSql = "SELECT count(*) FROM public.audit_log WHERE " + Selection; + + private const string PageSql = """ + SELECT id, "timestamp", module, operation, outcome, entity_type, entity_id, actor_user_id, + host(ip_address), user_agent, before_state, after_state, changes + FROM public.audit_log + WHERE (@first OR ("timestamp", id) < (@after_timestamp, @after_id)) + """ + " AND " + Selection + " " + """ + ORDER BY "timestamp" DESC, id DESC + LIMIT @page + """; + + private const string RetainedSql = """ + SELECT count(*) FILTER (WHERE actor_user_id = @subject), + count(*) FILTER (WHERE (entity_type = 'User' AND entity_id = @subject_text) + OR (entity_type = 'Membership' AND entity_id = ANY(@memberships))) + FROM public.audit_log + """ + " WHERE " + Selection; + + private const string MetadataSql = """ + SELECT count(*) FROM public.audit_log + WHERE tenant_id = @tenant + AND (NOT @scoped OR organization_id IS NOT DISTINCT FROM @organization) + AND (metadata ->> 'causal_actor_user_id' = @subject_text + OR metadata #>> '{authorization,causal_actor_user_id}' = @subject_text + OR metadata #>> '{provider_event,affected_user_id}' = @subject_text + OR COALESCE(metadata -> 'authorization' -> 'memberships', '[]'::jsonb) ?| @memberships) + """; + + public string Key => ParticipantKey; + + public long? ExportSectionCapBytes => DataRequestLimits.AuditSectionBytes; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(writer); + RequireGroup(subject); + long total; + await using (var count = Command(CountSql, subject)) + { + total = (long)(await ExecuteAsync(token => count.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false))!; + } + + var own = Own(subject); + long included = 0; + (DateTime Timestamp, Guid Id)? cursor = null; + while (true) + { + var rows = await ReadPageAsync(subject, cursor, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + var appended = await UserDataExportRecord.AppendAsync(writer, Collection, json => WriteRecord(json, row, subject, own), + cancellationToken).ConfigureAwait(false); + switch (appended) + { + case UserDataExportAppend.Appended: + included++; + break; + case UserDataExportAppend.SectionCapReached: + writer.DeclareTruncated(Collection, included, Math.Max(total, included)); + return; + default: + return; + } + } + + if (rows.Count < Page) + { + return; + } + + cursor = (rows[^1].Timestamp, rows[^1].Id); + } + } + + public async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + long actor; + long entity; + await using (var references = Command(RetainedSql, subject)) + { + (actor, entity) = await ExecuteAsync(async token => + { + await using var row = await references.ExecuteReaderAsync(token).ConfigureAwait(false); + return await row.ReadAsync(token).ConfigureAwait(false) ? (row.GetInt64(0), row.GetInt64(1)) : (0L, 0L); + }, cancellationToken).ConfigureAwait(false); + } + + long metadata; + await using (var command = Command(MetadataSql, subject)) + { + metadata = (long)(await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false))!; + } + + return + [ + new(RetainedReferenceKind.AuditActorReference, actor), + new(RetainedReferenceKind.AuditEntityReference, entity), + new(RetainedReferenceKind.AuditMetadataReference, metadata), + ]; + } + + /// Whether a row's payload columns may be disclosed: its entity is the subject's own Membership or a consent the subject recorded. + public static bool DisclosesPayload(AuditRow row, UserDataSubject subject) => + row.EntityType switch + { + "Membership" => row.EntityId is { } id && Guid.TryParseExact(id, "D", out var membership) + && subject.MembershipIds.Contains(membership), + "MembershipFieldConsent" => row.Actor == subject.SubjectUserId.Value, + _ => false, + }; + + /// The closed actor vocabulary of an exported row. + public static string? ActorOf(AuditRow row, UserDataSubject subject) => row.Actor switch + { + null => null, + { } actor when actor == subject.SubjectUserId.Value => AuditPayloadProjection.Self, + { } actor when actor == UserId.SystemActor.Value => "system", + _ => AuditPayloadProjection.ThirdParty, + }; + + public static void WriteRecord(Utf8JsonWriter json, AuditRow row, UserDataSubject subject, IReadOnlySet own) + { + json.WriteStartObject(); + json.WriteString("at", new DateTimeOffset(row.Timestamp, TimeSpan.Zero)); + json.WriteString("module", row.Module); + json.WriteString("operation", row.Operation); + json.WriteString("outcome", row.Outcome); + if (row.EntityType is null) + { + json.WriteNull("entity_type"); + } + else + { + json.WriteString("entity_type", row.EntityType); + } + + var actor = ActorOf(row, subject); + if (actor is null) + { + json.WriteNull("actor"); + } + else + { + json.WriteString("actor", actor); + } + + // The address and agent are the actor's: disclosed only when the actor is the subject. + if (actor == AuditPayloadProjection.Self) + { + WriteText(json, "ip_address", row.IpAddress); + WriteText(json, "user_agent", row.UserAgent); + } + + if (DisclosesPayload(row, subject)) + { + json.WriteStartObject("payload"); + json.WritePropertyName("before"); + AuditPayloadProjection.Write(json, row.BeforeState, own); + json.WritePropertyName("after"); + AuditPayloadProjection.Write(json, row.AfterState, own); + json.WritePropertyName("changes"); + AuditPayloadProjection.Write(json, row.Changes, own); + json.WriteEndObject(); + } + + json.WriteEndObject(); + } + + public static IReadOnlySet Own(UserDataSubject subject) => + new HashSet(subject.MembershipIds) { subject.SubjectUserId.Value }; + + private async Task> ReadPageAsync(UserDataSubject subject, (DateTime Timestamp, Guid Id)? cursor, + CancellationToken cancellationToken) + { + await using var command = Command(PageSql, subject); + command.Parameters.AddWithValue("first", cursor is null); + command.Parameters.AddWithValue("after_timestamp", NpgsqlDbType.TimestampTz, cursor?.Timestamp ?? DateTime.UnixEpoch); + command.Parameters.AddWithValue("after_id", cursor?.Id ?? Guid.Empty); + command.Parameters.AddWithValue("page", Page); + return await ExecuteAsync(async token => + { + var rows = new List(Page); + await using var reader = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + while (await reader.ReadAsync(token).ConfigureAwait(false)) + { + rows.Add(new AuditRow(reader.GetGuid(0), DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc), + reader.GetString(2), reader.GetString(3), reader.GetString(4), Text(reader, 5), Text(reader, 6), + reader.IsDBNull(7) ? null : reader.GetGuid(7), Text(reader, 8), Text(reader, 9), Text(reader, 10), + Text(reader, 11), Text(reader, 12))); + } + + return rows; + }, cancellationToken).ConfigureAwait(false); + } + + private NpgsqlCommand Command(string sql, UserDataSubject subject) + { + var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("scoped", subject.Origin != DataRequestOrigin.Self); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)subject.Group.OrganizationId?.Value ?? DBNull.Value); + command.Parameters.AddWithValue("subject", subject.SubjectUserId.Value); + command.Parameters.AddWithValue("subject_text", subject.SubjectUserId.Value.ToString("D")); + command.Parameters.Add(new NpgsqlParameter("memberships", NpgsqlDbType.Array | NpgsqlDbType.Text) + { + Value = subject.MembershipIds.Select(membership => membership.ToString("D")).ToArray(), + }); + return command; + } + + private async Task ExecuteAsync(Func> statement, CancellationToken cancellationToken) + { + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + return await statement(budget.Token).ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException + || failure is OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new InvalidOperationException("Audit export read unavailable."); + } + } + + private void RequireGroup(UserDataSubject subject) + { + if (subject.Group.TenantId != tenant.TenantId || subject.Group.OrganizationId != tenant.OrganizationId + || !unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A participant reads only the announced group of its request."); + } + } + + private static string? Text(NpgsqlDataReader reader, int ordinal) => reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); + + private static void WriteText(Utf8JsonWriter json, string name, string? value) + { + if (value is null) + { + json.WriteNull(name); + } + else + { + json.WriteString(name, value); + } + } + + /// One selected row, read and dropped page by page. + public sealed record AuditRow(Guid Id, DateTime Timestamp, string Module, string Operation, string Outcome, string? EntityType, + string? EntityId, Guid? Actor, string? IpAddress, string? UserAgent, string? BeforeState, string? AfterState, string? Changes) + { + public override string ToString() => nameof(AuditRow); + } +} + +/// Registers the Audit module's participant from its own boundary (ADR-0107 § 1). +public static class AuditDataRequestRegistration +{ + public static IServiceCollection AddAuditUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + return services; + } +} diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserDataParticipant.cs b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserDataParticipant.cs new file mode 100644 index 00000000..091a81aa --- /dev/null +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserDataParticipant.cs @@ -0,0 +1,62 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Customization.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Modules.Customization.Infrastructure.DataRequests; + +/// +/// The Customization module's part in subject data requests: describe-only. Its rows are tenant definitions, not +/// the person's data; the person appears only as creator, updater or deleter, reported as +/// attribution_reference (ADR-0107 § 1, § 6). +/// +/// +/// Its export section is empty: definitions are tenant settings and the export excludes them (ADR-0107 § 3). The +/// labels and classification of the person's own custom-field values are exported by Identity, through the exact +/// definition reader contract. Erasure is the default no-op. +/// +public sealed class CustomizationUserDataParticipant(CustomizationDbContext db, ITenantContext tenant) : IUserDataParticipant +{ + public string Key => "customization"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(writer); + RequireGroup(subject); + return Task.CompletedTask; + } + + public async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + return + [ + new(RetainedReferenceKind.AttributionReference, + await AttributionReferenceCounter.CountAsync(db, subject, null, cancellationToken).ConfigureAwait(false)), + ]; + } + + private void RequireGroup(UserDataSubject subject) + { + if (subject.Group.TenantId != tenant.TenantId || subject.Group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A participant reads only the announced group of its request."); + } + } +} + +/// Registers the Customization module's participant from its own boundary (ADR-0107 § 1). +public static class CustomizationDataRequestRegistration +{ + public static IServiceCollection AddCustomizationUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + return services; + } +} diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserDataParticipant.cs b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserDataParticipant.cs new file mode 100644 index 00000000..d19754b5 --- /dev/null +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserDataParticipant.cs @@ -0,0 +1,61 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Education.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Modules.Education.Infrastructure.DataRequests; + +/// +/// The Education module's part in subject data requests: describe-only. Courses and lessons are tenant content; +/// the person appears only as their creator, updater or deleter, reported as attribution_reference +/// (ADR-0107 § 1, § 6). +/// +/// +/// Its export section is empty: no Education table holds the person's own data yet. Phase 07's first +/// learner-behaviour writer extends this participant before it ships (ADR-0107 § 1). Erasure is the default no-op. +/// +public sealed class EducationUserDataParticipant(EducationDbContext db, ITenantContext tenant) : IUserDataParticipant +{ + public string Key => "education"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(writer); + RequireGroup(subject); + return Task.CompletedTask; + } + + public async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + return + [ + new(RetainedReferenceKind.AttributionReference, + await AttributionReferenceCounter.CountAsync(db, subject, null, cancellationToken).ConfigureAwait(false)), + ]; + } + + private void RequireGroup(UserDataSubject subject) + { + if (subject.Group.TenantId != tenant.TenantId || subject.Group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A participant reads only the announced group of its request."); + } + } +} + +/// Registers the Education module's participant from its own boundary (ADR-0107 § 1). +public static class EducationDataRequestRegistration +{ + public static IServiceCollection AddEducationUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + return services; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataExportJobContracts.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataExportJobContracts.cs new file mode 100644 index 00000000..c8e15f0f --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataExportJobContracts.cs @@ -0,0 +1,13 @@ +using LearnStack.SharedKernel.Jobs; + +namespace LearnStack.Modules.Identity.Application.Contracts.DataRequests; + +/// +/// The export job's only input: the request it fulfils +/// (ADR-0107 § 2). +/// The group, the subject and the snapshot are read from the request row, never from the job. +/// +public sealed record DataExportJobParameters(Guid RequestId) : IBackgroundJobParameters; + +/// The delayed purge job's only input: the artifact whose chunks expire (ADR-0107 § 2, § 4). +public sealed record DataExportPurgeParameters(Guid ArtifactId) : IBackgroundJobParameters; 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 c8f8c949..546ef8e6 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 @@ -2,6 +2,7 @@ using LearnStack.Modules.Identity.Application.Contracts.CustomFields; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; +using LearnStack.Modules.Identity.Application.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Seeding; using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Memberships; @@ -35,6 +36,15 @@ public void Describe(IAuditCatalogBuilder builder) builder.MustAudit("identity.invitation.prepare_email", OperationType.SecurityEvent, typeof(Invitation)); builder.MustAudit("identity.invitation.email_submission", OperationType.SecurityEvent, typeof(Invitation)); builder.MustAudit("identity.invitation.email_submission", OperationType.SecurityEvent, typeof(Invitation)); + // ADR-0106 § 13, ADR-0107 § 2: an export's fulfilment is one row about the request and one about the artifact + // it stored (the revoked earlier artifact travels in that row's changes); the purge is one row about the + // artifact. A recorded no-op writes the rows with no subject. + builder.MustAudit("identity.data_request.fulfill_export", OperationType.SecurityEvent, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_export.store", OperationType.SecurityEvent, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_request.fulfill_export", OperationType.SecurityEvent, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_export.store", OperationType.SecurityEvent, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_export.purge", OperationType.Delete, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_export.purge", OperationType.Delete, typeof(DataExportArtifact)); builder.MustAudit(IdentityOperationPolicySource.NativeSessionAdmissionOperation, OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs new file mode 100644 index 00000000..93feff96 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs @@ -0,0 +1,214 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +public sealed record RunTenantDataExportCommand(DataExportJobParameters Parameters) : IRequest>; +public sealed record RunOrganizationDataExportCommand(DataExportJobParameters Parameters) : IRequest>; +public sealed record PurgeTenantDataExportCommand(DataExportPurgeParameters Parameters) : IRequest>; +public sealed record PurgeOrganizationDataExportCommand(DataExportPurgeParameters Parameters) : IRequest>; + +/// +/// The four transactional roots of the export workflow +/// (ADR-0107 § 2–§ 4): +/// scope-specific declarations sharing one mechanic, run as the system actor under the trusted job policy on the +/// job's own tenant transaction, never in the platform scope. +/// +/// +/// +/// One transaction. The transactional runtime owns exactly one transaction per root, so the export takes +/// requested → fulfilling and then fulfilling → completed (or failed) as separate UPDATEs of +/// that one transaction, each one arrow and one row-version step as the request guard requires. A failure rolls +/// every write back, the request is requested again and the runtime's retry re-runs the whole export, so a +/// retried or resumed job never stores twice; a commit stores the request, its artifact, every chunk and the +/// purge job together. +/// +/// +/// Recorded no-ops. The runtime has no cancel call, so a job whose request is missing, of another kind, +/// cancelled or already terminal completes without changing anything, and its MUST row records that it ran. +/// +/// +/// Fences. The run holds the Identity tenant fence shared from its first read, which the request guard +/// requires of every request write and which orders it against a tenant erasure taking the same fence exclusively +/// (ADR-0107 § 5): an erasure either cancels a still requested export first, or finds it completed and revokes +/// its artifact. +/// +/// +public sealed class DataExportJobHandlers(IDataRequestStore store, IIdentityMutationLocks locks, ITenantContext tenant, + IAuditSubject audit, IClock clock, IGuidFactory ids, IDataExportBundleBuilder bundles, IUserDataParticipantRegistry participants, + IDataExportArtifactStore artifacts, IDataRequestFulfillmentScheduler scheduler) + : IRequestHandler>, + IRequestHandler>, + IRequestHandler>, + IRequestHandler> +{ + public Task> Handle(RunTenantDataExportCommand request, CancellationToken cancellationToken) => + ExportAsync(request.Parameters, cancellationToken); + + public Task> Handle(RunOrganizationDataExportCommand request, CancellationToken cancellationToken) => + ExportAsync(request.Parameters, cancellationToken); + + public Task> Handle(PurgeTenantDataExportCommand request, CancellationToken cancellationToken) => + PurgeAsync(request.Parameters, cancellationToken); + + public Task> Handle(PurgeOrganizationDataExportCommand request, CancellationToken cancellationToken) => + PurgeAsync(request.Parameters, cancellationToken); + + private async Task> ExportAsync(DataExportJobParameters parameters, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + _ = store.RequireCurrentJob(); + if (parameters.RequestId == Guid.Empty || parameters.RequestId.Version != 7) + { + return Done(); + } + + await locks.AcquireAsync(new IdentityMutationLockPlan([], tenant.TenantId, IdentityTenantLockMode.Shared), cancellationToken) + .ConfigureAwait(false); + var request = await store.FindLockedAsync(DataSubjectRequestId.From(parameters.RequestId), cancellationToken) + .ConfigureAwait(false); + if (request is null) + { + return Done(); + } + + audit.Designate(request); + if (request.Kind != DataRequestKind.Export || request.Status is not (DataRequestStatus.Requested or DataRequestStatus.Fulfilling)) + { + return Done(); + } + + var now = clock.UtcNow; + var actor = tenant.UserId ?? UserId.SystemActor; + if (request.Status == DataRequestStatus.Requested) + { + Require(request.StartFulfilling(now, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + } + + // Only an earlier transaction of this same request can have stored its artifact; the one-artifact-per-request + // index makes that the request's artifact, so a resumed run completes instead of storing a second bundle. + if (await store.FindArtifactOfRequestAsync(request.Id, cancellationToken).ConfigureAwait(false) is null) + { + var subject = new UserDataSubject(request.Id.Value, request.Kind, request.Origin, request.SubjectUserId, + request.Group, request.SnapshotMembershipIds.Select(membership => membership.Value)); + var built = await bundles.BuildAsync(subject, now, cancellationToken).ConfigureAwait(false); + if (built.IsTooLarge) + { + Require(request.Fail(DataRequestFailureReason.ExportTooLarge, now, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return Done(); + } + + using var bundle = built.Bundle!; + await StoreAsync(request, bundle, now, cancellationToken).ConfigureAwait(false); + } + + foreach (var participant in participants.Participants) + { + var before = request.Version; + Require(request.RecordParticipantCompleted(participant.Key, now, actor)); + if (request.Version != before) + { + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + } + } + + var retained = await DescribeRetainedAsync(request, cancellationToken).ConfigureAwait(false); + Require(request.Complete(retained, now, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return Done(); + } + + /// + /// Revokes the subject's earlier available artifact in the group, then stores the new one and schedules its purge + /// at its expiry: a subject holds at most one available artifact per group (ADR-0107 § 4). + /// + private async Task StoreAsync(DataSubjectRequest request, IDataExportBundle bundle, DateTimeOffset now, + CancellationToken cancellationToken) + { + foreach (var earlier in await store.FindAvailableArtifactsAsync(request.SubjectUserId, cancellationToken).ConfigureAwait(false)) + { + var outcome = await artifacts.PurgeAsync(new DataExportArtifactLocator(earlier.Value, request.Group), + DataExportArtifactStatus.Revoked, cancellationToken).ConfigureAwait(false); + if (outcome is not (DataExportArtifactStatus.Revoked or DataExportArtifactStatus.Purged)) + { + throw new InvalidOperationException("An earlier export artifact could not be withdrawn."); + } + } + + var artifactId = ids.NewUuidV7(); + if (artifactId == Guid.Empty || artifactId.Version != 7) + { + throw new InvalidOperationException("The identity factory must return a UUIDv7."); + } + + var stored = await artifacts.PutAsync(new DataExportArtifactPut(artifactId, request.Id.Value, request.SubjectUserId, + request.Group, bundle.ByteCount, bundle.Truncations), bundle.ReadChunksAsync(cancellationToken), cancellationToken) + .ConfigureAwait(false); + if (stored.ArtifactId != artifactId || stored.RequestId != request.Id.Value || stored.ExpiresAt <= now) + { + throw new InvalidOperationException("The stored export artifact does not match its request."); + } + + await scheduler.SchedulePurgeAsync(DataExportArtifactId.From(artifactId), stored.ExpiresAt, cancellationToken) + .ConfigureAwait(false); + } + + /// Every participant's retained references for the subject and group, summed per closed kind (ADR-0107 § 6). + private async Task> DescribeRetainedAsync(DataSubjectRequest request, + CancellationToken cancellationToken) + { + var subject = new UserDataSubject(request.Id.Value, request.Kind, request.Origin, request.SubjectUserId, + request.Group, request.SnapshotMembershipIds.Select(membership => membership.Value)); + var totals = new SortedDictionary(); + foreach (var participant in participants.Participants) + { + foreach (var retained in await participant.DescribeRetainedAsync(subject, cancellationToken).ConfigureAwait(false)) + { + totals[retained.Kind] = checked(totals.GetValueOrDefault(retained.Kind) + retained.Count); + } + } + + return [.. totals.Select(total => new RetainedReferenceCount(total.Key, total.Value))]; + } + + private async Task> PurgeAsync(DataExportPurgeParameters parameters, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + _ = store.RequireCurrentJob(); + if (parameters.ArtifactId == Guid.Empty || parameters.ArtifactId.Version != 7) + { + return Done(); + } + + var group = new DataRequestScopeGroup(tenant.TenantId, tenant.OrganizationId); + var outcome = await artifacts.PurgeAsync(new DataExportArtifactLocator(parameters.ArtifactId, group), + DataExportArtifactStatus.Purged, cancellationToken).ConfigureAwait(false); + + // Absent, revoked or purged: nothing is left to purge. Still available means the database clock has not reached + // the expiry the job was scheduled for; the runtime retries rather than leave the chunks behind. + return outcome == DataExportArtifactStatus.Available + ? throw new InvalidOperationException("The export artifact is not yet due for purge.") + : Done(); + } + + /// A transition refused here is a programming error: every precondition was checked under the row lock. + private static void Require(Result transition) + { + if (transition.IsFailure) + { + throw new InvalidOperationException("A data request transition that its own preconditions admitted was refused."); + } + } + + private static Result Done() => Result.Ok(None.Value); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs new file mode 100644 index 00000000..5f9cd2f7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs @@ -0,0 +1,90 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// Stores failed with execution_failed for a request whose fulfilment job is dead +/// (ADR-0106 § 8). +/// +/// +/// +/// Why it exists. ADR-0106 § 8 reads failed from the job phase, so no hook runs in a dead job; but +/// the one-active partial unique index frees a group's slot only for a stored terminal status. A person +/// whose export's job died could otherwise never file another. The creation path calls this before it inserts, +/// and the receipt displays the same answer without writing through . +/// +/// +/// Transitions, one per save. A dead export's request is requested (its transactional job rolled every +/// write back), so it takes requested → fulfilling and then fulfilling → failed as two saves, because +/// the request guard admits one arrow per UPDATE; both are the aggregate's own transitions. It runs on the +/// caller's tenant transaction under the shared Identity tenant fence that guard requires. +/// +/// +public sealed class DataRequestFailureReconciler(IDataRequestStore store, IDataRequestJobPhaseReader phases, + IIdentityMutationLocks locks, ITenantContext tenant, IClock clock) +{ + /// + /// The status a receipt shows: the stored one, or failed for a non-terminal request whose job is dead. + /// + public static DataRequestStatus EffectiveStatus(DataSubjectRequest request, DataRequestJobPhase phase) + { + ArgumentNullException.ThrowIfNull(request); + return !request.IsTerminal && phase == DataRequestJobPhase.Dead && CanFail(request) + ? DataRequestStatus.Failed + : request.Status; + } + + /// + /// Stores failed for a tracked, non-terminal request whose job is dead. + /// + /// + /// The caller loads the request through on its own group + /// transaction, so the row is locked against a job that is, after all, still committing. + /// + /// Whether the request was moved to failed. + public async Task ReconcileAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (request.IsTerminal || !CanFail(request) || request.TenantId != tenant.TenantId + || request.OrganizationId != tenant.OrganizationId) + { + return false; + } + + if (await phases.ReadAsync(request, cancellationToken).ConfigureAwait(false) != DataRequestJobPhase.Dead) + { + return false; + } + + await locks.AcquireAsync(new IdentityMutationLockPlan([], tenant.TenantId, IdentityTenantLockMode.Shared), cancellationToken) + .ConfigureAwait(false); + var now = clock.UtcNow; + var actor = tenant.UserId ?? UserId.SystemActor; + if (request.Status == DataRequestStatus.Requested) + { + Require(request.StartFulfilling(now, actor).IsSuccess); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + } + + Require(request.Fail(DataRequestFailureReason.ExecutionFailed, now, actor).IsSuccess); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return true; + } + + /// Only an export has a fulfilment job in this step, and only a requested or fulfilling one can fail. + private static bool CanFail(DataSubjectRequest request) => + request.Kind == DataRequestKind.Export && request.Status is DataRequestStatus.Requested or DataRequestStatus.Fulfilling; + + private static void Require(bool admitted) + { + if (!admitted) + { + throw new InvalidOperationException("A failure transition its own preconditions admitted was refused."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs new file mode 100644 index 00000000..c0f8c57c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs @@ -0,0 +1,79 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The four transactional definitions of the export workflow, one per purpose and scope group +/// (ADR-0107 § 2). +/// The erasure definitions are Step 2's. +/// +public static class DataExportJobKeys +{ + public static BackgroundJobKey TenantExport { get; } = new("identity.data_export_tenant.v1"); + public static BackgroundJobKey OrganizationExport { get; } = new("identity.data_export_organization.v1"); + public static BackgroundJobKey TenantPurge { get; } = new("identity.data_export_purge_tenant.v1"); + public static BackgroundJobKey OrganizationPurge { get; } = new("identity.data_export_purge_organization.v1"); + + /// The export definition of a group. + public static BackgroundJobKey ExportFor(DataRequestScopeGroup group) + { + ArgumentNullException.ThrowIfNull(group); + return group.IsTenantWide ? TenantExport : OrganizationExport; + } +} + +/// +/// Submits a data request's fulfilment work on the caller's own transaction +/// (ADR-0107 § 2). +/// +/// +/// The request's creation calls inside the transaction that inserts the request, so the +/// row and its job commit together or not at all; the job's tenant, organization and producer come from that +/// transaction's trusted enrollment, never from this call. +/// +public interface IDataRequestFulfillmentScheduler +{ + /// Submits the job of the request's kind and group; only an export has one in this step. + /// + /// The request is not a requested export of the announced group: a programming error, because the creation + /// path decides the kind and the group before it submits. + /// + ValueTask SubmitAsync(DataSubjectRequest request, CancellationToken cancellationToken); + + /// Schedules the purge of an artifact's chunks at , its expiry (ADR-0107 § 4). + ValueTask SchedulePurgeAsync(DataExportArtifactId artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken); +} + +/// The default , over the typed job scheduler. +public sealed class DataRequestFulfillmentScheduler(IBackgroundJobScheduler scheduler, ITenantContext tenant) + : IDataRequestFulfillmentScheduler +{ + public async ValueTask SubmitAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (request.Kind != DataRequestKind.Export || request.Status != DataRequestStatus.Requested + || request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Only a requested export of the announced group has a fulfilment job in this step."); + } + + await scheduler.EnqueueAsync(DataExportJobKeys.ExportFor(request.Group), + new DataExportJobParameters(request.Id.Value), cancellationToken).ConfigureAwait(false); + } + + public async ValueTask SchedulePurgeAsync(DataExportArtifactId artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) + { + if (artifactId.Value == Guid.Empty || artifactId.Value.Version != 7 || dueAt == default) + { + throw new InvalidOperationException("A purge is scheduled for an artifact at its expiry."); + } + + var key = tenant.OrganizationId is null ? DataExportJobKeys.TenantPurge : DataExportJobKeys.OrganizationPurge; + await scheduler.ScheduleAsync(key, new DataExportPurgeParameters(artifactId.Value), dueAt, cancellationToken) + .ConfigureAwait(false); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs new file mode 100644 index 00000000..e779fe05 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs @@ -0,0 +1,61 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The data request rows of the ambient group, read and written on the ambient tenant transaction as +/// learnstack_app (ADR-0106 § 8). +/// +/// +/// Every read is confined to the announced tenant and organization, by the predicate and by the row policy, so a +/// request or artifact of another group is absent rather than refused. Writes go through tracked aggregates only: +/// each transition is saved on its own, because the request and artifact guards admit exactly one arrow and one +/// row-version step per UPDATE. +/// +public interface IDataRequestStore +{ + /// The executing data-request job: refuses a caller that is not one of the module's job roots. + BackgroundJobId RequireCurrentJob(); + + /// The request in the ambient group, locked for update; when absent. + Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken); + + /// Whether the request already has its artifact (at most one per request). + Task FindArtifactOfRequestAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken); + + /// The subject's artifacts in the ambient group that are still stored available. + Task> FindAvailableArtifactsAsync(UserId subject, CancellationToken cancellationToken); + + /// Saves the changes of a request this scope loaded and tracks. + Task SaveAsync(DataSubjectRequest request, CancellationToken cancellationToken); +} + +/// +/// Where a data request's fulfilment job stands, read from the job's own row +/// (ADR-0106 § 8). +/// +public enum DataRequestJobPhase +{ + /// No fulfilment job of the request is visible in its group. + Unavailable = 1, + + /// Queued, running or retrying: the job may still finish. + Pending = 2, + + /// The job finished with its business outcome committed. + Completed = 3, + + /// Quarantined or dead-lettered: the job ends without a business outcome and runs no hook. + Dead = 4, +} + +/// +/// Reads the phase of a request's fulfilment job without writing anything, so a receipt can show failed +/// for a dead job before the reconciler has stored it. +/// +public interface IDataRequestJobPhaseReader +{ + Task ReadAsync(DataSubjectRequest request, CancellationToken cancellationToken); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/MembershipFieldRevisionReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/MembershipFieldRevisionReader.cs new file mode 100644 index 00000000..86d4a51c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/MembershipFieldRevisionReader.cs @@ -0,0 +1,40 @@ +using LearnStack.Modules.Customization.Application.Contracts.CustomFields; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// The pinned revision of one stored custom-field value: its labels and classification (ADR-0107 § 3). +public sealed record MembershipFieldRevision(Guid DefinitionId, int SchemaVersion, IReadOnlyDictionary Labels, + PersonalDataCategory Classification) +{ + public override string ToString() => nameof(MembershipFieldRevision); +} + +/// +/// Reads the exact revisions a Membership's stored custom-field values are pinned to, through Customization's +/// application contract, so the export names each value's definition revision, labels and classification. +/// +/// +/// The contract is the sanctioned cross-module read (ADR-0010); Identity's infrastructure reaches it only through +/// this application service. A revision that is no longer readable is simply absent, and the value is still +/// exported, because a missing label is not a reason to withhold the person's own data. +/// +public sealed class MembershipFieldRevisionReader(IExactCustomFieldDefinitionReader definitions) +{ + public async Task> ReadAsync(IReadOnlyCollection values, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(values); + if (values.Count == 0) + { + return []; + } + + var revisions = await definitions.ReadBatchAsync( + values.Select(value => new CustomFieldDefinitionPin(value.DefinitionId, value.SchemaVersion)).ToArray(), + CustomFieldResolution.ExistingPin, null, cancellationToken).ConfigureAwait(false); + return [.. revisions.Select(revision => new MembershipFieldRevision(revision.DefinitionId, revision.SchemaVersion, + revision.Labels, revision.PiiCategory))]; + } +} 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 2051c359..18ee8a57 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -8,6 +8,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Federation; using LearnStack.Modules.Identity.Domain; using LearnStack.Modules.Identity.Application.Invitations; +using LearnStack.Modules.Identity.Application.DataRequests; using LearnStack.SharedKernel.Permissions; namespace LearnStack.Modules.Identity.Application; @@ -60,6 +61,10 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("identity.invitation.prepare_organization_email", AuthorizationSourceKind.BackgroundJob), OperationPolicy.ForTrusted("identity.invitation.tenant_email_submission", AuthorizationSourceKind.BackgroundJob), OperationPolicy.ForTrusted("identity.invitation.organization_email_submission", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForTrusted("identity.data_request.fulfill_tenant_export", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForTrusted("identity.data_request.fulfill_organization_export", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForTrusted("identity.data_export.purge_tenant", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForTrusted("identity.data_export.purge_organization", AuthorizationSourceKind.BackgroundJob), OperationPolicy.ForProtected("identity.invitation.list", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected("identity.invitation.read", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected("identity.invitation.list_invitable_roles", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs index bc52f2ce..1ce41fc8 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs @@ -1,3 +1,4 @@ +using System.Collections.Immutable; using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Domain; using LearnStack.SharedKernel.Identifiers; @@ -52,15 +53,32 @@ private DataExportArtifact() { } /// When the chunks were deleted, by revocation or by the purge. public DateTimeOffset? PurgedAt { get; private set; } + /// + /// The bundle's truncation statement as canonical JSON, set at creation and never changed: the receipt + /// says a section was capped exactly as the bundle does (ADR-0107 § 3). {} when nothing was capped. + /// + public string TruncationJson { get; private set; } = DataRequestDocuments.EmptyObject; + + public ImmutableArray Truncations => DataRequestDocuments.ReadTruncation(TruncationJson); + /// /// Records the artifact of an export that is fulfilling: the group and subject come from the request, /// never from the caller. /// public static Result Create(DataExportArtifactId id, DataSubjectRequest request, long byteCount, - string keyVersion, DateTimeOffset at, UserId actor) + string keyVersion, DateTimeOffset at, UserId actor) => + Create(id, request, byteCount, keyVersion, [], at, actor); + + /// + /// Records the artifact of an export that is fulfilling, with the bundle's truncation statement. + /// + public static Result Create(DataExportArtifactId id, DataSubjectRequest request, long byteCount, + string keyVersion, IReadOnlyCollection truncations, DateTimeOffset at, UserId actor) { ArgumentNullException.ThrowIfNull(request); - if (!StronglyTypedId.IsAssigned(id) || id.Value.Version != 7 + ArgumentNullException.ThrowIfNull(truncations); + var truncation = DataRequestDocuments.WriteTruncation(truncations); + if (truncation is null || !StronglyTypedId.IsAssigned(id) || id.Value.Version != 7 || request.Kind != DataRequestKind.Export || request.Status != DataRequestStatus.Fulfilling || request.IsDeleted || byteCount is < 1 or > DataRequestLimits.MaximumBundleBytes || !DataRequestLimits.IsKeyVersion(keyVersion) || !StronglyTypedId.IsAssigned(actor) || at == default || at.Offset != TimeSpan.Zero @@ -80,6 +98,7 @@ public static Result Create(DataExportArtifactId id, DataSub ByteCount = byteCount, ChunkCount = DataRequestLimits.ChunkCountFor(byteCount), KeyVersion = keyVersion, + TruncationJson = truncation, ExpiresAt = at + DataRequestLimits.ArtifactLifetime, }; artifact.MarkCreated(at, actor); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs index da54ff2c..9e2d1fc3 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs @@ -166,5 +166,60 @@ public static FrozenDictionary ReadResult(string js } } + /// + /// Writes an artifact's truncation statement: participant.collection to its included and total + /// record counts, sorted by key (ADR-0107 § 3). An empty statement is {}. + /// + /// when a key repeats or the statement passes its bound. + public static string? WriteTruncation(IReadOnlyCollection truncations) + { + ArgumentNullException.ThrowIfNull(truncations); + ImmutableArray ordered; + try + { + ordered = DataExportTruncation.Normalize(truncations); + } + catch (ArgumentException) + { + return null; + } + + return JsonSerializer.Serialize(ordered.ToDictionary(item => item.Collection, + item => new SortedDictionary(StringComparer.Ordinal) { ["included"] = item.Included, ["total"] = item.Total }, + StringComparer.Ordinal)); + } + + /// The stored statement is malformed. + public static ImmutableArray ReadTruncation(string json) + { + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + throw Corrupt(); + } + + var items = new List(); + foreach (var entry in document.RootElement.EnumerateObject()) + { + if (entry.Value.ValueKind != JsonValueKind.Object || entry.Value.EnumerateObject().Count() != 2 + || !entry.Value.TryGetProperty("included", out var included) || !included.TryGetInt64(out var includedCount) + || !entry.Value.TryGetProperty("total", out var total) || !total.TryGetInt64(out var totalCount)) + { + throw Corrupt(); + } + + items.Add(new DataExportTruncation(entry.Name, includedCount, totalCount)); + } + + return DataExportTruncation.Normalize(items); + } + catch (Exception failure) when (failure is JsonException or ArgumentException) + { + throw Corrupt(); + } + } + private static InvalidOperationException Corrupt() => new("A stored data request document is malformed."); } 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 d431a42e..212e1fde 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 @@ -14,7 +14,12 @@ using LearnStack.Modules.Identity.Application.Contracts.Federation; using LearnStack.Modules.Identity.Application.Federation; using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Results; +using MediatR; using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Persistence; using Microsoft.Extensions.DependencyInjection; @@ -68,9 +73,31 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnCapabilitiesQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipCustomFieldsQuery))); services.TryAddScoped>(provider => () => provider.GetRequiredService()); + services.AddIdentityDataRequests(); return services; } + /// + /// ADR-0107 § 1–§ 4: the request store, the default artifact store, the export and purge job roots, the + /// fulfilment scheduler, the failure reconciler and the Identity participant. The cipher that seals the chunks + /// and the bundle builder are the composition root's. + /// + private static void AddIdentityDataRequests(this IServiceCollection services) + { + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + } + /// Registers internal consumers only; qualification is an explicit startup act before admission activation. public static IServiceCollection AddIdentityGlobalFoundation(this IServiceCollection services, IdentityAuthorityRegistration? registration = null) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportJobRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportJobRegistration.cs new file mode 100644 index 00000000..9fceb96b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportJobRegistration.cs @@ -0,0 +1,38 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.Jobs; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The export workflow's four transactional definitions and their four ordinary roots +/// (ADR-0107 § 2): +/// export and artifact purge, each once for the tenant-wide group and once for an organization group, version 1, +/// identifier-only parameters, the transactional queue and no capacity group. +/// +/// +/// They join the Identity module's one job registry in InvitationEmailRegistration.CreateRegistry, because +/// the runtime holds exactly one registry for every definition. The erasure definitions are P03-10 Step 2's. +/// +public static class DataExportJobRegistration +{ + public static IReadOnlyList Definitions { get; } = + [ + Definition(DataExportJobKeys.TenantExport.Value, BackgroundJobScope.TenantWide, typeof(DataExportJobParameters), typeof(RunTenantDataExportCommand)), + Definition(DataExportJobKeys.OrganizationExport.Value, BackgroundJobScope.Organization, typeof(DataExportJobParameters), typeof(RunOrganizationDataExportCommand)), + Definition(DataExportJobKeys.TenantPurge.Value, BackgroundJobScope.TenantWide, typeof(DataExportPurgeParameters), typeof(PurgeTenantDataExportCommand)), + Definition(DataExportJobKeys.OrganizationPurge.Value, BackgroundJobScope.Organization, typeof(DataExportPurgeParameters), typeof(PurgeOrganizationDataExportCommand)), + ]; + + public static IReadOnlyList Requests { get; } = + [ + new(typeof(RunTenantDataExportCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.TenantWide), + new(typeof(RunOrganizationDataExportCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization), + new(typeof(PurgeTenantDataExportCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.TenantWide), + new(typeof(PurgeOrganizationDataExportCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization), + ]; + + private static BackgroundJobDefinitionRegistration Definition(string key, BackgroundJobScope scope, Type parameters, Type root) => + new(key, typeof(DataExportJobHandlers), parameters, scope, BackgroundJobDefinitionReadiness.Active, "transactional", + BackgroundJobProfileRegistration.Transactional(root)); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs new file mode 100644 index 00000000..5658c1d1 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs @@ -0,0 +1,84 @@ +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// Reads a request's fulfilment job phase from background_jobs on the ambient transaction, the way the +/// invitation status reader reads its delivery job, so a dead job is seen without any hook running in it +/// (ADR-0106 § 8). +/// +/// +/// The request row carries no job identity, so the job is found by its exact route: the announced tenant and +/// organization, the export definition of that group, the transactional profile and the canonical serialization +/// of the request's own identifier, newest first. Nothing a caller supplies selects it. +/// +public sealed class DataRequestJobPhaseReader(IUnitOfWork unit, ITenantContext tenant) : IDataRequestJobPhaseReader +{ + public async Task ReadAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId + || request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A data request job phase requires its existing announced owner."); + } + + if (request.Kind != DataRequestKind.Export) + { + return DataRequestJobPhase.Unavailable; + } + + var parameters = BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(request.Id.Value), + typeof(DataExportJobParameters), BackgroundJobPayloadKind.Parameters); + await using var command = new NpgsqlCommand(""" + SELECT phase, quarantine_reason IS NOT NULL OR terminal_reason IS NOT NULL OR dead_lettered_at IS NOT NULL + FROM public.background_jobs + WHERE tenant_id = @tenant AND organization_id IS NOT DISTINCT FROM @organization + AND definition_key = @definition AND profile = 'transactional' AND parameters = @parameters + ORDER BY created_at DESC, id DESC + LIMIT 1 + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + command.Parameters.AddWithValue("definition", DataExportJobKeys.ExportFor(request.Group).Value); + command.Parameters.AddWithValue("parameters", parameters); + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + await using var row = await command.ExecuteReaderAsync(budget.Token).ConfigureAwait(false); + return await row.ReadAsync(budget.Token).ConfigureAwait(false) + ? Classify(row.GetString(0), row.GetBoolean(1)) + : DataRequestJobPhase.Unavailable; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && budget.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request job phase unavailable."); + } + catch (NpgsqlException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request job phase unavailable."); + } + } + + /// Quarantine, a terminal reason or a dead letter is dead; completed without one is done. + public static DataRequestJobPhase Classify(string phase, bool failed) => (phase, failed) switch + { + (_, true) or ("terminal_pending" or "quarantined", _) => DataRequestJobPhase.Dead, + ("completed", false) => DataRequestJobPhase.Completed, + _ => DataRequestJobPhase.Pending, + }; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs new file mode 100644 index 00000000..a91b71bd --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs @@ -0,0 +1,126 @@ +using LearnStack.Application.Messaging; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// on the ambient Identity context and transaction, confined to the announced group. +/// +public sealed class DataRequestStore(IdentityDbContext db, IUnitOfWork unit, ProducerExecution producer, ITenantContext tenant) + : IDataRequestStore +{ + private static readonly Type[] JobRoots = + [ + typeof(RunTenantDataExportCommand), typeof(RunOrganizationDataExportCommand), + typeof(PurgeTenantDataExportCommand), typeof(PurgeOrganizationDataExportCommand), + ]; + + public BackgroundJobId RequireCurrentJob() + { + var origin = producer.CaptureJobOrigin(unit); + if (origin.ParentJobId is not { } job || !JobRoots.Contains(origin.OperationType) + || origin.Announcement.TenantId != tenant.TenantId || origin.Announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Data request job owner refused."); + } + + producer.RequireJobOrigin(origin, unit); + return job; + } + + public async Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) + { + RequireOwner(); + await using var command = new NpgsqlCommand(""" + SELECT id FROM public.data_subject_requests + WHERE id=@id AND tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization FOR UPDATE + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) + { CommandTimeout = 5 }; + command.Parameters.AddWithValue("id", requestId.Value); + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + try + { + if (await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is null) + { + return null; + } + + return await db.DataSubjectRequests.SingleOrDefaultAsync(request => request.Id == requestId + && request.TenantId == tenant.TenantId && request.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + } + catch (NpgsqlException) + { + unit.MarkRollbackOnly(); + throw new InvalidOperationException("Data request storage unavailable."); + } + } + + public async Task FindArtifactOfRequestAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) + { + RequireOwner(); + var found = await db.DataExportArtifacts.AsNoTracking() + .Where(artifact => artifact.RequestId == requestId && artifact.TenantId == tenant.TenantId + && artifact.OrganizationId == tenant.OrganizationId) + .Select(artifact => artifact.Id).Take(2).ToListAsync(cancellationToken).ConfigureAwait(false); + return found.Count switch + { + 0 => null, + 1 => found[0], + _ => throw new InvalidOperationException("A request holds more than one export artifact."), + }; + } + + public async Task> FindAvailableArtifactsAsync(UserId subject, CancellationToken cancellationToken) + { + RequireOwner(); + // At most one by the partial unique index; the bound only keeps a corrupt state from being read unbounded. + return await db.DataExportArtifacts.AsNoTracking() + .Where(artifact => artifact.SubjectUserId == subject && artifact.Status == DataExportArtifactStatus.Available + && artifact.TenantId == tenant.TenantId && artifact.OrganizationId == tenant.OrganizationId) + .OrderBy(artifact => artifact.Id).Select(artifact => artifact.Id).Take(8) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + public async Task SaveAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + RequireOwner(); + if (request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId + || db.Entry(request).State == EntityState.Detached) + { + throw new InvalidOperationException("A data request is saved only from its own loaded group."); + } + + try + { + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException) + { + unit.MarkRollbackOnly(); + throw new InvalidOperationException("Data request storage unavailable."); + } + } + + private void RequireOwner() + { + if (!unit.HasActiveTransaction || unit.IsRollbackOnly || unit.Mode != TransactionMode.ReadWrite + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Data request storage requires its announced writable owner."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserDataParticipant.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserDataParticipant.cs new file mode 100644 index 00000000..385624ac --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserDataParticipant.cs @@ -0,0 +1,331 @@ +using System.Text.Json; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The Identity module's part in subject data requests: the subject's Memberships with their profile, role names +/// and custom-field values, and the invitations they accepted or issued +/// (ADR-0107 § 3, +/// ADR-0106 § 5). +/// +/// +/// +/// Subject predicate. Rows are selected by the subject's and the request's group, on the +/// ambient tenant transaction as learnstack_app: the Memberships are exactly the frozen snapshot that belongs +/// to the subject in the group, the invitations those the subject accepted or issued in the group. +/// +/// +/// Excluded. No identifier is written (no UserId, Membership, role, definition, consent or invitation +/// identity), nor the subject key, the provider subject, a verifier, an envelope or any key. Another person appears +/// only as third_party, and an invitee's address on an invitation the subject issued is omitted. +/// +/// +/// Custom fields. Every stored value is exported with its revision, labels and classification, including a +/// value withheld from ordinary disclosure by a withdrawn consent; a None classification is no exclusion. +/// +/// +public sealed class IdentityUserDataParticipant(IdentityDbContext db, ITenantContext tenant, + MembershipFieldRevisionReader fields) : IUserDataParticipant +{ + internal const string ParticipantKey = "identity"; + internal const string ThirdParty = "third_party"; + internal const string Self = "self"; + private const int Page = 200; + + private static readonly IReadOnlySet ReceiptTypes = + new HashSet { typeof(DataSubjectRequest), typeof(DataExportArtifact), typeof(DataExportTicket) }; + + public string Key => ParticipantKey; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(writer); + RequireGroup(subject); + if (!await ExportMembershipsAsync(subject, writer, cancellationToken).ConfigureAwait(false)) + { + return; + } + + if (!await ExportInvitationsAsync(subject, writer, accepted: true, cancellationToken).ConfigureAwait(false)) + { + return; + } + + await ExportInvitationsAsync(subject, writer, accepted: false, cancellationToken).ConfigureAwait(false); + } + + public async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + var person = subject.SubjectUserId; + UserId? nullablePerson = person; + var organization = subject.Group.OrganizationId; + var requests = await db.DataSubjectRequests.AsNoTracking() + .LongCountAsync(request => request.SubjectUserId == person && request.OrganizationId == organization, cancellationToken) + .ConfigureAwait(false); + var artifacts = await db.DataExportArtifacts.AsNoTracking() + .LongCountAsync(artifact => artifact.SubjectUserId == person && artifact.OrganizationId == organization, cancellationToken) + .ConfigureAwait(false); + var tickets = await db.DataExportTickets.AsNoTracking() + .LongCountAsync(ticket => ticket.CreatedBy == person && ticket.OrganizationId == organization, cancellationToken) + .ConfigureAwait(false); + var invitations = await db.Invitations.AsNoTracking() + .LongCountAsync(invitation => invitation.OrganizationId == organization + && (invitation.AcceptedBy == nullablePerson || invitation.InviterUserId == person), cancellationToken) + .ConfigureAwait(false); + var retained = new List + { + new(RetainedReferenceKind.RequestReceipt, checked(requests + artifacts + tickets)), + new(RetainedReferenceKind.InvitationRecord, invitations), + new(RetainedReferenceKind.AttributionReference, + await AttributionReferenceCounter.CountAsync(db, subject, ReceiptTypes, cancellationToken).ConfigureAwait(false)), + }; + + // Tenant-owned rows without an organization belong to the tenant-wide group alone. + if (subject.Group.IsTenantWide) + { + retained.Add(new(RetainedReferenceKind.FederationActorReference, await db.FederationConnections.AsNoTracking() + .LongCountAsync(connection => connection.PendingActor == nullablePerson || connection.TestActor == nullablePerson, + cancellationToken).ConfigureAwait(false))); + retained.Add(new(RetainedReferenceKind.ProviderEventRecord, await db.ProviderEventTargets.AsNoTracking() + .LongCountAsync(target => target.AffectedUserId == person, cancellationToken).ConfigureAwait(false))); + } + + return retained; + } + + private async Task ExportMembershipsAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + var person = subject.SubjectUserId; + var organization = subject.Group.OrganizationId; + var snapshot = subject.MembershipIds.Select(MembershipId.From).ToList(); + var memberships = await db.Memberships.AsNoTracking().Include(member => member.Profile).Include(member => member.RoleAssignments) + .Where(member => snapshot.Contains(member.Id) && member.UserId == person && member.OrganizationId == organization) + .OrderBy(member => member.CreatedAt).ThenBy(member => member.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + var roleIds = memberships.SelectMany(member => member.RoleAssignments).Select(assignment => assignment.RoleId).Distinct().ToList(); + var roles = await db.Roles.AsNoTracking().Where(role => roleIds.Contains(role.Id)) + .ToDictionaryAsync(role => role.Id, role => RoleName(role.BuiltInKey), cancellationToken).ConfigureAwait(false); + foreach (var membership in memberships) + { + var values = MembershipCustomFieldValues.Read(membership.Profile.CustomFieldsJson); + var revisions = await fields.ReadAsync(values, cancellationToken).ConfigureAwait(false); + var appended = await UserDataExportRecord.AppendAsync(writer, "memberships", json => + WriteMembership(json, membership, roles, values, revisions), cancellationToken).ConfigureAwait(false); + if (appended != UserDataExportAppend.Appended) + { + return false; + } + } + + return true; + } + + /// Accepted invitations carry the subject's own address; issued ones omit the invitee's. + private async Task ExportInvitationsAsync(UserDataSubject subject, IUserDataExportWriter writer, bool accepted, + CancellationToken cancellationToken) + { + var person = subject.SubjectUserId; + UserId? nullablePerson = person; + var organization = subject.Group.OrganizationId; + var collection = accepted ? "invitations_accepted" : "invitations_issued"; + var query = accepted + ? db.Invitations.AsNoTracking().Where(invitation => invitation.OrganizationId == organization && invitation.AcceptedBy == nullablePerson) + : db.Invitations.AsNoTracking().Where(invitation => invitation.OrganizationId == organization && invitation.InviterUserId == person); + for (var offset = 0; ; offset += Page) + { + // Bounded pages in a stable order on the one transaction; the bundle bounds the total. + var page = await query.OrderBy(invitation => invitation.CreatedAt).ThenBy(invitation => invitation.Id) + .Skip(offset).Take(Page).ToListAsync(cancellationToken).ConfigureAwait(false); + if (page.Count == 0) + { + return true; + } + + var roleIds = page.Select(invitation => invitation.RoleId).Distinct().ToList(); + var roles = await db.Roles.AsNoTracking().Where(role => roleIds.Contains(role.Id)) + .ToDictionaryAsync(role => role.Id, role => RoleName(role.BuiltInKey), cancellationToken).ConfigureAwait(false); + foreach (var invitation in page) + { + var appended = await UserDataExportRecord.AppendAsync(writer, collection, json => + WriteInvitation(json, invitation, roles, person, accepted), cancellationToken).ConfigureAwait(false); + if (appended != UserDataExportAppend.Appended) + { + return false; + } + } + + if (page.Count < Page) + { + return true; + } + } + } + + private static void WriteMembership(Utf8JsonWriter json, Membership membership, IReadOnlyDictionary roles, + IReadOnlyList values, IReadOnlyList revisions) + { + json.WriteStartObject(); + json.WriteString("status", membership.Status switch + { + MembershipStatus.Active => "active", + MembershipStatus.Suspended => "suspended", + MembershipStatus.Revoked => "revoked", + _ => throw new InvalidOperationException("A stored membership status is not in the closed set."), + }); + json.WriteString("scope", membership.OrganizationId is null ? "tenant" : "organization"); + json.WriteStartArray("roles"); + foreach (var role in membership.RoleAssignments.Select(assignment => roles.GetValueOrDefault(assignment.RoleId, "unavailable")) + .Order(StringComparer.Ordinal)) + { + json.WriteStringValue(role); + } + + json.WriteEndArray(); + json.WriteString("created_at", membership.CreatedAt); + WriteInstant(json, "updated_at", membership.UpdatedAt); + WriteInstant(json, "revoked_at", membership.DeletedAt); + json.WriteStartObject("profile"); + WriteText(json, "display_name", membership.Profile.DisplayName); + WriteText(json, "preferred_locale", membership.Profile.PreferredLocale); + json.WriteStartArray("custom_fields"); + foreach (var value in values) + { + var revision = revisions.FirstOrDefault(candidate => candidate.DefinitionId == value.DefinitionId + && candidate.SchemaVersion == value.SchemaVersion); + json.WriteStartObject(); + json.WriteString("field", value.ConceptKey); + json.WriteNumber("revision", value.SchemaVersion); + if (revision is null) + { + json.WriteNull("labels"); + json.WriteNull("classification"); + } + else + { + json.WriteStartObject("labels"); + foreach (var label in revision.Labels.OrderBy(item => item.Key, StringComparer.Ordinal)) + { + json.WriteString(label.Key, label.Value); + } + + json.WriteEndObject(); + json.WriteString("classification", Classification(revision.Classification)); + } + + json.WriteBoolean("consent_recorded", value.ConsentEvidenceId is not null); + json.WritePropertyName("value"); + value.Envelope.WriteTo(json); + json.WriteEndObject(); + } + + json.WriteEndArray(); + json.WriteEndObject(); + json.WriteEndObject(); + } + + private static void WriteInvitation(Utf8JsonWriter json, Invitation invitation, IReadOnlyDictionary roles, + UserId subject, bool accepted) + { + json.WriteStartObject(); + json.WriteString("status", invitation.Status switch + { + InvitationStatus.Pending => "pending", + InvitationStatus.Accepted => "accepted", + InvitationStatus.Revoked => "revoked", + _ => throw new InvalidOperationException("A stored invitation status is not in the closed set."), + }); + json.WriteString("scope", invitation.OrganizationId is null ? "tenant" : "organization"); + json.WriteString("role", roles.GetValueOrDefault(invitation.RoleId, "unavailable")); + json.WriteString("created_at", invitation.CreatedAt); + json.WriteString("expires_at", invitation.ExpiresAt); + WriteInstant(json, "accepted_at", invitation.AcceptedAt); + if (accepted) + { + // ADR-0107 § 3: the person's own address on the offer they accepted. + json.WriteString("recipient_email", invitation.RecipientEmail); + json.WriteString("issued_by", invitation.InviterUserId == subject ? Self : ThirdParty); + } + else + { + // ADR-0106 § 5: the invitee's address is another person's data and is omitted; the acceptor is a party. + if (invitation.AcceptedBy is { } acceptor) + { + json.WriteString("accepted_by", acceptor == subject ? Self : ThirdParty); + } + else + { + json.WriteNull("accepted_by"); + } + } + + json.WriteEndObject(); + } + + internal static string RoleName(BuiltInRoleKey key) => key switch + { + BuiltInRoleKey.TenantAdmin => "tenant_admin", + BuiltInRoleKey.Instructor => "instructor", + BuiltInRoleKey.Learner => "learner", + BuiltInRoleKey.Guardian => "guardian", + BuiltInRoleKey.Editor => "editor", + BuiltInRoleKey.OrgAdmin => "org_admin", + BuiltInRoleKey.OrgInstructor => "org_instructor", + _ => "unavailable", + }; + + private static string Classification(PersonalDataCategory category) => category switch + { + PersonalDataCategory.None => "none", + PersonalDataCategory.Identity => "identity", + PersonalDataCategory.Behaviour => "behaviour", + PersonalDataCategory.Sensitive => "sensitive", + PersonalDataCategory.Payment => "payment", + PersonalDataCategory.Audit => "audit", + _ => "unavailable", + }; + + private static void WriteInstant(Utf8JsonWriter json, string name, DateTimeOffset? value) + { + if (value is { } instant) + { + json.WriteString(name, instant); + } + else + { + json.WriteNull(name); + } + } + + private static void WriteText(Utf8JsonWriter json, string name, string? value) + { + if (value is null) + { + json.WriteNull(name); + } + else + { + json.WriteString(name, value); + } + } + + private void RequireGroup(UserDataSubject subject) + { + if (subject.Group.TenantId != tenant.TenantId || subject.Group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A participant reads only the announced group of its request."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PostgresDataExportArtifactStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PostgresDataExportArtifactStore.cs new file mode 100644 index 00000000..466bc1a6 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PostgresDataExportArtifactStore.cs @@ -0,0 +1,319 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The default : encrypted chunks in data_export_chunks and the +/// receipt-safe metadata in data_export_artifacts +/// (ADR-0107 § 4). +/// +/// +/// +/// Ambient only. Every call runs on the caller's announced tenant transaction as learnstack_app and +/// opens no connection; the locator's group must be the announced one, so the row policy and this check agree. +/// +/// +/// The metadata is an aggregate, the ciphertext is not. The artifact row is written through the tracked +/// , so its creation and transitions reach the audit capture; the chunks are +/// written, read and deleted with fixed parameterized statements and are never tracked, so ciphertext cannot reach +/// an audit snapshot. The database guards admit a chunk only for an available artifact and the deferred +/// completeness check refuses a commit in which an available artifact lacks a chunk or a revoked or purged one +/// keeps one. +/// +/// +/// Bounded memory. seals and inserts each plaintext chunk as it arrives and keeps +/// none; a read decrypts one chunk. +/// +/// +/// Time. Readability and the revoke-or-purge decision use the database clock, as the guards do, so an +/// artifact past its expiry is unreadable whether or not its purge ran. +/// +/// +public sealed class PostgresDataExportArtifactStore(IdentityDbContext db, IUnitOfWork unit, ITenantContext tenant, + DataExportCipher cipher, IClock clock, IAuditSubject audit) : IDataExportArtifactStore +{ + private static readonly TimeSpan StatementBudget = TimeSpan.FromSeconds(5); + + public async Task PutAsync(DataExportArtifactPut put, IAsyncEnumerable> plaintextChunks, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(put); + ArgumentNullException.ThrowIfNull(plaintextChunks); + RequireGroup(put.Group, writable: true); + var requestId = DataSubjectRequestId.From(put.RequestId); + var request = await db.DataSubjectRequests.SingleOrDefaultAsync(candidate => candidate.Id == requestId + && candidate.TenantId == tenant.TenantId && candidate.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + if (request is null || request.SubjectUserId != put.SubjectUserId) + { + throw Refused(); + } + + var created = DataExportArtifact.Create(DataExportArtifactId.From(put.ArtifactId), request, put.ByteCount, + cipher.ActiveKeyVersion, put.Truncations, clock.UtcNow, tenant.UserId ?? UserId.SystemActor); + if (created.IsFailure || created.Value.ChunkCount != put.ChunkCount) + { + throw Refused(); + } + + var artifact = created.Value; + db.DataExportArtifacts.Add(artifact); + audit.Designate(artifact); + await SaveAsync(cancellationToken).ConfigureAwait(false); + + var index = 0; + long stored = 0; + await foreach (var chunk in plaintextChunks.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + var expected = index < put.ChunkCount - 1 + ? DataRequestLimits.ChunkPlaintextBytes + : put.ByteCount - ((long)(put.ChunkCount - 1) * DataRequestLimits.ChunkPlaintextBytes); + if (index >= put.ChunkCount || chunk.Length != expected) + { + throw Refused(); + } + + var sealedChunk = cipher.Seal(new DataExportChunkBinding(tenant.TenantId.Value, put.RequestId, put.ArtifactId, + index, put.ChunkCount), chunk.Span); + await InsertChunkAsync(put.ArtifactId, index, sealedChunk, cancellationToken).ConfigureAwait(false); + stored += chunk.Length; + index++; + } + + if (index != put.ChunkCount || stored != put.ByteCount) + { + throw Refused(); + } + + return Metadata(artifact, readable: true); + } + + public async Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(artifact); + RequireGroup(artifact.Group, writable: false); + var id = DataExportArtifactId.From(artifact.ArtifactId); + var found = await db.DataExportArtifacts.AsNoTracking().SingleOrDefaultAsync(candidate => candidate.Id == id + && candidate.TenantId == tenant.TenantId && candidate.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + if (found is null) + { + return null; + } + + var now = await DatabaseNowAsync(cancellationToken).ConfigureAwait(false); + return Metadata(found, found.Status == DataExportArtifactStatus.Available && now < found.ExpiresAt); + } + + public async Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(artifact); + RequireGroup(artifact.Group, writable: false); + if (index is < 0 or >= DataRequestLimits.MaximumChunkCount) + { + return null; + } + + await using var command = Command(""" + SELECT a.request_id, a.chunk_count, a.key_version, c.nonce, c.ciphertext, c.tag + FROM public.data_export_artifacts AS a + JOIN public.data_export_chunks AS c ON c.tenant_id = a.tenant_id AND c.artifact_id = a.id + WHERE a.tenant_id = @tenant AND a.organization_id IS NOT DISTINCT FROM @organization AND a.id = @artifact + AND c.chunk_index = @index AND a.status = 'available' AND clock_timestamp() < a.expires_at + """); + command.Parameters.AddWithValue("artifact", artifact.ArtifactId); + command.Parameters.AddWithValue("index", index); + Guid requestId; + int count; + DataExportSealedChunk sealedChunk; + using (var budget = Budget(cancellationToken)) + { + try + { + await using var row = await command.ExecuteReaderAsync(budget.Token).ConfigureAwait(false); + if (!await row.ReadAsync(budget.Token).ConfigureAwait(false)) + { + return null; + } + + requestId = row.GetGuid(0); + count = row.GetInt32(1); + sealedChunk = new DataExportSealedChunk(row.GetString(2), (byte[])row[3], (byte[])row[4], (byte[])row[5]); + } + catch (NpgsqlException) + { + throw Unavailable(); + } + } + + var plaintext = cipher.Open(new DataExportChunkBinding(tenant.TenantId.Value, requestId, artifact.ArtifactId, index, count), + sealedChunk); + return new DataExportPlaintextChunk(index, count, plaintext); + } + + public async Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(artifact); + if (outcome is not (DataExportArtifactStatus.Revoked or DataExportArtifactStatus.Purged)) + { + throw new ArgumentOutOfRangeException(nameof(outcome), "A purge records the artifact revoked or purged."); + } + + RequireGroup(artifact.Group, writable: true); + await using (var lockRow = Command(""" + SELECT id FROM public.data_export_artifacts + WHERE id = @artifact AND tenant_id = @tenant AND organization_id IS NOT DISTINCT FROM @organization FOR UPDATE + """)) + { + lockRow.Parameters.AddWithValue("artifact", artifact.ArtifactId); + if (await ExecuteAsync(token => lockRow.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is null) + { + return null; + } + } + + var id = DataExportArtifactId.From(artifact.ArtifactId); + var found = await db.DataExportArtifacts.SingleAsync(candidate => candidate.Id == id + && candidate.TenantId == tenant.TenantId && candidate.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + if (found.Status is DataExportArtifactStatus.Revoked or DataExportArtifactStatus.Purged) + { + return found.Status; + } + + // The database clock decides, as the guard does: revoke before the expiry, purge after it. + var now = await DatabaseNowAsync(cancellationToken).ConfigureAwait(false); + var expired = now >= found.ExpiresAt; + if (!expired && outcome == DataExportArtifactStatus.Purged) + { + return found.Status; + } + + var actor = tenant.UserId ?? UserId.SystemActor; + var transition = expired ? found.Purge(now, actor) : found.Revoke(now, actor); + if (transition.IsFailure) + { + // The clocks disagree at the boundary: a later attempt decides again. + throw Unavailable(); + } + + await using (var delete = Command(""" + DELETE FROM public.data_export_chunks WHERE tenant_id = @tenant AND artifact_id = @artifact + """)) + { + delete.Parameters.AddWithValue("artifact", artifact.ArtifactId); + await ExecuteAsync(token => delete.ExecuteNonQueryAsync(token), cancellationToken).ConfigureAwait(false); + } + + await SaveAsync(cancellationToken).ConfigureAwait(false); + return found.Status; + } + + private async Task InsertChunkAsync(Guid artifactId, int index, DataExportSealedChunk chunk, CancellationToken cancellationToken) + { + await using var command = Command(""" + INSERT INTO public.data_export_chunks (tenant_id, organization_id, artifact_id, chunk_index, nonce, ciphertext, tag) + VALUES (@tenant, @organization, @artifact, @index, @nonce, @ciphertext, @tag) + """); + command.Parameters.AddWithValue("artifact", artifactId); + command.Parameters.AddWithValue("index", index); + command.Parameters.AddWithValue("nonce", NpgsqlDbType.Bytea, chunk.Nonce); + command.Parameters.AddWithValue("ciphertext", NpgsqlDbType.Bytea, chunk.Ciphertext); + command.Parameters.AddWithValue("tag", NpgsqlDbType.Bytea, chunk.Tag); + await ExecuteAsync(token => command.ExecuteNonQueryAsync(token), cancellationToken).ConfigureAwait(false); + } + + private async Task DatabaseNowAsync(CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand("SELECT clock_timestamp()", + (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) + { CommandTimeout = 5 }; + var value = await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false); + return value switch + { + DateTime utc when utc.Kind == DateTimeKind.Utc => new DateTimeOffset(utc, TimeSpan.Zero), + DateTimeOffset instant => instant.ToUniversalTime(), + _ => throw Unavailable(), + }; + } + + private async Task SaveAsync(CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException) + { + unit.MarkRollbackOnly(); + throw Unavailable(); + } + } + + private NpgsqlCommand Command(string sql) + { + var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + return command; + } + + private async Task ExecuteAsync(Func> statement, CancellationToken cancellationToken) + { + using var budget = Budget(cancellationToken); + try + { + return await statement(budget.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw Unavailable(); + } + catch (NpgsqlException) + { + unit.MarkRollbackOnly(); + throw Unavailable(); + } + } + + private static CancellationTokenSource Budget(CancellationToken cancellationToken) + { + var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(StatementBudget); + return budget; + } + + private void RequireGroup(DataRequestScopeGroup group, bool writable) + { + ArgumentNullException.ThrowIfNull(group); + if (group.TenantId != tenant.TenantId || group.OrganizationId != tenant.OrganizationId + || !unit.HasActiveTransaction || unit.IsRollbackOnly + || writable && unit.Mode != TransactionMode.ReadWrite + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != group.TenantId || announcement.OrganizationId != group.OrganizationId) + { + throw Refused(); + } + } + + private static DataExportArtifactMetadata Metadata(DataExportArtifact artifact, bool readable) => + new(artifact.Id.Value, artifact.RequestId.Value, artifact.Status, artifact.ByteCount, artifact.ChunkCount, + artifact.KeyVersion, artifact.ExpiresAt, artifact.PurgedAt, artifact.Truncations, readable); + + private static InvalidOperationException Refused() => new("Data export artifact custody refused."); + + private static InvalidOperationException Unavailable() => new("Data export artifact storage unavailable."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationEmailRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationEmailRegistration.cs index cfa7aa27..2bf3697a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationEmailRegistration.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationEmailRegistration.cs @@ -2,6 +2,7 @@ using LearnStack.Infrastructure.Jobs; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Results; using MediatR; @@ -45,14 +46,18 @@ public static BackgroundJobDefinitionRegistry CreateRegistry() new("control", BackgroundJobWorkerPoolKind.Control, 1, ["control"])], [new("identity.invitation_email", typeof(InvitationEmailJobHandlers), 4)], [new(typeof(IInvitationEmailOperation), typeof(InvitationSmtpOperation))], modules); + // The Identity module's one registry: the runtime holds a single registry, so the data-export definitions of + // ADR-0107 § 2 join the invitation pair here rather than replacing it. return BackgroundJobDefinitionRegistry.Create( [Definition("identity.invitation_email_tenant.v1", BackgroundJobScope.TenantWide, typeof(PrepareTenantInvitationEmailCommand), typeof(FinalizeTenantInvitationEmailCommand)), - Definition("identity.invitation_email_organization.v1", BackgroundJobScope.Organization, typeof(PrepareOrganizationInvitationEmailCommand), typeof(FinalizeOrganizationInvitationEmailCommand))], + Definition("identity.invitation_email_organization.v1", BackgroundJobScope.Organization, typeof(PrepareOrganizationInvitationEmailCommand), typeof(FinalizeOrganizationInvitationEmailCommand)), + .. DataExportJobRegistration.Definitions], [.. BackgroundJobFrameworkRequests.All, new(typeof(PrepareTenantInvitationEmailCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.TenantWide), new(typeof(FinalizeTenantInvitationEmailCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.TenantWide), new(typeof(PrepareOrganizationInvitationEmailCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization), - new(typeof(FinalizeOrganizationInvitationEmailCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization)], modules, infrastructure: infrastructure); + new(typeof(FinalizeOrganizationInvitationEmailCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization), + .. DataExportJobRegistration.Requests], modules, infrastructure: infrastructure); } private static BackgroundJobDefinitionRegistration Definition(string key, BackgroundJobScope scope, Type prepare, Type finalize) => new(key, typeof(InvitationEmailJobHandlers), typeof(InvitationEmailParameters), scope, BackgroundJobDefinitionReadiness.Active, "external", diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs index fccff560..f18637cf 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs @@ -159,6 +159,19 @@ public void Configure(EntityTypeBuilder builder) table.HasCheckConstraint("ck_data_export_artifacts_lifecycle", "((status IN ('revoked','purged')) = (purged_at IS NOT NULL) AND (purged_at IS NULL OR (isfinite(purged_at) AND purged_at >= created_at))) IS TRUE"); table.HasCheckConstraint("ck_data_export_artifacts_no_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + // ADR-0107 § 3: the receipt states a capped collection as the bundle does. A closed shape: at most 32 + // participant.collection keys, each holding exactly two whole counts with included <= total. + table.HasCheckConstraint("ck_data_export_artifacts_truncation", """ + CASE WHEN jsonb_typeof(truncation) = 'object' + THEN jsonb_array_length(jsonb_path_query_array(truncation, '$.keyvalue()')) <= 32 + AND NOT jsonb_path_exists(truncation, + '$.keyvalue() ? (!(@.key like_regex "^[a-z][a-z0-9_]{0,31}[.][a-z][a-z0-9_]{0,31}$") || @.value.type() != "object")') + AND NOT jsonb_path_exists(truncation, '$.*.keyvalue() ? (@.key != "included" && @.key != "total")') + AND NOT jsonb_path_exists(truncation, '$.* ? (!exists(@.included) || !exists(@.total))') + AND NOT jsonb_path_exists(truncation, + '$.* ? (@.included.type() != "number" || @.total.type() != "number" || @.included < 0 || @.included > @.total || @.total > 9007199254740991 || @.included.floor() != @.included || @.total.floor() != @.total)') + ELSE false END + """); }); builder.HasKey(entity => entity.Id).HasName("pk_data_export_artifacts"); builder.Property(entity => entity.Id) @@ -171,6 +184,9 @@ public void Configure(EntityTypeBuilder builder) builder.Property(entity => entity.Status) .HasConversion(new ClosedCodeConverter(DataRequestCodes.ArtifactStatuses)).HasColumnType("text"); builder.Property(entity => entity.KeyVersion).HasMaxLength(DataRequestLimits.MaximumKeyVersionLength).UseCollation("C"); + builder.Property(entity => entity.TruncationJson).HasColumnName("truncation").HasColumnType("jsonb") + .HasDefaultValue(DataRequestDocuments.EmptyObject).IsRequired(); + builder.Ignore(entity => entity.Truncations); builder.HasOne().WithMany().HasForeignKey(entity => new { entity.TenantId, entity.RequestId }) .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }) .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_data_export_artifacts_request"); @@ -185,9 +201,11 @@ public void Configure(EntityTypeBuilder builder) nameof(DataExportArtifact.Id), nameof(DataExportArtifact.TenantId), nameof(DataExportArtifact.OrganizationId), nameof(DataExportArtifact.RequestId), nameof(DataExportArtifact.SubjectUserId)); builder.DeclarePersonalData(PersonalDataCategory.None, - "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key.", + "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed " + + "truncation statement (collection names and counts); no content or key.", nameof(DataExportArtifact.Status), nameof(DataExportArtifact.ByteCount), nameof(DataExportArtifact.ChunkCount), - nameof(DataExportArtifact.KeyVersion), nameof(DataExportArtifact.ExpiresAt), nameof(DataExportArtifact.PurgedAt)); + nameof(DataExportArtifact.KeyVersion), nameof(DataExportArtifact.ExpiresAt), nameof(DataExportArtifact.PurgedAt), + nameof(DataExportArtifact.TruncationJson)); } } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs index 2d365293..cd9c7c46 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs @@ -325,9 +325,11 @@ OR NOT (request_status = 'fulfilling' OR (request_status = 'completed' AND reque RETURN NEW; END IF; IF (ROW(NEW.id, NEW.tenant_id, NEW.organization_id, NEW.request_id, NEW.subject_user_id, NEW.byte_count, - NEW.chunk_count, NEW.key_version, NEW.expires_at, NEW.created_at, NEW.created_by, NEW.deleted_at, NEW.deleted_by) + NEW.chunk_count, NEW.key_version, NEW.truncation, NEW.expires_at, NEW.created_at, NEW.created_by, + NEW.deleted_at, NEW.deleted_by) IS DISTINCT FROM ROW(OLD.id, OLD.tenant_id, OLD.organization_id, OLD.request_id, OLD.subject_user_id, OLD.byte_count, - OLD.chunk_count, OLD.key_version, OLD.expires_at, OLD.created_at, OLD.created_by, OLD.deleted_at, OLD.deleted_by) + OLD.chunk_count, OLD.key_version, OLD.truncation, OLD.expires_at, OLD.created_at, OLD.created_by, + OLD.deleted_at, OLD.deleted_by) OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 OR NEW.updated_at IS NULL OR NEW.updated_by IS NULL OR NOT isfinite(NEW.updated_at) OR NEW.updated_at < COALESCE(OLD.updated_at, OLD.created_at) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs index bce89d68..376f4ebe 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs @@ -39,13 +39,13 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("bigint") .HasColumnName("byte_count") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("ChunkCount") .HasColumnType("integer") .HasColumnName("chunk_count") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("CreatedAt") .HasColumnType("timestamp with time zone") @@ -75,7 +75,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone") .HasColumnName("expires_at") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("KeyVersion") .IsRequired() @@ -84,7 +84,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnName("key_version") .UseCollation("C") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("OrganizationId") .HasColumnType("uuid") @@ -96,7 +96,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone") .HasColumnName("purged_at") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("RequestId") .HasColumnType("uuid") @@ -109,7 +109,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("text") .HasColumnName("status") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("SubjectUserId") .HasColumnType("uuid") @@ -123,6 +123,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + b.Property("TruncationJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("truncation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); + b.Property("UpdatedAt") .HasColumnType("timestamp with time zone") .HasColumnName("updated_at") @@ -180,6 +189,8 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) t.HasCheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); t.HasCheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_truncation", "CASE WHEN jsonb_typeof(truncation) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(truncation, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(truncation,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}[.][a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"object\")')\n AND NOT jsonb_path_exists(truncation, '$.*.keyvalue() ? (@.key != \"included\" && @.key != \"total\")')\n AND NOT jsonb_path_exists(truncation, '$.* ? (!exists(@.included) || !exists(@.total))')\n AND NOT jsonb_path_exists(truncation,\n '$.* ? (@.included.type() != \"number\" || @.total.type() != \"number\" || @.included < 0 || @.included > @.total || @.total > 9007199254740991 || @.included.floor() != @.included || @.total.floor() != @.total)')\n ELSE false END"); }); }); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs index 6c451998..d207cd34 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs @@ -82,6 +82,7 @@ protected override void Up(MigrationBuilder migrationBuilder) byte_count = table.Column(type: "bigint", nullable: false), chunk_count = table.Column(type: "integer", nullable: false), key_version = table.Column(type: "character varying(32)", maxLength: 32, nullable: false, collation: "C"), + truncation = table.Column(type: "jsonb", nullable: false, defaultValue: "{}"), expires_at = table.Column(type: "timestamp with time zone", nullable: false), purged_at = table.Column(type: "timestamp with time zone", nullable: true), created_at = table.Column(type: "timestamp with time zone", nullable: false), @@ -104,6 +105,7 @@ protected override void Up(MigrationBuilder migrationBuilder) table.CheckConstraint("ck_data_export_artifacts_status", "status IN ('available','revoked','expired','purged')"); table.CheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); table.CheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + table.CheckConstraint("ck_data_export_artifacts_truncation", "CASE WHEN jsonb_typeof(truncation) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(truncation, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(truncation,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}[.][a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"object\")')\n AND NOT jsonb_path_exists(truncation, '$.*.keyvalue() ? (@.key != \"included\" && @.key != \"total\")')\n AND NOT jsonb_path_exists(truncation, '$.* ? (!exists(@.included) || !exists(@.total))')\n AND NOT jsonb_path_exists(truncation,\n '$.* ? (@.included.type() != \"number\" || @.total.type() != \"number\" || @.included < 0 || @.included > @.total || @.total > 9007199254740991 || @.included.floor() != @.included || @.total.floor() != @.total)')\n ELSE false END"); table.ForeignKey( name: "fk_data_export_artifacts_request", columns: x => new { x.tenant_id, x.request_id }, diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs index 8e2bf30f..61f60cb0 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs @@ -36,13 +36,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("bigint") .HasColumnName("byte_count") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("ChunkCount") .HasColumnType("integer") .HasColumnName("chunk_count") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("CreatedAt") .HasColumnType("timestamp with time zone") @@ -72,7 +72,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone") .HasColumnName("expires_at") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("KeyVersion") .IsRequired() @@ -81,7 +81,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnName("key_version") .UseCollation("C") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("OrganizationId") .HasColumnType("uuid") @@ -93,7 +93,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone") .HasColumnName("purged_at") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("RequestId") .HasColumnType("uuid") @@ -106,7 +106,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("text") .HasColumnName("status") .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) - .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label and expiry; no content or key."); + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); b.Property("SubjectUserId") .HasColumnType("uuid") @@ -120,6 +120,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) .HasAnnotation("LearnStack:PersonalData:Purpose", "A person's export receipt: the group, the request and the subject it was generated for."); + b.Property("TruncationJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValue("{}") + .HasColumnName("truncation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed artifact lifecycle, plaintext size, chunk count, key-ring version label, expiry and the closed truncation statement (collection names and counts); no content or key."); + b.Property("UpdatedAt") .HasColumnType("timestamp with time zone") .HasColumnName("updated_at") @@ -177,6 +186,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("ck_data_export_artifacts_tenant", "tenant_id NOT IN ('00000000-0000-0000-0000-000000000000'::uuid,'00000000-0000-7000-8000-000000000002'::uuid)"); t.HasCheckConstraint("ck_data_export_artifacts_times", "(isfinite(created_at) AND expires_at = created_at + interval '7 days' AND (updated_at IS NULL OR (isfinite(updated_at) AND updated_at >= created_at))) IS TRUE"); + + t.HasCheckConstraint("ck_data_export_artifacts_truncation", "CASE WHEN jsonb_typeof(truncation) = 'object'\n THEN jsonb_array_length(jsonb_path_query_array(truncation, '$.keyvalue()')) <= 32\n AND NOT jsonb_path_exists(truncation,\n '$.keyvalue() ? (!(@.key like_regex \"^[a-z][a-z0-9_]{0,31}[.][a-z][a-z0-9_]{0,31}$\") || @.value.type() != \"object\")')\n AND NOT jsonb_path_exists(truncation, '$.*.keyvalue() ? (@.key != \"included\" && @.key != \"total\")')\n AND NOT jsonb_path_exists(truncation, '$.* ? (!exists(@.included) || !exists(@.total))')\n AND NOT jsonb_path_exists(truncation,\n '$.* ? (@.included.type() != \"number\" || @.total.type() != \"number\" || @.included < 0 || @.included > @.total || @.total > 9007199254740991 || @.included.floor() != @.included || @.total.floor() != @.total)')\n ELSE false END"); }); }); diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserDataParticipant.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserDataParticipant.cs new file mode 100644 index 00000000..419b9e63 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserDataParticipant.cs @@ -0,0 +1,124 @@ +using System.Text.Json; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Modules.Tenancy.Infrastructure.DataRequests; + +/// +/// The Tenancy module's part in subject data requests: the subject's membership field consent history in the +/// group, exported and retained as consent_evidence +/// (ADR-0107 § 3, § 6). +/// +/// +/// +/// A consent row is the subject's when it names the subject and one of the request's frozen Memberships in the +/// group. A record holds the purpose, the definition revision, the notice locale, the state, the sequence and the +/// time, and who recorded it as self or third_party; the Membership and definition identities and the +/// notice digest are internal and stay out. +/// +/// +/// The table is append-only evidence of lawful basis (ADR-0107 § 6), so erasure leaves it and this participant +/// only describes it. +/// +/// +public sealed class TenancyUserDataParticipant(TenancyDbContext db, ITenantContext tenant) : IUserDataParticipant +{ + internal const string ParticipantKey = "tenancy"; + private const int Page = 200; + + private static readonly IReadOnlySet EvidenceTypes = new HashSet { typeof(MembershipFieldConsent) }; + + public string Key => ParticipantKey; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(writer); + RequireGroup(subject); + for (var offset = 0; ; offset += Page) + { + var page = await Consents(subject).OrderBy(consent => consent.CreatedAt).ThenBy(consent => consent.Sequence) + .ThenBy(consent => consent.Id).Skip(offset).Take(Page).ToListAsync(cancellationToken).ConfigureAwait(false); + foreach (var consent in page) + { + var appended = await UserDataExportRecord.AppendAsync(writer, "field_consents", + json => Write(json, consent, subject), cancellationToken).ConfigureAwait(false); + if (appended != UserDataExportAppend.Appended) + { + return; + } + } + + if (page.Count < Page) + { + return; + } + } + } + + public async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + return + [ + new(RetainedReferenceKind.ConsentEvidence, + await Consents(subject).LongCountAsync(cancellationToken).ConfigureAwait(false)), + new(RetainedReferenceKind.AttributionReference, + await AttributionReferenceCounter.CountAsync(db, subject, EvidenceTypes, cancellationToken).ConfigureAwait(false)), + ]; + } + + private IQueryable Consents(UserDataSubject subject) + { + var person = subject.SubjectUserId; + var organization = subject.Group.OrganizationId; + var memberships = subject.MembershipIds.ToList(); + return db.MembershipFieldConsents.AsNoTracking().Where(consent => consent.SubjectUserId == person + && consent.OrganizationId == organization && memberships.Contains(consent.MembershipId)); + } + + private static void Write(Utf8JsonWriter json, MembershipFieldConsent consent, UserDataSubject subject) + { + json.WriteStartObject(); + json.WriteString("purpose", consent.PurposeKey); + json.WriteNumber("revision", consent.DefinitionVersion); + json.WriteString("notice_locale", consent.NoticeLocale); + json.WriteString("state", consent.State switch + { + MembershipFieldConsentState.Granted => "granted", + MembershipFieldConsentState.Withdrawn => "withdrawn", + _ => throw new InvalidOperationException("A stored consent state is not in the closed set."), + }); + json.WriteNumber("sequence", consent.Sequence); + json.WriteString("recorded_at", consent.CreatedAt); + json.WriteString("recorded_by", consent.ActorUserId == subject.SubjectUserId ? "self" : "third_party"); + json.WriteEndObject(); + } + + private void RequireGroup(UserDataSubject subject) + { + if (subject.Group.TenantId != tenant.TenantId || subject.Group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A participant reads only the announced group of its request."); + } + } +} + +/// Registers the Tenancy module's participant from its own boundary (ADR-0107 § 1). +public static class TenancyDataRequestRegistration +{ + public static IServiceCollection AddTenancyUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + return services; + } +} diff --git a/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs b/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs index d30edab4..0d9ed68a 100644 --- a/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs +++ b/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs @@ -14,6 +14,8 @@ internal static class InvitationEmailFixtureConfiguration ["InvitationEmail:Smtp:Tls"] = "ImplicitTls", ["InvitationEmail:Smtp:Username"] = "synthetic-fixture", ["InvitationEmail:Smtp:Password"] = "synthetic-fixture", + // ADR-0107 § 4: the export key ring is checked at startup the same way. + ["DataExport:KeyRing"] = "{\"active\":\"test\",\"keys\":{\"test\":\"AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=\"}}", }; internal static void AddTo(IWebHostBuilder builder) diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAdmissionBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAdmissionBoundaryTests.cs index f04b745f..cec7405f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAdmissionBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAdmissionBoundaryTests.cs @@ -146,12 +146,14 @@ private static SortedSet JobStepThreeOffenders(ProductionCensus census) (InfrastructureAssembly, JobScheduler, "SubmitRecipientAsync"), ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailStager", "StageAsync"), ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailJobStore", "RequireCurrentJob"), + ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataRequestStore", "RequireCurrentJob"), (InfrastructureAssembly, "LearnStack.Infrastructure.Email.InvitationEmailEnvelopeWriter", "StageAsync")]); Capability(DeliveryApplication, DeliveryProducer, "RequireJobOrigin", [(InfrastructureAssembly, JobScheduler, "SubmitAsync"), (InfrastructureAssembly, JobScheduler, "SubmitAsync"), (InfrastructureAssembly, JobScheduler, "SubmitAsync"), (InfrastructureAssembly, JobScheduler, "SubmitRecipientAsync"), (InfrastructureAssembly, JobScheduler, "InsertAsync"), ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailStager", "StageAsync"), ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailJobStore", "RequireCurrentJob"), + ("LearnStack.Modules.Identity.Infrastructure", "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataRequestStore", "RequireCurrentJob"), (InfrastructureAssembly, "LearnStack.Infrastructure.Email.InvitationEmailEnvelopeWriter", "StageAsync")]); Capability(DeliveryApplication, DeliveryCoordinator, "ExecuteRequestAsync", [(DeliveryApplication, JobTransactionBehavior, "Handle")]); diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs index 2a128949..248843ab 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs @@ -1,9 +1,12 @@ using FluentAssertions; using LearnStack.Infrastructure.Jobs; using LearnStack.SharedKernel.Jobs; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; using LearnStack.Modules.Identity.Infrastructure.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Mono.Cecil; @@ -167,7 +170,10 @@ private static void AssertEndpointControl(IEnumerable offenders, string private static void CheckInvitationJobManifest() { var registry = InvitationEmailRegistration.CreateRegistry(); - registry.DefinitionKeys.Should().BeEquivalentTo("identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1"); + registry.DefinitionKeys.Should().BeEquivalentTo("identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1", + "identity.data_export_tenant.v1", "identity.data_export_organization.v1", + "identity.data_export_purge_tenant.v1", "identity.data_export_purge_organization.v1"); + CheckDataExportJobManifest(registry); foreach (var (key, scope, prepare, finalize) in new[] { ("identity.invitation_email_tenant.v1", BackgroundJobScope.TenantWide, typeof(PrepareTenantInvitationEmailCommand), typeof(FinalizeTenantInvitationEmailCommand)), @@ -206,6 +212,69 @@ private static void CheckInvitationJobManifest() } } + /// + /// ADR-0107 § 2: the export workflow adds exactly four transactional, identifier-only, version-1 definitions, one + /// per purpose and scope group, with no capacity group and no nested request; their declaration source is bound + /// so a widened scope, profile, queue or root cannot pass silently. + /// + private static void CheckDataExportJobManifest(BackgroundJobDefinitionRegistry registry) + { + foreach (var (key, scope, parameters, root) in new[] + { + ("identity.data_export_tenant.v1", BackgroundJobScope.TenantWide, typeof(DataExportJobParameters), typeof(RunTenantDataExportCommand)), + ("identity.data_export_organization.v1", BackgroundJobScope.Organization, typeof(DataExportJobParameters), typeof(RunOrganizationDataExportCommand)), + ("identity.data_export_purge_tenant.v1", BackgroundJobScope.TenantWide, typeof(DataExportPurgeParameters), typeof(PurgeTenantDataExportCommand)), + ("identity.data_export_purge_organization.v1", BackgroundJobScope.Organization, typeof(DataExportPurgeParameters), typeof(PurgeOrganizationDataExportCommand)), + }) + { + registry.TryGet(key, out var definition).Should().BeTrue(); + definition!.OwnerModule.Should().Be("identity"); + definition.ParameterType.Should().Be(parameters); + definition.Scope.Should().Be(scope); + definition.Readiness.Should().Be(BackgroundJobDefinitionReadiness.Active); + definition.Profile.Should().Be(BackgroundJobExecutionProfile.Transactional); + definition.Queue.Should().Be("transactional"); + definition.CapacityGroup.Should().BeNull(); + definition.RootRequestTypes.Should().Equal(root); + definition.NestedRequestTypes.Should().BeEmpty(); + } + + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportJobRegistration.cs")); + DataExportManifestSourceIsBound(source).Should().BeTrue(); + foreach (var (before, after) in new[] + { + ("BackgroundJobScope.Organization, typeof(DataExportPurgeParameters)", "BackgroundJobScope.TenantWide, typeof(DataExportPurgeParameters)"), + ("BackgroundJobDefinitionReadiness.Active", "BackgroundJobDefinitionReadiness.Pending"), + ("\"transactional\"", "\"external\""), + ("BackgroundJobProfileRegistration.Transactional(root)", "BackgroundJobProfileRegistration.Transactional(typeof(object))"), + }) + { + var dirty = source.Replace(before, after, StringComparison.Ordinal); + dirty.Should().NotBe(source); + DataExportManifestSourceIsBound(dirty).Should().BeFalse("the four export declarations cannot broaden their scope, readiness, queue or root"); + } + } + + private static bool DataExportManifestSourceIsBound(string source) + { + var syntax = CSharpSyntaxTree.ParseText(source).GetRoot(); + if (syntax.ContainsDiagnostics) return false; + var definition = syntax.DescendantNodes().OfType().SingleOrDefault(method => method.Identifier.ValueText == "Definition"); + var calls = syntax.DescendantNodes().OfType().Where(call => call.Expression.ToString() == "Definition").ToArray(); + var expectedCalls = new[] + { + "Definition(DataExportJobKeys.TenantExport.Value, BackgroundJobScope.TenantWide, typeof(DataExportJobParameters), typeof(RunTenantDataExportCommand))", + "Definition(DataExportJobKeys.OrganizationExport.Value, BackgroundJobScope.Organization, typeof(DataExportJobParameters), typeof(RunOrganizationDataExportCommand))", + "Definition(DataExportJobKeys.TenantPurge.Value, BackgroundJobScope.TenantWide, typeof(DataExportPurgeParameters), typeof(PurgeTenantDataExportCommand))", + "Definition(DataExportJobKeys.OrganizationPurge.Value, BackgroundJobScope.Organization, typeof(DataExportPurgeParameters), typeof(PurgeOrganizationDataExportCommand))", + }; + return definition?.ExpressionBody is { } body && SyntaxFactory.AreEquivalent(body.Expression, SyntaxFactory.ParseExpression( + "new(key, typeof(DataExportJobHandlers), parameters, scope, BackgroundJobDefinitionReadiness.Active, \"transactional\", " + + "BackgroundJobProfileRegistration.Transactional(root))")) + && calls.Length == 4 && calls.Select((call, index) => SyntaxFactory.AreEquivalent(call, SyntaxFactory.ParseExpression(expectedCalls[index]))).All(equal => equal); + } + private static bool InvitationManifestSourceIsBound(string source) { var syntax = CSharpSyntaxTree.ParseText(source).GetRoot(); @@ -258,15 +327,18 @@ private static SortedSet JobManifestOffenders(ProductionCensus census) .Select(instruction => (item.Owner, Instruction: instruction, Target: (MethodReference)instruction.Operand))).ToArray(); var invitation = types[("LearnStack.Modules.Identity.Infrastructure", typeof(InvitationEmailRegistration).FullName!)]; var invitationDefinition = invitation.Methods.Single(method => method.Name == "Definition"); + var dataExport = types[("LearnStack.Modules.Identity.Infrastructure", typeof(DataExportJobRegistration).FullName!)]; + var dataExportDefinition = dataExport.Methods.Single(method => method.Name == "Definition"); foreach (var registration in new[] { typeof(BackgroundJobDefinitionRegistration), typeof(BackgroundJobRecurrenceRegistration) }) { var target = types[(KernelAssembly, registration.FullName!)]; var constructions = sites.Where(site => SameType(site.Target.DeclaringType, target) && site.Target.Name == ".ctor").ToArray(); if (registration == typeof(BackgroundJobDefinitionRegistration)) - CheckSet(offenders, "exact invitation business-definition constructor", constructions.Select(site => MethodId(site.Owner)), [MethodId(invitationDefinition)]); + CheckSet(offenders, "exact invitation and data-export business-definition constructors", constructions.Select(site => MethodId(site.Owner)), + [MethodId(invitationDefinition), MethodId(dataExportDefinition)]); foreach (var site in constructions.Where(site => registration != typeof(BackgroundJobDefinitionRegistration) - || site.Owner != invitationDefinition || site.Instruction.OpCode != OpCodes.Newobj)) + || site.Owner != invitationDefinition && site.Owner != dataExportDefinition || site.Instruction.OpCode != OpCodes.Newobj)) offenders.Add("Production business/recurrence declaration: " + MethodId(site.Owner)); } diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs index 85caaf69..3eb1eaf9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs @@ -24,6 +24,8 @@ public sealed partial class IdentityAuditConventionTests 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"; + // ADR-0107 § 2: the data-request job store confirms its caller is one of the four export roots, as the invitation job store does. + private const string DataRequestJobStore = "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataRequestStore"; private const string InvitationProducer = "LearnStack.Application.Messaging.ProducerExecution"; private const string InvitationJobOrigin = InvitationProducer + "/JobOrigin"; private const string InvitationRegistration = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailRegistration"; @@ -79,10 +81,10 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m 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 }) + foreach (var owner in new[] { InvitationJobStore, InvitationStager, DataRequestJobStore }) { var adapter = module.GetType(owner); - var method = adapter.Methods.Single(candidate => candidate.Name == (owner == InvitationJobStore ? "RequireCurrentJob" : "StageAsync")); + var method = adapter.Methods.Single(candidate => candidate.Name == (owner == InvitationStager ? "StageAsync" : "RequireCurrentJob")); var extra = Instruction.Create(OpCodes.Ldftn, module.ImportReference(typeof(LearnStack.Application.Messaging.ProducerExecution).GetMethod("CaptureJobOrigin")!)); method.Body.Instructions.Add(extra); try { CoreEdgeViolations(adapter).Should().NotBeEmpty("the admitted adapter cannot acquire another executable producer alias"); } @@ -181,7 +183,7 @@ private static IEnumerable CoreEdgeViolations(TypeDefinition type) or "LearnStack.Application.Persistence.TransactionExecutionCoordinator/PreparedGlobalIdentityOwner" || type.FullName == InitialMigration && reference.FullName == Installer || type.FullName == RebindDdl && reference.FullName == RebindInstaller - || type.FullName is InvitationJobStore or InvitationStager + || type.FullName is InvitationJobStore or InvitationStager or DataRequestJobStore && reference.FullName is InvitationProducer or InvitationJobOrigin || type.FullName == InvitationRegistration && reference.FullName == FrameworkRequests; if (!allowed) yield return type.FullName + " -> " + reference.FullName; @@ -198,8 +200,8 @@ private static IEnumerable CoreEdgeViolations(TypeDefinition type) yield return "Invitation registration imports only the exact construction-free framework request list once"; yield break; } - if (type.FullName is not (InvitationJobStore or InvitationStager)) yield break; - var owner = type.FullName == InvitationJobStore ? "RequireCurrentJob" : "StageAsync"; + if (type.FullName is not (InvitationJobStore or InvitationStager or DataRequestJobStore)) yield break; + var owner = type.FullName == InvitationStager ? "StageAsync" : "RequireCurrentJob"; var calls = Il.Methods(type).Where(pair => pair.Definition.HasBody) .SelectMany(pair => pair.Definition.Body.Instructions.Where(instruction => instruction.Operand is MethodReference) .Select(instruction => (pair.DeclaredAs, Instruction: instruction, Target: (MethodReference)instruction.Operand))) @@ -213,6 +215,7 @@ private static IEnumerable CoreEdgeViolations(TypeDefinition type) || !(call.Target.DeclaringType.FullName == InvitationProducer && call.Target.Name is "CaptureJobOrigin" or "RequireJobOrigin" || call.Target.DeclaringType.FullName == InvitationProducer + "/JobOrigin" && (type.FullName == InvitationJobStore ? call.Target.Name is "get_ParentJobId" or "get_OperationType" + : type.FullName == DataRequestJobStore ? call.Target.Name is "get_ParentJobId" or "get_OperationType" or "get_Announcement" : call.Target.Name is "get_OperationType" or "get_Announcement"))) yield return type.FullName + " acquired an unapproved producer member or alias: " + call.Target.FullName; } diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs index 74b4ce7b..431a8519 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -120,6 +120,10 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard.AdmitAsync", "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler.Handle", "LearnStack.Modules.Identity.Application.Federation.FederationCommandHandlers.ActAsync", + // ADR-0107 § 2, § 5: the export job and the failure reconciler hold the shared tenant fence the request + // guard requires of every request write; neither admits a Membership. + "LearnStack.Modules.Identity.Application.DataRequests.DataExportJobHandlers.ExportAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestFailureReconciler.ReconcileAsync", ]; // A retained-plan check is not another acquisition: the guards, bounded // reader and two separately confined source/witness pairs must recheck it. diff --git a/backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs b/backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs new file mode 100644 index 00000000..0d96d0c5 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs @@ -0,0 +1,164 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0107 § 1: every module whose model holds a person reference registers exactly one +/// through the composition root, from inside its own boundary, and no module +/// references another module's participant. Each detector is proved able to fail by a planted violation. +/// +public sealed class UserDataParticipantCensusTests +{ + [Fact] + public void Every_Module_With_A_Person_Reference_Registers_One_User_Data_Participant() + { + var registered = RegisteredParticipants(); + var referencing = ModulesWithPersonReferences(); + + referencing.Should().BeEquivalentTo(["Audit", "Customization", "Education", "Identity", "Tenancy"], + "the census covers every module whose model maps a person reference"); + CensusOffenders(referencing, registered).Should().BeEmpty(); + + // Planted: a module that stops registering its participant is named. + foreach (var module in referencing) + { + var missing = registered.Where(type => ModuleOf(type.Assembly) != module).ToArray(); + CensusOffenders(referencing, missing).Should().ContainSingle() + .Which.Should().Be("Missing user data participant registration: " + module); + } + + // Planted: a second participant inside one module, and one outside every module, are named. + CensusOffenders(referencing, [.. registered, typeof(PlantedParticipant)]) + .Should().Contain("User data participant outside a module boundary: " + typeof(PlantedParticipant).FullName); + var twice = registered.Append(registered.First(type => ModuleOf(type.Assembly) == "Identity")).ToArray(); + CensusOffenders(referencing, twice).Should().Contain("More than one user data participant: Identity"); + } + + [Fact] + public void No_Module_References_Another_Modules_User_Data_Participant() + { + var registered = RegisteredParticipants(); + var references = ModuleAssemblies().ToDictionary(assembly => assembly.GetName().Name!, + assembly => (IReadOnlyCollection)assembly.GetReferencedAssemblies().Select(name => name.Name!).ToArray(), + StringComparer.Ordinal); + + ReferenceOffenders(registered, references).Should().BeEmpty(); + + // Planted: Education reaching Tenancy's participant assembly is named. + var tenancy = registered.Single(type => ModuleOf(type.Assembly) == "Tenancy").Assembly.GetName().Name!; + var planted = new Dictionary>(references, StringComparer.Ordinal) + { + ["LearnStack.Modules.Education.Infrastructure"] = [.. references["LearnStack.Modules.Education.Infrastructure"], tenancy], + }; + ReferenceOffenders(registered, planted).Should().ContainSingle() + .Which.Should().Be("LearnStack.Modules.Education.Infrastructure references " + tenancy); + } + + /// Every participant the API composition actually registers, Identity's and the root's own. + private static Type[] RegisteredParticipants() + { + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new ConfigurationBuilder().Build()); + return services.Where(descriptor => descriptor.ServiceType == typeof(IUserDataParticipant)) + .Select(descriptor => descriptor.ImplementationType + ?? throw new InvalidOperationException("A participant is registered by its concrete type.")) + .ToArray(); + } + + /// A module whose mapped model has a property holds a person reference. + private static string[] ModulesWithPersonReferences() => + Modules.Mapped.Where(module => + { + using var context = module.Context(); + return context.Model.GetEntityTypes().SelectMany(entity => entity.GetProperties()) + .Any(property => property.ClrType == typeof(UserId) || property.ClrType == typeof(UserId?)); + }) + .Select(module => ModuleOf(module.Domain)!) + .Order(StringComparer.Ordinal).ToArray(); + + private static List CensusOffenders(IReadOnlyCollection referencing, IReadOnlyCollection registered) + { + var offenders = new List(); + foreach (var participant in registered.Where(type => ModuleOf(type.Assembly) is null)) + { + offenders.Add("User data participant outside a module boundary: " + participant.FullName); + } + + foreach (var group in registered.Where(type => ModuleOf(type.Assembly) is not null).GroupBy(type => ModuleOf(type.Assembly)!)) + { + if (group.Count() > 1) + { + offenders.Add("More than one user data participant: " + group.Key); + } + } + + foreach (var module in referencing) + { + if (!registered.Any(type => ModuleOf(type.Assembly) == module)) + { + offenders.Add("Missing user data participant registration: " + module); + } + } + + return offenders; + } + + private static List ReferenceOffenders(IReadOnlyCollection participants, + IReadOnlyDictionary> references) + { + var offenders = new List(); + foreach (var participant in participants) + { + var owner = ModuleOf(participant.Assembly); + var home = participant.Assembly.GetName().Name!; + foreach (var (assembly, referenced) in references.OrderBy(pair => pair.Key, StringComparer.Ordinal)) + { + if (ModuleOf(assembly) is { } module && module != owner && referenced.Contains(home, StringComparer.Ordinal)) + { + offenders.Add(assembly + " references " + home); + } + } + } + + return offenders; + } + + private static readonly string[] Legs = ["Domain", "Application.Contracts", "Application", "Infrastructure"]; + + private static IEnumerable ModuleAssemblies() => + Modules.Names.SelectMany(module => Legs.Select(leg => Assembly.Load("LearnStack.Modules." + module + "." + leg))); + + private static string? ModuleOf(Assembly assembly) => ModuleOf(assembly.GetName().Name!); + + private static string? ModuleOf(string assembly) + { + const string prefix = "LearnStack.Modules."; + if (!assembly.StartsWith(prefix, StringComparison.Ordinal)) + { + return null; + } + + var rest = assembly[prefix.Length..]; + return rest[..rest.IndexOf('.', StringComparison.Ordinal)]; + } + + private sealed class PlantedParticipant : IUserDataParticipant + { + public string Key => "planted"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => + Task.CompletedTask; + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs index 6019ffcd..99411b86 100644 --- a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs @@ -179,13 +179,23 @@ private static List ManifestOffenders(IServiceProvider services) { var definitions = services.GetRequiredService(); var recurrences = services.GetRequiredService(); - var expectedDefinitions = new[] { "identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1" }; + var expectedDefinitions = new[] + { + "identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1", + // ADR-0107 § 2: export and artifact purge, once per scope group. + "identity.data_export_tenant.v1", "identity.data_export_organization.v1", + "identity.data_export_purge_tenant.v1", "identity.data_export_purge_organization.v1", + }; (Type RequestType, BackgroundJobScope? Scope)[] expectedRequests = { (typeof(PrepareTenantInvitationEmailCommand), BackgroundJobScope.TenantWide), (typeof(PrepareOrganizationInvitationEmailCommand), BackgroundJobScope.Organization), (typeof(FinalizeTenantInvitationEmailCommand), BackgroundJobScope.TenantWide), (typeof(FinalizeOrganizationInvitationEmailCommand), BackgroundJobScope.Organization), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.RunTenantDataExportCommand), BackgroundJobScope.TenantWide), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.RunOrganizationDataExportCommand), BackgroundJobScope.Organization), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.PurgeTenantDataExportCommand), BackgroundJobScope.TenantWide), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.PurgeOrganizationDataExportCommand), BackgroundJobScope.Organization), }; var actualDefinitions = definitions.DefinitionKeys.ToArray(); var actualRequests = definitions.All.Where(item => item.Classification == BackgroundJobRequestClassification.Ordinary) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportArtifactStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportArtifactStoreTests.cs new file mode 100644 index 00000000..f4aa5ed1 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportArtifactStoreTests.cs @@ -0,0 +1,209 @@ +using FluentAssertions; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Time; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 4: as learnstack_app on the ambient group +/// transaction of the seeded schema — sealed chunks that read back, the group bound, revocation that leaves no +/// ciphertext, and the database guards behind it. Every case rolls back. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataExportArtifactStoreTests(SchemaFixture schema) +{ + private const int Size = (2 * DataRequestLimits.ChunkPlaintextBytes) + 77; + + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task A_put_bundle_reads_back_chunk_by_chunk_and_a_revocation_leaves_no_ciphertext(string group) + { + var (tenant, organization, subject, membership) = group == "tenant" + ? (SchemaFixture.TenantA, (Guid?)null, AdminA, AdminMembershipA) + : (SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, BranchMembershipA1); + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, tenant, organization, [subject]); + using var cipher = DataExportTestKit.Cipher(); + var store = Store(scope, cipher); + if (organization is not null) + { + // The seeded subject already holds an available artifact in this group: withdraw it first, as the export does. + (await store.PurgeAsync(new DataExportArtifactLocator(BranchA1.Artifact!.Value, new DataRequestScopeGroup( + TenantId.From(tenant), OrganizationId.From(organization.Value))), DataExportArtifactStatus.Revoked, CancellationToken.None)) + .Should().Be(DataExportArtifactStatus.Revoked); + } + + var request = await FulfillingRequestAsync(scope, subject, membership); + var bundle = Bundle(Size); + var artifactId = Guid.CreateVersion7(); + + var put = await store.PutAsync(new DataExportArtifactPut(artifactId, request.Id.Value, request.SubjectUserId, request.Group, + Size, [new DataExportTruncation("audit.entries", 3, 9)]), Chunks(bundle), CancellationToken.None); + + put.Status.Should().Be(DataExportArtifactStatus.Available); + put.ChunkCount.Should().Be(3); + put.KeyVersion.Should().Be(cipher.ActiveKeyVersion); + put.IsReadable.Should().BeTrue(); + put.Truncations.Should().Equal(new DataExportTruncation("audit.entries", 3, 9)); + var locator = new DataExportArtifactLocator(artifactId, request.Group); + var metadata = (await store.ReadMetadataAsync(locator, CancellationToken.None))!; + metadata.IsReadable.Should().BeTrue(); + metadata.ByteCount.Should().Be(Size); + metadata.Truncations.Should().Equal(put.Truncations); + var read = new List(); + for (var index = 0; index < 3; index++) + { + var chunk = (await store.ReadChunkAsync(locator, index, CancellationToken.None))!; + chunk.Index.Should().Be(index); + chunk.Count.Should().Be(3); + read.AddRange(chunk.Bytes.ToArray()); + } + + read.Should().Equal(bundle); + (await store.ReadChunkAsync(locator, 3, CancellationToken.None)).Should().BeNull(); + (await store.ReadChunkAsync(locator, -1, CancellationToken.None)).Should().BeNull(); + (await ScalarAsync(scope.Connection, scope.Transaction, + "SELECT count(*) FROM public.data_export_chunks WHERE artifact_id=@id AND position(@probe in ciphertext) > 0", + ("id", artifactId), ("probe", bundle[..32]))).Should().Be(0, "no stored chunk holds the plaintext"); + await ExecuteAsync(scope.Connection, scope.Transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(scope.Connection, scope.Transaction, "SET CONSTRAINTS ALL DEFERRED"); + + (await store.PurgeAsync(locator, DataExportArtifactStatus.Purged, CancellationToken.None)) + .Should().Be(DataExportArtifactStatus.Available, "a purge before the expiry changes nothing"); + (await store.PurgeAsync(locator, DataExportArtifactStatus.Revoked, CancellationToken.None)) + .Should().Be(DataExportArtifactStatus.Revoked); + (await store.PurgeAsync(locator, DataExportArtifactStatus.Revoked, CancellationToken.None)) + .Should().Be(DataExportArtifactStatus.Revoked, "repeating a revocation changes nothing"); + (await store.ReadChunkAsync(locator, 0, CancellationToken.None)).Should().BeNull(); + var revoked = (await store.ReadMetadataAsync(locator, CancellationToken.None))!; + revoked.Status.Should().Be(DataExportArtifactStatus.Revoked); + revoked.IsReadable.Should().BeFalse(); + revoked.PurgedAt.Should().NotBeNull(); + (await ScalarAsync(scope.Connection, scope.Transaction, + "SELECT count(*) FROM public.data_export_chunks WHERE artifact_id=@id", ("id", artifactId))).Should().Be(0); + await ExecuteAsync(scope.Connection, scope.Transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + var refusal = await RefuseAsync(scope.Transaction, () => InsertChunkAsync(scope.Connection, scope.Transaction, tenant, + organization, artifactId, 0)); + refusal.MessageText.Should().Be("Data export chunk refused.", "a revoked artifact takes no chunk again"); + await scope.Frame.FailAsync(); + } + + [Theory] + [InlineData("short_middle")] + [InlineData("long_last")] + [InlineData("missing")] + [InlineData("extra")] + [InlineData("other_request")] + public async Task A_put_that_does_not_match_its_declared_bundle_is_refused(string shape) + { + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, null, [AdminA]); + using var cipher = DataExportTestKit.Cipher(); + var store = Store(scope, cipher); + var request = await FulfillingRequestAsync(scope, AdminA, AdminMembershipA); + var bundle = Bundle(Size); + var chunks = shape switch + { + "short_middle" => Pieces(bundle[..DataRequestLimits.ChunkPlaintextBytes], bundle[(DataRequestLimits.ChunkPlaintextBytes + 1)..]), + "long_last" => Pieces(bundle[..DataRequestLimits.ChunkPlaintextBytes], bundle[DataRequestLimits.ChunkPlaintextBytes..(2 * DataRequestLimits.ChunkPlaintextBytes)], + [.. bundle[(2 * DataRequestLimits.ChunkPlaintextBytes)..], 1]), + "missing" => Pieces(bundle[..DataRequestLimits.ChunkPlaintextBytes]), + "extra" => Pieces([.. Chunked(bundle), new byte[] { 1 }]), + _ => Pieces(Chunked(bundle)), + }; + var put = new DataExportArtifactPut(Guid.CreateVersion7(), shape == "other_request" ? Guid.CreateVersion7() : request.Id.Value, + request.SubjectUserId, request.Group, Size); + + var act = () => store.PutAsync(put, chunks, CancellationToken.None); + + await act.Should().ThrowAsync(); + await scope.Frame.FailAsync(); + } + + [Fact] + public async Task An_artifact_is_reachable_only_from_its_own_group() + { + // Committed rows: a disposable copy of the seeded schema, so the shared one keeps its census. + await using var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await BackgroundJobSchemaSeed.SeedTenantsAsync(database.AppConnectionString); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + Guid artifactId; + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null, [AdminA])) + { + using var cipher = DataExportTestKit.Cipher(); + var store = Store(scope, cipher); + var request = await FulfillingRequestAsync(scope, AdminA, AdminMembershipA); + artifactId = Guid.CreateVersion7(); + await store.PutAsync(new DataExportArtifactPut(artifactId, request.Id.Value, request.SubjectUserId, request.Group, 10), + Pieces(Bundle(10)), CancellationToken.None); + var foreign = new DataExportArtifactLocator(artifactId, new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), + OrganizationId.From(SchemaFixture.OrgA1))); + await FluentActions.Awaiting(() => store.ReadMetadataAsync(foreign, CancellationToken.None)) + .Should().ThrowAsync("a locator names the announced group or nothing"); + await scope.Frame.CompleteAsync(); + } + + foreach (var (tenant, organization) in new (Guid, Guid?)[] + { (SchemaFixture.TenantB, null), (SchemaFixture.TenantA, SchemaFixture.OrgA1) }) + { + await using var other = await DataExportTestKit.OpenAsync(database.AppConnectionString, tenant, organization); + using var cipher = DataExportTestKit.Cipher(); + var store = Store(other, cipher); + var locator = new DataExportArtifactLocator(artifactId, new DataRequestScopeGroup(TenantId.From(tenant), + organization is { } org ? OrganizationId.From(org) : null)); + (await store.ReadMetadataAsync(locator, CancellationToken.None)).Should().BeNull(); + (await store.ReadChunkAsync(locator, 0, CancellationToken.None)).Should().BeNull(); + (await store.PurgeAsync(locator, DataExportArtifactStatus.Revoked, CancellationToken.None)).Should().BeNull(); + await other.Frame.FailAsync(); + } + } + + internal static PostgresDataExportArtifactStore Store(DataExportTestKit.GroupScope scope, DataExportCipher cipher) => + new(scope.Db, scope.Unit, scope.Context, cipher, new SystemClock(), new DataExportTestKit.NoAuditSubject()); + + /// A fresh export of the subject in the scope's group, saved through the aggregate and fulfilling. + private static async Task FulfillingRequestAsync(DataExportTestKit.GroupScope scope, Guid subject, Guid membership) + { + var now = DateTimeOffset.UtcNow; + var request = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, + UserId.From(subject), new DataRequestScopeGroup(scope.Context.TenantId, scope.Context.OrganizationId), + [MembershipId.From(membership)], now).Value!; + scope.Db.Add(request); + await scope.Db.SaveChangesAsync(); + request.StartFulfilling(now, UserId.SystemActor).IsSuccess.Should().BeTrue(); + await scope.Db.SaveChangesAsync(); + return request; + } + + private static byte[] Bundle(int length) => Enumerable.Range(0, length).Select(index => (byte)('a' + (index % 26))).ToArray(); + + private static byte[][] Chunked(byte[] bundle) => + bundle.Chunk(DataRequestLimits.ChunkPlaintextBytes).ToArray(); + + private static IAsyncEnumerable> Chunks(byte[] bundle) => Pieces(Chunked(bundle)); + + private static async IAsyncEnumerable> Pieces(params byte[][] pieces) + { + foreach (var piece in pieces) + { + await Task.Yield(); + yield return piece; + } + } + + private static async Task RefuseAsync(NpgsqlTransaction transaction, Func act) + { + await transaction.SaveAsync("probe"); + var refusal = (await act.Should().ThrowAsync()).Which; + await transaction.RollbackAsync("probe"); + return refusal; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs new file mode 100644 index 00000000..7dc8716c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs @@ -0,0 +1,566 @@ +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Time; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using LearnStack.Application.Messaging; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 2–§ 4 through the actual job runtime and the actual composition root: a seeded export request runs +/// as its registered transactional definition, as learnstack_app under the job's own tenant transaction, to a +/// completed request and an encrypted artifact that decrypts to the expected bundle — and every way it must not. +/// Each case owns a disposable copy of the seeded schema. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class DataExportExecutionTests(SchemaFixture fixture) +{ + private static readonly string[] Participants = ["audit", "customization", "education", "identity", "tenancy"]; + private DisposableSchemaDatabase? _database; + + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task An_export_runs_to_completed_with_one_decryptable_bundle_and_withdraws_the_earlier_artifact(string scope) + { + await using var database = await OpenDatabaseAsync(); + var (organization, membership, earlier) = scope == "tenant" + ? ((Guid?)null, LearnerMembershipA, TenantWideA.Artifact!.Value) + : (SchemaFixture.OrgA1, BranchMembershipA1, BranchA1.Artifact!.Value); + await using var host = Host(); + var request = await FileExportAsync(SchemaFixture.TenantA, organization, PersonA, membership); + var job = await SubmitAsync(SchemaFixture.TenantA, organization, request); + + var result = await RunAsync(host.Services, job); + + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + var state = await RequestAsync(SchemaFixture.TenantA, organization, request); + state.Status.Should().Be("completed"); + state.Failure.Should().BeNull(); + JsonDocument.Parse(state.Progress).RootElement.EnumerateObject().Select(entry => entry.Name).Should().BeEquivalentTo(Participants, + "every registered participant's completion is recorded"); + JsonDocument.Parse(state.Result).RootElement.EnumerateObject().Select(entry => entry.Name).Should() + .Contain(["request_receipt", "invitation_record", "attribution_reference", "consent_evidence", + "audit_actor_reference", "audit_entity_reference", "audit_metadata_reference"]); + var artifacts = await ArtifactsAsync(SchemaFixture.TenantA, organization, PersonA); + var stored = artifacts.Single(artifact => artifact.Request == request); + stored.Status.Should().Be("available"); + stored.Chunks.Should().Be(stored.ChunkCount); + stored.Truncation.Should().Be("{}"); + var withdrawn = artifacts.Single(artifact => artifact.Id == earlier); + withdrawn.Status.Should().Be("revoked", "a subject holds one available artifact per group"); + withdrawn.Chunks.Should().Be(0); + (await PurgeJobsAsync(SchemaFixture.TenantA, organization, stored.Id)).Should().ContainSingle() + .Which.Should().Be(stored.ExpiresAt, "the purge is scheduled at the artifact's expiry"); + + using var bundle = await DecryptAsync(host.Services, SchemaFixture.TenantA, organization, stored.Id); + var text = bundle.RootElement.GetRawText(); + var root = bundle.RootElement; + root.GetProperty("request").GetProperty("id").GetString().Should().Be(request.ToString("D")); + root.GetProperty("request").GetProperty("scope").GetString().Should().Be(scope); + root.GetProperty("sections").EnumerateObject().Select(section => section.Name).Should().Equal(Participants); + var memberships = root.GetProperty("sections").GetProperty("identity").GetProperty("memberships"); + memberships.GetArrayLength().Should().Be(1, "only the request's group, never another organization of the same person"); + memberships[0].GetProperty("scope").GetString().Should().Be(scope); + memberships[0].GetProperty("status").GetString().Should().Be("active"); + memberships[0].GetProperty("roles").EnumerateArray().Select(role => role.GetString()).Should().Equal("learner"); + memberships[0].GetProperty("profile").GetProperty("display_name").GetString().Should().Be("profile-canary"); + root.GetProperty("truncated").EnumerateObject().Should().BeEmpty(); + Identifier().Matches(text).Select(match => match.Value).Should().OnlyContain(value => value == request.ToString("D"), + "the bundle names no internal identifier but its own request"); + text.Should().NotContain("fixture-subject").And.NotContain("verifier").And.NotContain("subject_key"); + + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.data_request.fulfill_export", request.ToString("D"))) + .Should().Be(1, "the fulfilment is one MUST row about the request"); + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.data_export.store", stored.Id.ToString("D"))) + .Should().Be(1, "and one about the stored artifact"); + } + + [Theory] + [InlineData("missing")] + [InlineData("cancelled")] + [InlineData("completed")] + public async Task A_missing_cancelled_or_completed_request_completes_its_job_as_a_recorded_no_op(string state) + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(); + var request = Guid.CreateVersion7(); + if (state != "missing") + { + request = await FileExportAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, BranchMembershipA2); + } + + if (state == "cancelled") + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA2, null); + await StepAsync(app, transaction, request, "status='cancelled'"); + await transaction.CommitAsync(); + } + else if (state == "completed") + { + (await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, request))).CommitAcknowledged.Should().BeTrue(); + } + + var before = await ArtifactsAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA); + + var result = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, request)); + + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + (await ArtifactsAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA)).Should().BeEquivalentTo(before, "a no-op stores nothing"); + if (state != "missing") + { + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, request)).Status.Should().Be(state); + } + + (await AuditAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, "identity.data_request.fulfill_export", null)) + .Should().Be(state == "completed" ? 2 : 1, "every run, a no-op included, writes its MUST row"); + } + + [Fact] + public async Task A_failed_attempt_rolls_every_write_back_and_the_retry_stores_exactly_once() + { + await using var database = await OpenDatabaseAsync(); + var probe = new FailingParticipant(); + await using var host = Host(services => services.AddSingleton(probe)); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + + var failed = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request)); + + failed.CommitAcknowledged.Should().BeFalse(); + failed.KnownRollback.Should().BeTrue(); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("requested", "the attempt's transitions rolled back"); + var untouched = await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA); + untouched.Should().NotContain(artifact => artifact.Request == request); + untouched.Single(artifact => artifact.Id == TenantWideA.Artifact!.Value).Status.Should().Be("available", + "the earlier artifact is withdrawn only together with its successor"); + + var retried = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request)); + var again = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request)); + + retried.CommitAcknowledged.Should().BeTrue(); + again.CommitAcknowledged.Should().BeTrue(); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("completed"); + var artifacts = await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA); + artifacts.Count(artifact => artifact.Request == request).Should().Be(1, "a retried or repeated run never stores twice"); + (await PurgeJobsAsync(SchemaFixture.TenantA, null, artifacts.Single(artifact => artifact.Request == request).Id)).Should().ContainSingle(); + } + + [Fact] + public async Task The_bundle_ceiling_fails_the_request_with_export_too_large_and_stores_nothing() + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(services => services.AddSingleton(new BulkParticipant()), + maxBytes: DataRequestLimits.MinimumBundleBytes); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + + var result = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request)); + + result.CommitAcknowledged.Should().BeTrue(); + var state = await RequestAsync(SchemaFixture.TenantA, null, request); + state.Status.Should().Be("failed"); + state.Failure.Should().Be("export_too_large"); + var artifacts = await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA); + artifacts.Should().NotContain(artifact => artifact.Request == request); + artifacts.Single(artifact => artifact.Id == TenantWideA.Artifact!.Value).Status.Should().Be("available"); + } + + [Fact] + public async Task A_capped_section_is_stated_in_the_bundle_and_kept_on_the_artifact_receipt() + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(services => services.AddSingleton(new CappedParticipant())); + var request = await FileExportAsync(SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, BranchMembershipB, existing: BranchB.Request); + + var result = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantB, SchemaFixture.OrgB1, request)); + + result.CommitAcknowledged.Should().BeTrue(); + var stored = (await ArtifactsAsync(SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB)).Single(artifact => artifact.Request == request); + var receipt = JsonDocument.Parse(stored.Truncation).RootElement.GetProperty("capped.entries"); + var included = receipt.GetProperty("included").GetInt64(); + included.Should().BeGreaterThan(0).And.BeLessThan(CappedParticipant.Total); + receipt.GetProperty("total").GetInt64().Should().Be(CappedParticipant.Total); + using var bundle = await DecryptAsync(host.Services, SchemaFixture.TenantB, SchemaFixture.OrgB1, stored.Id); + bundle.RootElement.GetProperty("sections").GetProperty("capped").GetProperty("entries").GetArrayLength().Should().Be((int)included); + bundle.RootElement.GetProperty("truncated").GetProperty("capped.entries").GetProperty("included").GetInt64().Should().Be(included); + } + + [Fact] + public async Task An_expired_artifact_is_unreadable_before_its_purge_and_the_purge_job_then_removes_every_chunk() + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + (await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request))).CommitAcknowledged.Should().BeTrue(); + var stored = (await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA)).Single(artifact => artifact.Request == request); + await BackdateAsync(SchemaFixture.TenantA, stored.Id); + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + using var cipher = DataExportTestKit.Cipher(); + var store = DataExportArtifactStoreTests.Store(scope, cipher); + var locator = new DataExportArtifactLocator(stored.Id, new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null)); + var metadata = (await store.ReadMetadataAsync(locator, CancellationToken.None))!; + metadata.Status.Should().Be(DataExportArtifactStatus.Available, "the purge has not run"); + metadata.IsReadable.Should().BeFalse("expiry is a time check against the database clock"); + (await store.ReadChunkAsync(locator, 0, CancellationToken.None)).Should().BeNull(); + await scope.Frame.FailAsync(); + } + + var purge = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, "identity.data_export_purge_tenant.v1", + tenant: SchemaFixture.TenantA, parameters: BackgroundJobPayloadContract.Serialize(new DataExportPurgeParameters(stored.Id), + typeof(DataExportPurgeParameters), BackgroundJobPayloadKind.Parameters)); + (await RunAsync(host.Services, purge)).CommitAcknowledged.Should().BeTrue(); + (await RunAsync(host.Services, await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, + "identity.data_export_purge_tenant.v1", tenant: SchemaFixture.TenantA, parameters: BackgroundJobPayloadContract.Serialize( + new DataExportPurgeParameters(stored.Id), typeof(DataExportPurgeParameters), BackgroundJobPayloadKind.Parameters)))) + .CommitAcknowledged.Should().BeTrue("a purge of a purged artifact is a no-op"); + + var purged = (await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA)).Single(artifact => artifact.Id == stored.Id); + purged.Status.Should().Be("purged"); + purged.Chunks.Should().Be(0); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.data_export.purge", stored.Id.ToString("D"))).Should().BeGreaterThanOrEqualTo(1); + } + + [Fact] + public async Task A_dead_export_job_reads_as_failed_and_the_reconciler_stores_it_and_frees_the_slot() + { + await using var database = await OpenDatabaseAsync(); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var job = await SubmitAsync(SchemaFixture.TenantA, null, request); + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + var (reconciler, reader, store) = Reconciler(scope); + var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; + (await reader.ReadAsync(loaded, CancellationToken.None)).Should().Be(DataRequestJobPhase.Pending); + DataRequestFailureReconciler.EffectiveStatus(loaded, DataRequestJobPhase.Pending).Should().Be(DataRequestStatus.Requested); + (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().BeFalse("a live job may still finish"); + await scope.Frame.FailAsync(); + } + + await using (var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.OutboxConnectionString)) + await SchemaQueries.ExecuteAsync(dispatcher, null, + "UPDATE background_jobs SET phase='quarantined', quarantine_reason='unknown_outcome' WHERE id=@id", ("id", job.Value)); + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + var (reconciler, reader, store) = Reconciler(scope); + var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; + var phase = await reader.ReadAsync(loaded, CancellationToken.None); + phase.Should().Be(DataRequestJobPhase.Dead); + DataRequestFailureReconciler.EffectiveStatus(loaded, phase).Should().Be(DataRequestStatus.Failed, + "the receipt shows failed without writing"); + (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().BeTrue(); + loaded.Status.Should().Be(DataRequestStatus.Failed); + loaded.FailureReason.Should().Be(DataRequestFailureReason.ExecutionFailed); + (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().BeFalse("a terminal request is left alone"); + await scope.Frame.CompleteAsync(); + } + + var state = await RequestAsync(SchemaFixture.TenantA, null, request); + state.Status.Should().Be("failed"); + state.Failure.Should().Be("execution_failed"); + var next = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + (await RequestAsync(SchemaFixture.TenantA, null, next)).Status.Should().Be("requested", "the stored failure freed the slot"); + } + + private static (DataRequestFailureReconciler Reconciler, DataRequestJobPhaseReader Reader, DataRequestStore Store) Reconciler( + DataExportTestKit.GroupScope scope) + { + var store = new DataRequestStore(scope.Db, scope.Unit, new ProducerExecution(scope.Unit), scope.Context); + var reader = new DataRequestJobPhaseReader(scope.Unit, scope.Context); + return (new DataRequestFailureReconciler(store, reader, new LearnStack.Infrastructure.Persistence.IdentityMutationLocks(scope.Unit), + scope.Context, new SystemClock()), reader, store); + } + + private async Task OpenDatabaseAsync() + { + _database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await BackgroundJobSchemaSeed.SeedTenantsAsync(_database.AppConnectionString); + await SeedSchemaAsync(_database.MigrationConnectionString, _database.AppConnectionString); + return _database; + } + + private WebApplicationFactory Host(Action? configure = null, long? maxBytes = null) => + new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", _database!.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", _database!.OutboxConnectionString); + if (maxBytes is { } ceiling) + { + builder.UseSetting("DataExport:MaxBytes", ceiling.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + if (configure is not null) + { + builder.ConfigureTestServices(configure); + } + }); + + /// A self-filed export in its initial state, under the canonical fences; or the seeded one. + private async Task FileExportAsync(Guid tenant, Guid? organization, Guid subject, Guid membership, Guid? existing = null) + { + if (existing is { } seeded) + { + return seeded; + } + + var id = Guid.CreateVersion7(); + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, subject); + await InsertRequestAsync(app, transaction, id, tenant, organization, subject, [membership]); + await transaction.CommitAsync(); + return id; + } + + private Task SubmitAsync(Guid tenant, Guid? organization, Guid request) => + BackgroundJobRuntimeRows.InsertAsync(_database!.AppConnectionString, + organization is null ? "identity.data_export_tenant.v1" : "identity.data_export_organization.v1", + organization: organization, tenant: tenant, parameters: BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(request), + typeof(DataExportJobParameters), BackgroundJobPayloadKind.Parameters)); + + private async Task RunAsync(IServiceProvider services, BackgroundJobId job) + { + var executor = services.GetRequiredService(); + var start = await executor.ExecuteAsync(await RoutingClaim.ClaimAsync(_database!.OutboxConnectionString, job), BackgroundJobTestRun.Create()); + start.Outcome.Should().Be(JobStartExecutionOutcome.Started); + return await executor.ExecuteBusinessAsync(start.Receipt!, start.Receipt!.Run.OpenBoundary(BackgroundJobCheckpointKind.Transactional)); + } + + private sealed record RequestState(string Status, string Progress, string Result, string? Failure); + + private sealed record ArtifactState(Guid Id, Guid Request, string Status, int ChunkCount, long Chunks, string Truncation, + DateTimeOffset ExpiresAt); + + private async Task RequestAsync(Guid tenant, Guid? organization, Guid request) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand( + "SELECT status, progress::text, result::text, failure_reason FROM public.data_subject_requests WHERE id=@id", app, transaction); + command.Parameters.AddWithValue("id", request); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new RequestState(row.GetString(0), row.GetString(1), row.GetString(2), row.IsDBNull(3) ? null : row.GetString(3)); + } + + private async Task> ArtifactsAsync(Guid tenant, Guid? organization, Guid subject) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT a.id, a.request_id, a.status, a.chunk_count, + (SELECT count(*) FROM public.data_export_chunks AS c WHERE c.tenant_id=a.tenant_id AND c.artifact_id=a.id), + a.truncation::text, a.expires_at + FROM public.data_export_artifacts AS a + WHERE a.subject_user_id=@subject AND a.organization_id IS NOT DISTINCT FROM @organization + ORDER BY a.id + """, app, transaction); + command.Parameters.AddWithValue("subject", subject); + command.Parameters.AddWithValue("organization", NpgsqlTypes.NpgsqlDbType.Uuid, (object?)organization ?? DBNull.Value); + var artifacts = new List(); + await using var row = await command.ExecuteReaderAsync(); + while (await row.ReadAsync()) + { + artifacts.Add(new ArtifactState(row.GetGuid(0), row.GetGuid(1), row.GetString(2), row.GetInt32(3), row.GetInt64(4), + row.GetString(5), new DateTimeOffset(row.GetDateTime(6), TimeSpan.Zero))); + } + + return artifacts; + } + + private async Task> PurgeJobsAsync(Guid tenant, Guid? organization, Guid artifact) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT original_due_at FROM public.background_jobs + WHERE definition_key=@key AND profile='transactional' AND parameters=@parameters + AND organization_id IS NOT DISTINCT FROM @organization + """, app, transaction); + command.Parameters.AddWithValue("key", organization is null ? "identity.data_export_purge_tenant.v1" : "identity.data_export_purge_organization.v1"); + command.Parameters.AddWithValue("parameters", BackgroundJobPayloadContract.Serialize(new DataExportPurgeParameters(artifact), + typeof(DataExportPurgeParameters), BackgroundJobPayloadKind.Parameters)); + command.Parameters.AddWithValue("organization", NpgsqlTypes.NpgsqlDbType.Uuid, (object?)organization ?? DBNull.Value); + var due = new List(); + await using var row = await command.ExecuteReaderAsync(); + while (await row.ReadAsync()) + { + due.Add(new DateTimeOffset(row.GetDateTime(0), TimeSpan.Zero)); + } + + return due; + } + + private async Task AuditAsync(Guid tenant, Guid? organization, string operation, string? entity) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + return await ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.audit_log + WHERE operation=@operation AND organization_id IS NOT DISTINCT FROM @organization::uuid + AND (@entity::text IS NULL OR entity_id=@entity::text) + """, ("operation", operation), ("organization", (object?)organization ?? DBNull.Value), ("entity", (object?)entity ?? DBNull.Value)); + } + + /// Reads every chunk as the application role and opens it with the host's own key ring and binding. + private async Task DecryptAsync(IServiceProvider services, Guid tenant, Guid? organization, Guid artifact) + { + var cipher = services.GetRequiredService(); + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT a.request_id, a.chunk_count, a.key_version, c.chunk_index, c.nonce, c.ciphertext, c.tag + FROM public.data_export_artifacts AS a JOIN public.data_export_chunks AS c ON c.tenant_id=a.tenant_id AND c.artifact_id=a.id + WHERE a.id=@id ORDER BY c.chunk_index + """, app, transaction); + command.Parameters.AddWithValue("id", artifact); + var plaintext = new List(); + await using var row = await command.ExecuteReaderAsync(); + while (await row.ReadAsync()) + { + plaintext.AddRange(cipher.Open(new DataExportChunkBinding(tenant, row.GetGuid(0), artifact, row.GetInt32(3), row.GetInt32(1)), + new DataExportSealedChunk(row.GetString(2), (byte[])row[4], (byte[])row[5], (byte[])row[6]))); + } + + return JsonDocument.Parse(plaintext.ToArray()); + } + + /// Moves an artifact eight days into the past as the owner, with its guard paused and restored. + private async Task BackdateAsync(Guid tenant, Guid artifact) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_artifacts DISABLE TRIGGER tg_data_export_artifacts_mutation_guard"); + await ScopeAsync(owner, transaction, tenant); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_export_artifacts SET created_at=created_at - interval '8 days', expires_at=expires_at - interval '8 days' + WHERE id=@id + """, ("id", artifact)); + await ExecuteAsync(owner, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_artifacts ENABLE TRIGGER tg_data_export_artifacts_mutation_guard"); + await transaction.CommitAsync(); + } + + private async Task OpenAppAsync() + { + var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + return app; + } + + [GeneratedRegex("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}")] + private static partial Regex Identifier(); + + /// Throws on its first export and succeeds afterwards: a transient failure inside the business transaction. + private sealed class FailingParticipant : IUserDataParticipant + { + private int _calls; + + public string Key => "probe"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => + Interlocked.Increment(ref _calls) == 1 + ? throw new InvalidOperationException("Synthetic transient export failure.") + : Task.CompletedTask; + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + /// Writes past any ceiling until refused. + private sealed class BulkParticipant : IUserDataParticipant + { + public string Key => "bulk"; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + var record = Encoding.UTF8.GetBytes("\"" + new string('b', 100_000) + "\""); + while (await writer.AppendAsync("items", record, cancellationToken) == UserDataExportAppend.Appended) + { + } + } + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + /// A small capped section that declares its truncation, as the audit section does at 8 MiB. + private sealed class CappedParticipant : IUserDataParticipant + { + internal const long Total = 500; + + public string Key => "capped"; + + public long? ExportSectionCapBytes => 4096; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + long included = 0; + for (var index = 0; index < Total; index++) + { + var record = Encoding.UTF8.GetBytes("{\"n\":" + index + ",\"pad\":\"" + new string('p', 40) + "\"}"); + if (await writer.AppendAsync("entries", record, cancellationToken) != UserDataExportAppend.Appended) + { + writer.DeclareTruncated("entries", included, Total); + return; + } + + included++; + } + } + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + private sealed class RoutingClaim : BackgroundJobRoutingClaim.MintingSource + { + internal static async Task ClaimAsync(string connectionString, BackgroundJobId job) + { + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand(""" + UPDATE background_jobs SET ownership_token=@token,ownership_kind='routing', + ownership_until=clock_timestamp()+interval '4 minutes' WHERE id=@job + RETURNING id,tenant_id,organization_id,definition_key,queue,wake_generation,ownership_token, + ownership_until,original_due_at,profile,phase,clock_timestamp() + """, dispatcher); + command.Parameters.AddWithValue("job", job.Value); + command.Parameters.AddWithValue("token", Guid.NewGuid()); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return MintClaim(row); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.cs new file mode 100644 index 00000000..915c5502 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.cs @@ -0,0 +1,136 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Audit.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 3 and ADR-0108 § 4 against the database: the audit participant's subject predicate and who-asked +/// reach, as learnstack_app in an organization group of the seeded schema. Every case rolls back. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataExportParticipantTests(SchemaFixture schema) +{ + private static readonly string[] SelfReach = ["own_tenant_wide", "own_branch", "admin_on_membership", "about_the_user"]; + private static readonly string[] AdministratorReach = ["own_branch", "admin_on_membership"]; + + [Theory] + [InlineData("self")] + [InlineData("administrator")] + public async Task The_audit_section_selects_the_subjects_rows_and_its_reach_follows_who_asked(string origin) + { + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, SchemaFixture.OrgA1); + var foreignMembership = Guid.CreateVersion7(); + var rows = new (string Name, Guid? Organization, Guid Actor, string EntityType, string Entity)[] + { + ("own_tenant_wide", null, PersonA, "Invitation", Guid.CreateVersion7().ToString("D")), + ("own_branch", SchemaFixture.OrgA1, PersonA, "Invitation", Guid.CreateVersion7().ToString("D")), + ("admin_on_membership", SchemaFixture.OrgA1, AdminA, "Membership", BranchMembershipA1.ToString("D")), + ("admin_on_other_membership", SchemaFixture.OrgA1, AdminA, "Membership", foreignMembership.ToString("D")), + ("about_the_user", null, UserId.SystemActor.Value, "User", PersonA.ToString("D")), + ("other_person", SchemaFixture.OrgA1, PersonB, "Invitation", Guid.CreateVersion7().ToString("D")), + }; + foreach (var row in rows) + { + await ScopeAsync(scope.Connection, scope.Transaction, SchemaFixture.TenantA, row.Organization); + await ExecuteAsync(scope.Connection, scope.Transaction, """ + INSERT INTO public.audit_log(id,timestamp,tenant_id,organization_id,actor_user_id,module,operation,operation_type, + operation_class,entity_type,entity_id,outcome,reason,before_state,after_state,changes,ip_address,user_agent) + VALUES(@id,clock_timestamp(),@tenant,@organization,@actor,'identity',@operation,'SecurityEvent','Must',@type,@entity, + 'success',NULL,@before::jsonb,NULL,NULL,'198.51.100.4'::inet,'Synthetic/2.0') + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("organization", (object?)row.Organization ?? DBNull.Value), + ("actor", row.Actor), ("operation", "fixture." + row.Name), ("type", row.EntityType), ("entity", row.Entity), + ("before", $$"""{"UserId":"{{PersonA}}","UpdatedBy":"{{AdminA}}"}""")); + } + + await ScopeAsync(scope.Connection, scope.Transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + var participant = new AuditUserDataParticipant(scope.Unit, scope.Context); + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, + origin == "self" ? DataRequestOrigin.Self : DataRequestOrigin.Administrator, UserId.From(PersonA), + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)), [BranchMembershipA1]); + var writer = new CollectingWriter(); + + await participant.ExportAsync(subject, writer, CancellationToken.None); + + var exported = writer.Records.Select(record => JsonDocument.Parse(record).RootElement) + .Where(record => record.GetProperty("operation").GetString()!.StartsWith("fixture.", StringComparison.Ordinal)) + .ToDictionary(record => record.GetProperty("operation").GetString()!["fixture.".Length..]); + exported.Keys.Should().BeEquivalentTo(origin == "self" ? SelfReach : AdministratorReach, + "a self request reaches every visible row of the tenant, an administrator's only the group's organization"); + exported["own_branch"].GetProperty("actor").GetString().Should().Be("self"); + exported["own_branch"].GetProperty("ip_address").GetString().Should().Be("198.51.100.4"); + exported["own_branch"].TryGetProperty("payload", out _).Should().BeFalse("an invitation row is not the subject's own entity"); + var administered = exported["admin_on_membership"]; + administered.GetProperty("actor").GetString().Should().Be("third_party"); + administered.TryGetProperty("ip_address", out _).Should().BeFalse("the administrator's address is another person's data"); + administered.GetProperty("payload").GetProperty("before").GetProperty("UserId").GetString().Should().Be("self"); + administered.GetProperty("payload").GetProperty("before").GetProperty("UpdatedBy").GetString().Should().Be("third_party"); + writer.Records.Should().OnlyContain(record => !record.Contains(PersonB.ToString("D"), StringComparison.OrdinalIgnoreCase) + && !record.Contains(AdminA.ToString("D"), StringComparison.OrdinalIgnoreCase)); + + var retained = (await participant.DescribeRetainedAsync(subject, CancellationToken.None)).ToDictionary(item => item.Kind, item => item.Count); + retained[RetainedReferenceKind.AuditActorReference].Should().BeGreaterThanOrEqualTo(origin == "self" ? 2 : 1); + retained[RetainedReferenceKind.AuditEntityReference].Should().BeGreaterThanOrEqualTo(origin == "self" ? 2 : 1); + retained.Should().ContainKey(RetainedReferenceKind.AuditMetadataReference); + await scope.Frame.FailAsync(); + } + + [Fact] + public async Task A_capped_audit_section_declares_the_records_included_and_the_total() + { + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, null); + for (var index = 0; index < 5; index++) + { + await ExecuteAsync(scope.Connection, scope.Transaction, """ + INSERT INTO public.audit_log(id,timestamp,tenant_id,organization_id,actor_user_id,module,operation,operation_type, + operation_class,entity_type,entity_id,outcome) + VALUES(@id,clock_timestamp(),@tenant,NULL,@actor,'identity','fixture.capped','SecurityEvent','Must','Invitation',NULL,'success') + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("actor", PersonA)); + } + + var participant = new AuditUserDataParticipant(scope.Unit, scope.Context); + participant.ExportSectionCapBytes.Should().Be(DataRequestLimits.AuditSectionBytes); + var writer = new CollectingWriter(admit: 2); + + await participant.ExportAsync(new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + UserId.From(PersonA), new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null), [LearnerMembershipA]), + writer, CancellationToken.None); + + writer.Records.Should().HaveCount(2); + writer.Truncated.Should().ContainSingle(); + writer.Truncated[0].Collection.Should().Be("entries"); + writer.Truncated[0].Included.Should().Be(2); + writer.Truncated[0].Total.Should().BeGreaterThanOrEqualTo(5); + await scope.Frame.FailAsync(); + } + + /// Collects records, and reports the section cap after admit of them. + private sealed class CollectingWriter(int admit = int.MaxValue) : IUserDataExportWriter + { + public List Records { get; } = []; + + public List<(string Collection, long Included, long Total)> Truncated { get; } = []; + + public long RemainingBytes => long.MaxValue; + + public ValueTask AppendAsync(string collection, ReadOnlyMemory utf8JsonRecord, + CancellationToken cancellationToken) + { + if (Records.Count >= admit) + { + return ValueTask.FromResult(UserDataExportAppend.SectionCapReached); + } + + Records.Add(System.Text.Encoding.UTF8.GetString(utf8JsonRecord.Span)); + return ValueTask.FromResult(UserDataExportAppend.Appended); + } + + public void DeclareTruncated(string collection, long includedRecords, long totalRecords) => + Truncated.Add((collection, includedRecords, totalRecords)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportTestKit.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportTestKit.cs new file mode 100644 index 00000000..f51ac80d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportTestKit.cs @@ -0,0 +1,76 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The pieces an ADR-0107 export proof needs outside a request pipeline: an announced application-role unit of +/// work over one group, the Identity context on it, and the fixture's export key ring. +/// +internal static class DataExportTestKit +{ + internal static string KeyRing => InvitationEmailFixtureConfiguration.Values[DataExportCipher.KeyRingSecret]!; + + internal static DataExportCipher Cipher() => new(new FixedSecrets(KeyRing)); + + /// An application-role transaction announced for one group, with the group's Identity context. + internal static async Task OpenAsync(string appConnectionString, Guid tenant, Guid? organization, + IEnumerable? userFences = null) + { + var source = ApplicationDataSource.Build(appConnectionString); + var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + var frame = await unit.BeginTransactionAsync(); + var context = new SeedTenantContext(TenantId.From(tenant), organization is { } org ? OrganizationId.From(org) : null); + await unit.SetTenantContextAsync(context); + await new IdentityMutationLocks(unit).AcquireAsync(new((userFences ?? []).Select(UserId.From), context.TenantId, + IdentityTenantLockMode.Shared)); + var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(unit.Connection).Options, + new StaticTenantContextAccessor(context), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(unit.Transaction); + return new GroupScope(source, unit, frame, context, db); + } + + internal sealed class GroupScope(NpgsqlDataSource source, NpgsqlUnitOfWork unit, IUnitOfWorkScope frame, ITenantContext context, + IdentityDbContext db) : IAsyncDisposable + { + public NpgsqlUnitOfWork Unit => unit; + public IUnitOfWorkScope Frame => frame; + public ITenantContext Context => context; + public IdentityDbContext Db => db; + public NpgsqlConnection Connection => (NpgsqlConnection)unit.Connection; + public NpgsqlTransaction Transaction => (NpgsqlTransaction)unit.Transaction!; + + public async ValueTask DisposeAsync() + { + await db.DisposeAsync(); + await frame.DisposeAsync(); + await unit.DisposeAsync(); + await source.DisposeAsync(); + } + } + + /// The audit capture is the pipeline's; outside it a designation binds nothing. + internal sealed class NoAuditSubject : IAuditSubject + { + public void Designate(IAggregateRoot aggregate) where TId : struct, IStronglyTypedId + { + } + } + + private sealed class FixedSecrets(string ring) : ISecretProvider + { + public string? GetSecret(string key) => key == DataExportCipher.KeyRingSecret ? ring : null; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs index a023cb06..ca810856 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs @@ -411,6 +411,30 @@ public async Task The_artifact_guard_holds_its_request_lifecycle_and_one_availab (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, "UPDATE public.data_export_artifacts SET byte_count=byte_count WHERE id=@id", ("id", first)))).SqlState.Should().Be("42501", "the size is not an application-writable column"); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "UPDATE public.data_export_artifacts SET truncation='{}'::jsonb WHERE id=@id", ("id", first)))).SqlState.Should().Be("42501", + "the truncation statement is set at insert and never written again (ADR-0107 § 3)"); + foreach (var malformed in new[] + { + "[]", "{\"audit\":{\"included\":1,\"total\":2}}", "{\"audit.entries\":{\"included\":3,\"total\":2}}", + "{\"audit.entries\":{\"included\":1,\"total\":2,\"value\":\"x\"}}", "{\"audit.entries\":{\"included\":1.5,\"total\":2}}", + "{\"audit.entries\":{\"included\":-1,\"total\":2}}", "{\"audit.entries\":{\"total\":2}}", "{\"Audit.entries\":{\"included\":1,\"total\":2}}", + }) + // The guard admits the copy (its request completes in this transaction); the CHECK runs before the indexes. + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, """ + INSERT INTO public.data_export_artifacts(id,tenant_id,organization_id,request_id,subject_user_id,status,byte_count, + chunk_count,key_version,truncation,expires_at,created_at,created_by) + SELECT @id,tenant_id,organization_id,request_id,subject_user_id,'available',byte_count,chunk_count,key_version, + @truncation::jsonb,expires_at,created_at,created_by FROM public.data_export_artifacts WHERE id=@first + """, ("id", Guid.CreateVersion7()), ("first", first), ("truncation", malformed)))).ConstraintName + .Should().Be("ck_data_export_artifacts_truncation", "the truncation statement has one closed shape: " + malformed); + (await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, """ + INSERT INTO public.data_export_artifacts(id,tenant_id,organization_id,request_id,subject_user_id,status,byte_count, + chunk_count,key_version,truncation,expires_at,created_at,created_by) + SELECT @id,tenant_id,organization_id,request_id,subject_user_id,'available',byte_count,chunk_count,key_version, + '{"audit.entries":{"included":1,"total":2}}'::jsonb,expires_at,created_at,created_by FROM public.data_export_artifacts WHERE id=@first + """, ("id", Guid.CreateVersion7()), ("first", first)))).ConstraintName.Should().NotBe("ck_data_export_artifacts_truncation", + "a well-formed statement passes the CHECK and meets the one-artifact indexes instead"); await RevokeAsync(app, transaction, first); await ExecuteAsync(app, transaction, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", first)); diff --git a/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/DataExportBundleBuilderTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/DataExportBundleBuilderTests.cs new file mode 100644 index 00000000..240184c6 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/DataExportBundleBuilderTests.cs @@ -0,0 +1,299 @@ +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.DataProtection; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.Application.DataProtection; + +/// ADR-0107 § 3–§ 4: one JSON document, bounded sections, the ceiling, truncation and chunking. +public sealed class DataExportBundleBuilderTests +{ + private static readonly DateTimeOffset GeneratedAt = new(2026, 11, 22, 10, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task The_bundle_is_one_document_with_its_envelope_and_a_section_per_participant_in_registry_order() + { + var subject = Subject(organization: true); + var builder = Builder(DataExportOptions.Default, + new Participant("zeta", writer => Append(writer, "items", "{\"value\":2}")), + new Participant("alpha", async writer => + { + await Append(writer, "first", "{\"value\":1}"); + await Append(writer, "first", "[1,2]"); + await Append(writer, "second", "\"text\""); + }), + new Participant("empty", _ => Task.CompletedTask)); + + var result = await builder.BuildAsync(subject, GeneratedAt, CancellationToken.None); + + using var bundle = result.Bundle!; + using var document = await Read(bundle); + var root = document.RootElement; + root.EnumerateObject().Select(property => property.Name).Should() + .Equal("schema_version", "request", "generated_at", "sections", "truncated"); + root.GetProperty("schema_version").GetInt32().Should().Be(DataExportBundleBuilder.SchemaVersion); + root.GetProperty("request").GetProperty("id").GetString().Should().Be(subject.RequestId.ToString("D")); + root.GetProperty("request").GetProperty("kind").GetString().Should().Be("export"); + root.GetProperty("request").GetProperty("origin").GetString().Should().Be("self"); + root.GetProperty("request").GetProperty("scope").GetString().Should().Be("organization"); + root.GetProperty("generated_at").GetString().Should().Be("2026-11-22T10:00:00.0000000Z"); + var sections = root.GetProperty("sections"); + sections.EnumerateObject().Select(section => section.Name).Should().Equal("alpha", "empty", "zeta"); + sections.GetProperty("alpha").GetProperty("first").GetArrayLength().Should().Be(2); + sections.GetProperty("alpha").GetProperty("second")[0].GetString().Should().Be("text"); + sections.GetProperty("empty").EnumerateObject().Should().BeEmpty(); + sections.GetProperty("zeta").GetProperty("items")[0].GetProperty("value").GetInt32().Should().Be(2); + root.GetProperty("truncated").EnumerateObject().Should().BeEmpty(); + bundle.Truncations.Should().BeEmpty(); + bundle.ChunkCount.Should().Be(1); + } + + [Fact] + public async Task A_section_cap_refuses_the_record_that_would_pass_it_and_the_declared_truncation_is_stated() + { + var outcomes = new List(); + var record = "{\"padding\":\"" + new string('x', 900) + "\"}"; + var builder = Builder(DataExportOptions.Default, new Participant("audit", async writer => + { + for (var index = 0; index < 50; index++) + { + var outcome = await Append(writer, "entries", record); + outcomes.Add(outcome); + if (outcome == UserDataExportAppend.SectionCapReached) + { + writer.DeclareTruncated("entries", index, 50); + return; + } + } + }, cap: 10_000)); + + var result = await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + using var bundle = result.Bundle!; + outcomes.Should().EndWith(UserDataExportAppend.SectionCapReached); + var included = outcomes.Count(outcome => outcome == UserDataExportAppend.Appended); + included.Should().BeInRange(9, 10); + using var document = await Read(bundle); + document.RootElement.GetProperty("sections").GetProperty("audit").GetProperty("entries").GetArrayLength().Should().Be(included); + var truncated = document.RootElement.GetProperty("truncated").GetProperty("audit.entries"); + truncated.GetProperty("included").GetInt64().Should().Be(included); + truncated.GetProperty("total").GetInt64().Should().Be(50); + bundle.Truncations.Should().ContainSingle().Which.Should().Be(new DataExportTruncation("audit.entries", included, 50)); + } + + [Fact] + public async Task The_bundle_ceiling_fails_the_whole_bundle_and_refuses_every_later_record() + { + var outcomes = new List(); + var record = "\"" + new string('y', 100_000) + "\""; + var builder = Builder(new DataExportOptions(DataRequestLimits.MinimumBundleBytes), + new Participant("first", async writer => + { + for (var index = 0; index < 20; index++) + { + outcomes.Add(await Append(writer, "items", record)); + } + }), + new Participant("second", _ => throw new InvalidOperationException("A refused bundle runs no later participant."))); + + var result = await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + result.IsTooLarge.Should().BeTrue(); + result.Bundle.Should().BeNull(); + outcomes.Should().Contain(UserDataExportAppend.BundleCeilingReached); + outcomes.SkipWhile(outcome => outcome == UserDataExportAppend.Appended) + .Should().OnlyContain(outcome => outcome == UserDataExportAppend.BundleCeilingReached); + } + + [Fact] + public async Task A_finished_bundle_never_passes_the_ceiling_however_close_the_records_come() + { + var options = new DataExportOptions(DataRequestLimits.MinimumBundleBytes); + var builder = Builder(options, new Participant("fill", async writer => + { + while (await Append(writer, "items", "\"" + new string('z', 997) + "\"") == UserDataExportAppend.Appended) + { + } + }, cap: 900_000), new Participant("tail", async writer => + { + while (await Append(writer, "items", "1") == UserDataExportAppend.Appended) + { + } + })); + + var result = await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + result.IsTooLarge.Should().BeTrue("the tail fills the bundle to its ceiling"); + var bounded = Builder(options, new Participant("fill", async writer => + { + while (await Append(writer, "items", "\"" + new string('z', 997) + "\"") == UserDataExportAppend.Appended) + { + } + }, cap: 900_000)); + using var bundle = (await bounded.BuildAsync(Subject(), GeneratedAt, CancellationToken.None)).Bundle!; + bundle.ByteCount.Should().BeLessThanOrEqualTo(options.MaxBytes); + using var _ = await Read(bundle); + } + + [Theory] + [InlineData("")] + [InlineData("{")] + [InlineData("{} {}")] + [InlineData("1 2")] + [InlineData("/* comment */ 1")] + [InlineData("{\"a\":1,}")] + public async Task A_record_that_is_not_exactly_one_JSON_value_is_refused_before_any_byte_is_written(string record) + { + var builder = Builder(DataExportOptions.Default, new Participant("bad", writer => Append(writer, "items", record))); + + var act = () => builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + await act.Should().ThrowAsync(); + } + + [Theory] + [InlineData("return")] + [InlineData("name")] + [InlineData("late")] + [InlineData("twice")] + public async Task The_section_writer_is_append_only_and_bounded_to_its_participant(string misuse) + { + IUserDataExportWriter? kept = null; + var builder = Builder(DataExportOptions.Default, new Participant("misuse", async writer => + { + kept = writer; + switch (misuse) + { + case "return": + await Append(writer, "a", "1"); + await Append(writer, "b", "2"); + await Append(writer, "a", "3"); + break; + case "name": + await Append(writer, "Bad-Name", "1"); + break; + case "twice": + writer.DeclareTruncated("a", 1, 2); + writer.DeclareTruncated("a", 1, 2); + break; + } + })); + + var act = () => builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + if (misuse == "late") + { + using var bundle = (await act()).Bundle!; + await FluentActions.Invoking(() => kept!.AppendAsync("a", Encoding.UTF8.GetBytes("1"), CancellationToken.None).AsTask()) + .Should().ThrowAsync(); + FluentActions.Invoking(() => kept!.DeclareTruncated("a", 0, 1)).Should().Throw(); + kept!.RemainingBytes.Should().Be(0); + } + else if (misuse == "name") + { + await act.Should().ThrowAsync(); + } + else + { + await act.Should().ThrowAsync(); + } + } + + [Fact] + public async Task A_large_bundle_is_chunked_into_full_chunks_and_one_remainder_that_concatenate_to_the_document() + { + var record = "\"" + new string('c', 50_000) + "\""; + var builder = Builder(DataExportOptions.Default, new Participant("big", async writer => + { + for (var index = 0; index < 10; index++) + { + (await Append(writer, "items", record)).Should().Be(UserDataExportAppend.Appended); + } + })); + + using var bundle = (await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None)).Bundle!; + + var chunks = new List(); + await foreach (var chunk in bundle.ReadChunksAsync()) + { + chunks.Add(chunk.ToArray()); + } + + bundle.ChunkCount.Should().Be(DataRequestLimits.ChunkCountFor(bundle.ByteCount)).And.Be(chunks.Count).And.BeGreaterThan(1); + chunks.SkipLast(1).Should().OnlyContain(chunk => chunk.Length == DataRequestLimits.ChunkPlaintextBytes); + chunks[^1].Length.Should().BeInRange(1, DataRequestLimits.ChunkPlaintextBytes); + chunks.Sum(chunk => (long)chunk.Length).Should().Be(bundle.ByteCount); + using var document = JsonDocument.Parse(chunks.SelectMany(chunk => chunk).ToArray()); + document.RootElement.GetProperty("sections").GetProperty("big").GetProperty("items").GetArrayLength().Should().Be(10); + } + + [Fact] + public async Task Only_an_export_with_a_utc_generation_time_builds_a_bundle() + { + var builder = Builder(DataExportOptions.Default); + var erasure = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Erasure, DataRequestOrigin.Self, + UserId.From(Guid.CreateVersion7()), new DataRequestScopeGroup(TenantId.From(Guid.CreateVersion7()), null), + [Guid.CreateVersion7()]); + + await FluentActions.Invoking(() => builder.BuildAsync(erasure, GeneratedAt, CancellationToken.None)) + .Should().ThrowAsync(); + await FluentActions.Invoking(() => builder.BuildAsync(Subject(), new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.FromHours(3)), + CancellationToken.None)).Should().ThrowAsync(); + } + + [Theory] + [InlineData(null, DataRequestLimits.DefaultMaximumBundleBytes)] + [InlineData("1048576", 1_048_576L)] + [InlineData("67108864", DataRequestLimits.MaximumBundleBytes)] + public void The_ceiling_setting_defaults_to_sixteen_mebibytes_and_admits_its_range(string? setting, long expected) => + DataExportOptions.FromSetting(setting).MaxBytes.Should().Be(expected); + + [Theory] + [InlineData("")] + [InlineData("abc")] + [InlineData("1048575")] + [InlineData("67108865")] + [InlineData("-1")] + [InlineData(" 1048576")] + [InlineData("1e7")] + public void An_invalid_ceiling_setting_fails_fast(string setting) => + FluentActions.Invoking(() => DataExportOptions.FromSetting(setting)).Should().Throw(); + + private static DataExportBundleBuilder Builder(DataExportOptions options, params IUserDataParticipant[] participants) => + new(new UserDataParticipantRegistry(participants), options); + + private static UserDataSubject Subject(bool organization = false) => new(Guid.CreateVersion7(), DataRequestKind.Export, + DataRequestOrigin.Self, UserId.From(Guid.CreateVersion7()), + new DataRequestScopeGroup(TenantId.From(Guid.CreateVersion7()), organization ? OrganizationId.From(Guid.CreateVersion7()) : null), + [Guid.CreateVersion7()]); + + private static Task Append(IUserDataExportWriter writer, string collection, string record) => + writer.AppendAsync(collection, Encoding.UTF8.GetBytes(record), CancellationToken.None).AsTask(); + + private static async Task Read(IDataExportBundle bundle) + { + var bytes = new List(); + await foreach (var chunk in bundle.ReadChunksAsync()) + { + bytes.AddRange(chunk.ToArray()); + } + + bytes.Should().HaveCount((int)bundle.ByteCount); + return JsonDocument.Parse(bytes.ToArray()); + } + + private sealed class Participant(string key, Func export, long? cap = null) : IUserDataParticipant + { + public string Key => key; + + public long? ExportSectionCapBytes => cap; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => export(writer); + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Audit/AuditUserDataParticipantTests.cs b/backend/tests/LearnStack.Tests.Unit/Audit/AuditUserDataParticipantTests.cs new file mode 100644 index 00000000..9364ebba --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Audit/AuditUserDataParticipantTests.cs @@ -0,0 +1,142 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Modules.Audit.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.Audit; + +/// +/// ADR-0107 § 3, ADR-0106 § 5: what an exported audit record discloses — the envelope, the actor as a closed word, +/// the subject's own address and agent only, the payload only of the subject's own Membership or consent — and that +/// every identifier is rewritten to self or third_party. +/// +public sealed partial class AuditUserDataParticipantTests +{ + private static readonly Guid Subject = Guid.Parse("01970000-0000-7000-8000-00000000000a"); + private static readonly Guid OwnMembership = Guid.Parse("01970000-0000-7000-8000-00000000000b"); + private static readonly Guid OtherPerson = Guid.Parse("01970000-0000-7000-8000-00000000000c"); + private static readonly Guid OtherMembership = Guid.Parse("01970000-0000-7000-8000-00000000000d"); + + [Theory] + [InlineData("subject", "self")] + [InlineData("system", "system")] + [InlineData("other", "third_party")] + [InlineData("none", null)] + public void The_actor_is_a_closed_word_never_an_identifier(string actor, string? expected) => + AuditUserDataParticipant.ActorOf(Row(actor: Actor(actor)), Request()).Should().Be(expected); + + [Theory] + [InlineData("Membership", "own", "other", true)] + [InlineData("Membership", "other_membership", "subject", false)] + [InlineData("MembershipFieldConsent", "any", "subject", true)] + [InlineData("MembershipFieldConsent", "any", "other", false)] + [InlineData("Invitation", "any", "subject", false)] + [InlineData("Role", "any", "subject", false)] + [InlineData("User", "subject", "system", false)] + public void The_payload_is_disclosed_only_for_the_subjects_own_membership_or_recorded_consent(string entityType, string entity, + string actor, bool disclosed) + { + var entityId = entity switch + { + "own" => OwnMembership.ToString("D"), + "other_membership" => OtherMembership.ToString("D"), + "subject" => Subject.ToString("D"), + _ => Guid.CreateVersion7().ToString("D"), + }; + + AuditUserDataParticipant.DisclosesPayload(Row(entityType: entityType, entityId: entityId, actor: Actor(actor)), Request()) + .Should().Be(disclosed); + } + + [Fact] + public void An_administrators_change_to_the_subjects_membership_shows_the_payload_but_never_the_administrators_address() + { + var row = Row(entityType: "Membership", entityId: OwnMembership.ToString("D"), actor: OtherPerson, + before: $$"""{"Id":"{{OwnMembership}}","UserId":"{{Subject}}","Status":"Active","UpdatedBy":"{{OtherPerson}}"}""", + after: $$"""{"Id":"{{OwnMembership}}","UserId":"{{Subject}}","Status":"Suspended","UpdatedBy":"{{OtherPerson}}","RoleIds":["{{OtherMembership}}"]}""", + changes: $$"""[{"path":"/Membership/{{OwnMembership}}/Status","before":"Active","after":"Suspended"}]"""); + + var json = Write(row); + + var record = JsonDocument.Parse(json).RootElement; + record.GetProperty("actor").GetString().Should().Be("third_party"); + record.TryGetProperty("ip_address", out _).Should().BeFalse(); + record.TryGetProperty("user_agent", out _).Should().BeFalse(); + var payload = record.GetProperty("payload"); + payload.GetProperty("before").GetProperty("UserId").GetString().Should().Be("self"); + payload.GetProperty("before").GetProperty("Id").GetString().Should().Be("self"); + payload.GetProperty("after").GetProperty("UpdatedBy").GetString().Should().Be("third_party"); + payload.GetProperty("after").GetProperty("RoleIds")[0].GetString().Should().Be("third_party"); + payload.GetProperty("changes")[0].GetProperty("path").GetString().Should().Be("/Membership/self/Status"); + AnyIdentifier().IsMatch(json).Should().BeFalse("no identifier, the subject's own included, leaves in an export"); + } + + [Fact] + public void A_row_the_subject_acted_in_carries_their_own_address_and_agent_and_no_payload_for_a_foreign_entity() + { + var row = Row(entityType: "Invitation", entityId: Guid.CreateVersion7().ToString("D"), actor: Subject, + ip: "203.0.113.7", agent: "Synthetic/1.0", before: $$"""{"RecipientEmail":"***REDACTED***","InviterUserId":"{{Subject}}"}"""); + + var record = JsonDocument.Parse(Write(row)).RootElement; + + record.EnumerateObject().Select(property => property.Name).Should() + .Equal("at", "module", "operation", "outcome", "entity_type", "actor", "ip_address", "user_agent"); + record.GetProperty("actor").GetString().Should().Be("self"); + record.GetProperty("ip_address").GetString().Should().Be("203.0.113.7"); + record.GetProperty("user_agent").GetString().Should().Be("Synthetic/1.0"); + record.GetProperty("module").GetString().Should().Be("identity"); + record.GetProperty("operation").GetString().Should().Be("identity.invitation.create"); + record.GetProperty("outcome").GetString().Should().Be("success"); + } + + [Fact] + public void Identifiers_in_property_names_and_any_case_are_rewritten_and_the_redaction_sentinel_is_kept() + { + var own = AuditUserDataParticipant.Own(Request()); + var upper = OtherPerson.ToString("D").ToUpperInvariant(); + + AuditPayloadProjection.Rewrite($"x-{Subject}-{upper}", own).Should().Be("x-self-third_party"); + AuditPayloadProjection.Rewrite("***REDACTED***", own).Should().Be("***REDACTED***"); + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream)) + { + AuditPayloadProjection.Write(json, "{\"" + OtherMembership + "\":{\"n\":1,\"b\":true,\"z\":null}}", own); + } + + JsonDocument.Parse(stream.ToArray()).RootElement.GetProperty("third_party").GetProperty("n").GetInt32().Should().Be(1); + } + + private static string Write(AuditUserDataParticipant.AuditRow row) + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream)) + { + AuditUserDataParticipant.WriteRecord(json, row, Request(), AuditUserDataParticipant.Own(Request())); + } + + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + + private static UserDataSubject Request() => new(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + UserId.From(Subject), new DataRequestScopeGroup(TenantId.From(Guid.CreateVersion7()), null), [OwnMembership]); + + private static Guid? Actor(string actor) => actor switch + { + "subject" => Subject, + "system" => UserId.SystemActor.Value, + "other" => OtherPerson, + _ => null, + }; + + private static AuditUserDataParticipant.AuditRow Row(string entityType = "Membership", string? entityId = null, Guid? actor = null, + string? ip = null, string? agent = null, string? before = null, string? after = null, string? changes = null) => + new(Guid.CreateVersion7(), new DateTime(2026, 11, 22, 9, 0, 0, DateTimeKind.Utc), "identity", + entityType == "Invitation" ? "identity.invitation.create" : "identity.membership.change_status", "success", + entityType, entityId, actor, ip, agent, before, after, changes); + + [GeneratedRegex("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}")] + private static partial Regex AnyIdentifier(); +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTruncationTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTruncationTests.cs new file mode 100644 index 00000000..466ad413 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTruncationTests.cs @@ -0,0 +1,69 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// ADR-0107 § 3: the receipt's closed truncation statement; ADR-0106 § 8: a dead job reads as failed. +public sealed class DataExportTruncationTests +{ + [Fact] + public void A_truncation_statement_round_trips_in_one_canonical_form() + { + var statement = new[] { new DataExportTruncation("tenancy.field_consents", 1, 4), new DataExportTruncation("audit.entries", 10, 25) }; + + var json = DataRequestDocuments.WriteTruncation(statement); + + json.Should().Be("""{"audit.entries":{"included":10,"total":25},"tenancy.field_consents":{"included":1,"total":4}}"""); + DataRequestDocuments.ReadTruncation(json!).Should().Equal(statement.OrderBy(item => item.Collection, StringComparer.Ordinal)); + DataRequestDocuments.WriteTruncation([]).Should().Be("{}"); + DataRequestDocuments.ReadTruncation("{}").Should().BeEmpty(); + } + + [Theory] + [InlineData("audit", 0, 1)] + [InlineData("Audit.entries", 0, 1)] + [InlineData("audit.entries.more", 0, 1)] + [InlineData(".entries", 0, 1)] + [InlineData("audit.", 0, 1)] + [InlineData("audit.entries", 2, 1)] + [InlineData("audit.entries", -1, 1)] + public void A_truncation_names_one_section_collection_with_included_at_most_total(string collection, long included, long total) => + FluentActions.Invoking(() => new DataExportTruncation(collection, included, total)).Should().Throw(); + + [Fact] + public void A_statement_is_bounded_and_names_each_collection_once() + { + var repeated = new[] { new DataExportTruncation("audit.entries", 1, 2), new DataExportTruncation("audit.entries", 1, 3) }; + var oversized = Enumerable.Range(0, DataRequestLimits.MaximumTruncatedCollections + 1) + .Select(index => new DataExportTruncation("audit.c" + index, 0, 1)).ToArray(); + + DataRequestDocuments.WriteTruncation(repeated).Should().BeNull(); + DataRequestDocuments.WriteTruncation(oversized).Should().BeNull(); + } + + [Theory] + [InlineData("[]")] + [InlineData("{\"audit.entries\":1}")] + [InlineData("{\"audit.entries\":{\"included\":1}}")] + [InlineData("{\"audit.entries\":{\"included\":1,\"total\":2,\"extra\":3}}")] + [InlineData("{\"audit.entries\":{\"included\":3,\"total\":2}}")] + [InlineData("{\"bad\":{\"included\":1,\"total\":2}}")] + public void A_stored_statement_outside_the_closed_shape_is_corrupt_storage(string json) => + FluentActions.Invoking(() => DataRequestDocuments.ReadTruncation(json)).Should().Throw(); + + [Theory] + [InlineData("pending", false, "Pending")] + [InlineData("executing", false, "Pending")] + [InlineData("reconciling", false, "Pending")] + [InlineData("completed", false, "Completed")] + [InlineData("completed", true, "Dead")] + [InlineData("terminal_pending", false, "Dead")] + [InlineData("quarantined", false, "Dead")] + [InlineData("executing", true, "Dead")] + public void A_quarantined_dead_lettered_or_terminally_failed_job_is_dead(string phase, bool failed, string expected) => + DataRequestJobPhaseReader.Classify(phase, failed).Should().Be(Enum.Parse(expected)); +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs new file mode 100644 index 00000000..ff958639 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs @@ -0,0 +1,111 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Tenancy; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// ADR-0107 § 2: the fulfilment job of a request's kind and group, and the purge at the artifact's expiry. +public sealed class DataRequestFulfillmentSchedulerTests +{ + private static readonly DateTimeOffset At = new(2026, 11, 22, 9, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly OrganizationId Organization = OrganizationId.From(Guid.CreateVersion7()); + + [Theory] + [InlineData("tenant", "identity.data_export_tenant.v1")] + [InlineData("organization", "identity.data_export_organization.v1")] + public async Task A_requested_export_submits_the_export_definition_of_its_group(string scope, string key) + { + var organization = scope == "tenant" ? (OrganizationId?)null : Organization; + var jobs = new RecordingScheduler(); + var request = Request(DataRequestKind.Export, organization); + + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(request, CancellationToken.None); + + jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataExportJobParameters(request.Id.Value), (DateTimeOffset?)null)); + } + + [Theory] + [InlineData("erasure")] + [InlineData("closure")] + [InlineData("other_group")] + [InlineData("fulfilling")] + public async Task Anything_but_a_requested_export_of_the_announced_group_is_a_programming_error(string variant) + { + var jobs = new RecordingScheduler(); + var request = variant switch + { + "erasure" => Request(DataRequestKind.Erasure, null), + "closure" => Request(DataRequestKind.Closure, null), + _ => Request(DataRequestKind.Export, null), + }; + if (variant == "fulfilling") + { + request.StartFulfilling(At, UserId.SystemActor).IsSuccess.Should().BeTrue(); + } + + var context = new Context(variant == "other_group" ? Organization : null); + + await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, context).SubmitAsync(request, CancellationToken.None).AsTask()) + .Should().ThrowAsync(); + jobs.Submitted.Should().BeEmpty(); + } + + [Theory] + [InlineData("tenant", "identity.data_export_purge_tenant.v1")] + [InlineData("organization", "identity.data_export_purge_organization.v1")] + public async Task A_purge_is_scheduled_for_its_artifact_at_the_due_time(string scope, string key) + { + var organization = scope == "tenant" ? (OrganizationId?)null : Organization; + var jobs = new RecordingScheduler(); + var artifact = DataExportArtifactId.From(Guid.CreateVersion7()); + var due = At + DataRequestLimits.ArtifactLifetime; + + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SchedulePurgeAsync(artifact, due, CancellationToken.None); + + jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataExportPurgeParameters(artifact.Value), (DateTimeOffset?)due)); + await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, new Context(organization)) + .SchedulePurgeAsync(DataExportArtifactId.From(Guid.NewGuid()), due, CancellationToken.None).AsTask()) + .Should().ThrowAsync("an artifact identity is a UUIDv7"); + } + + private static DataSubjectRequest Request(DataRequestKind kind, OrganizationId? organization) => + DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), kind, UserId.From(Guid.CreateVersion7()), + new DataRequestScopeGroup(Tenant, organization), [MembershipId.From(Guid.CreateVersion7())], At).Value!; + + private sealed class Context(OrganizationId? organization) : ITenantContext + { + public bool IsResolved => true; + public TenantContextOrigin? Origin => TenantContextOrigin.Ambient; + public TenantId TenantId => Tenant; + public OrganizationId? OrganizationId => organization; + public UserId? UserId => null; + public string? CorrelationId => null; + public string? ModuleName => null; + } + + private sealed class RecordingScheduler : IBackgroundJobScheduler + { + public List<(string Key, object Parameters, DateTimeOffset? Due)> Submitted { get; } = []; + + public Task EnqueueAsync(BackgroundJobKey definition, TParameters parameters, + CancellationToken cancellationToken = default) where TParameters : IBackgroundJobParameters + { + Submitted.Add((definition.Value, parameters, null)); + return Task.FromResult(BackgroundJobId.From(Guid.CreateVersion7())); + } + + public Task ScheduleAsync(BackgroundJobKey definition, TParameters parameters, + DateTimeOffset dueAt, CancellationToken cancellationToken = default) where TParameters : IBackgroundJobParameters + { + Submitted.Add((definition.Value, parameters, dueAt)); + return Task.FromResult(BackgroundJobId.From(Guid.CreateVersion7())); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/DataExportCipherTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/DataExportCipherTests.cs new file mode 100644 index 00000000..7938c932 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/DataExportCipherTests.cs @@ -0,0 +1,245 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Secrets; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.DataProtection; + +/// ADR-0107 § 4: AES-256-GCM export custody, its key ring and its associated-data binding. +public sealed class DataExportCipherTests +{ + private static readonly Guid Tenant = Guid.Parse("01970000-0000-7000-8000-000000000001"); + private static readonly Guid Request = Guid.Parse("01970000-0000-7000-8000-000000000002"); + private static readonly Guid Artifact = Guid.Parse("01970000-0000-7000-8000-000000000003"); + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + public void A_bounded_key_ring_seals_under_its_active_key_and_opens_what_it_sealed(int count) + { + using var cipher = Cipher("k" + count, Enumerable.Range(1, count).ToDictionary(index => "k" + index, Key)); + var plaintext = Plaintext(1000); + + var sealedChunk = cipher.Seal(Binding(0, 3), plaintext); + + sealedChunk.KeyVersion.Should().Be("k" + count); + cipher.ActiveKeyVersion.Should().Be("k" + count); + sealedChunk.Nonce.Should().HaveCount(DataRequestLimits.NonceBytes); + sealedChunk.Tag.Should().HaveCount(DataRequestLimits.TagBytes); + sealedChunk.Ciphertext.Should().HaveCount(plaintext.Length).And.NotEqual(plaintext); + cipher.Open(Binding(0, 3), sealedChunk).Should().Equal(plaintext); + } + + [Theory] + [InlineData("absent")] + [InlineData("not_json")] + [InlineData("not_object")] + [InlineData("extra_property")] + [InlineData("no_active")] + [InlineData("active_unknown")] + [InlineData("active_not_string")] + [InlineData("no_keys")] + [InlineData("empty_keys")] + [InlineData("five_keys")] + [InlineData("short_key")] + [InlineData("long_key")] + [InlineData("not_base64")] + [InlineData("duplicate_material")] + [InlineData("bad_label")] + [InlineData("long_label")] + [InlineData("key_not_string")] + public void A_missing_or_malformed_key_ring_refuses_construction_without_detail(string ring) + { + var secret = ring switch + { + "absent" => null, + "not_json" => "{", + "not_object" => "[]", + "extra_property" => Ring("k1", new() { ["k1"] = Key(1) }, extra: true), + "no_active" => JsonSerializer.Serialize(new { keys = new Dictionary { ["k1"] = Convert.ToBase64String(Key(1)) } }), + "active_unknown" => Ring("k9", new() { ["k1"] = Key(1) }), + "active_not_string" => "{\"active\":1,\"keys\":{\"k1\":\"" + Convert.ToBase64String(Key(1)) + "\"}}", + "no_keys" => "{\"active\":\"k1\",\"other\":{}}", + "empty_keys" => "{\"active\":\"k1\",\"keys\":{}}", + "five_keys" => Ring("k1", Enumerable.Range(1, 5).ToDictionary(index => "k" + index, Key)), + "short_key" => Ring("k1", new() { ["k1"] = new byte[31] }), + "long_key" => Ring("k1", new() { ["k1"] = new byte[33] }), + "not_base64" => "{\"active\":\"k1\",\"keys\":{\"k1\":\"%%%\"}}", + "duplicate_material" => Ring("k1", new() { ["k1"] = Key(1), ["k2"] = Key(1) }), + "bad_label" => Ring("k 1", new() { ["k 1"] = Key(1) }), + "long_label" => Ring(new string('k', 33), new() { [new string('k', 33)] = Key(1) }), + "key_not_string" => "{\"active\":\"k1\",\"keys\":{\"k1\":5}}", + _ => throw new ArgumentOutOfRangeException(nameof(ring)), + }; + + var act = () => new DataExportCipher(new FixedSecrets(secret)); + + act.Should().Throw().WithMessage("Data export custody unavailable.") + .Which.InnerException.Should().BeNull(); + } + + [Theory] + [InlineData("tenant")] + [InlineData("request")] + [InlineData("artifact")] + [InlineData("index")] + [InlineData("count")] + public void Every_associated_data_member_binds_the_chunk(string member) + { + using var cipher = Cipher("k1", new() { ["k1"] = Key(1) }); + var sealedChunk = cipher.Seal(Binding(1, 4), Plaintext(64)); + var other = Guid.Parse("01970000-0000-7000-8000-0000000000ff"); + var moved = member switch + { + "tenant" => new DataExportChunkBinding(other, Request, Artifact, 1, 4), + "request" => new DataExportChunkBinding(Tenant, other, Artifact, 1, 4), + "artifact" => new DataExportChunkBinding(Tenant, Request, other, 1, 4), + "index" => new DataExportChunkBinding(Tenant, Request, Artifact, 2, 4), + "count" => new DataExportChunkBinding(Tenant, Request, Artifact, 1, 3), + _ => throw new ArgumentOutOfRangeException(nameof(member)), + }; + + FluentActions.Invoking(() => cipher.Open(moved, sealedChunk)).Should().Throw() + .WithMessage("Data export custody unavailable."); + cipher.Open(Binding(1, 4), sealedChunk).Should().Equal(Plaintext(64)); + } + + [Theory] + [InlineData("ciphertext")] + [InlineData("tag")] + [InlineData("nonce")] + [InlineData("short_tag")] + [InlineData("short_nonce")] + [InlineData("empty_ciphertext")] + [InlineData("unknown_version")] + [InlineData("relabelled_version")] + public void A_tampered_truncated_or_relabelled_chunk_fails_closed(string tamper) + { + using var cipher = Cipher("k2", new() { ["k1"] = Key(1), ["k2"] = Key(2) }); + var sealedChunk = cipher.Seal(Binding(0, 1), Plaintext(128)); + var forged = tamper switch + { + "ciphertext" => sealedChunk with { Ciphertext = Flip(sealedChunk.Ciphertext) }, + "tag" => sealedChunk with { Tag = Flip(sealedChunk.Tag) }, + "nonce" => sealedChunk with { Nonce = Flip(sealedChunk.Nonce) }, + "short_tag" => sealedChunk with { Tag = sealedChunk.Tag[..12] }, + "short_nonce" => sealedChunk with { Nonce = sealedChunk.Nonce[..8] }, + "empty_ciphertext" => sealedChunk with { Ciphertext = [] }, + "unknown_version" => sealedChunk with { KeyVersion = "k9" }, + "relabelled_version" => sealedChunk with { KeyVersion = "k1" }, + _ => throw new ArgumentOutOfRangeException(nameof(tamper)), + }; + + FluentActions.Invoking(() => cipher.Open(Binding(0, 1), forged)).Should().Throw() + .WithMessage("Data export custody unavailable."); + } + + [Fact] + public void Rotation_opens_older_chunks_while_the_old_key_stays_and_not_after_it_leaves() + { + byte[] plaintext = Plaintext(300); + DataExportSealedChunk old; + using (var before = Cipher("k1", new() { ["k1"] = Key(1) })) + { + old = before.Seal(Binding(0, 1), plaintext); + } + + using var rotated = Cipher("k2", new() { ["k1"] = Key(1), ["k2"] = Key(2) }); + rotated.Open(Binding(0, 1), old).Should().Equal(plaintext); + rotated.Seal(Binding(0, 1), plaintext).KeyVersion.Should().Be("k2"); + + using var retired = Cipher("k2", new() { ["k2"] = Key(2) }); + FluentActions.Invoking(() => retired.Open(Binding(0, 1), old)).Should().Throw(); + } + + [Fact] + public void Every_chunk_gets_a_fresh_nonce() + { + using var cipher = Cipher("k1", new() { ["k1"] = Key(1) }); + var nonces = Enumerable.Range(0, DataRequestLimits.MaximumChunkCount) + .Select(index => Convert.ToHexString(cipher.Seal(Binding(index, DataRequestLimits.MaximumChunkCount), Plaintext(16)).Nonce)) + .ToArray(); + + nonces.Should().OnlyHaveUniqueItems(); + } + + [Theory] + [InlineData(0, false)] + [InlineData(1, true)] + [InlineData(DataRequestLimits.ChunkPlaintextBytes, true)] + [InlineData(DataRequestLimits.ChunkPlaintextBytes + 1, false)] + public void A_chunk_holds_one_to_at_most_one_hundred_twenty_eight_kibibytes(int length, bool admitted) + { + using var cipher = Cipher("k1", new() { ["k1"] = Key(1) }); + + var seal = () => cipher.Seal(Binding(0, 1), new byte[length]); + + if (admitted) + { + cipher.Open(Binding(0, 1), seal()).Should().HaveCount(length); + } + else + { + seal.Should().Throw(); + } + } + + [Theory] + [InlineData(-1, 1)] + [InlineData(1, 1)] + [InlineData(0, 0)] + [InlineData(0, DataRequestLimits.MaximumChunkCount + 1)] + public void A_binding_names_a_position_inside_its_artifact(int index, int count) + { + FluentActions.Invoking(() => new DataExportChunkBinding(Tenant, Request, Artifact, index, count)) + .Should().Throw(); + FluentActions.Invoking(() => new DataExportChunkBinding(Guid.Empty, Request, Artifact, 0, 1)) + .Should().Throw(); + } + + [Fact] + public void Nothing_prints_key_material_or_content_and_a_disposed_cipher_refuses() + { + var cipher = Cipher("k1", new() { ["k1"] = Key(1) }); + var sealedChunk = cipher.Seal(Binding(0, 1), Plaintext(32)); + + cipher.ToString().Should().Be(nameof(DataExportCipher)); + sealedChunk.ToString().Should().Be(nameof(DataExportSealedChunk)); + Binding(0, 1).ToString().Should().Be(nameof(DataExportChunkBinding)); + cipher.Dispose(); + FluentActions.Invoking(() => cipher.Seal(Binding(0, 1), Plaintext(32))).Should().Throw(); + FluentActions.Invoking(() => cipher.Open(Binding(0, 1), sealedChunk)).Should().Throw(); + } + + private static DataExportChunkBinding Binding(int index, int count) => new(Tenant, Request, Artifact, index, count); + + private static DataExportCipher Cipher(string active, Dictionary keys) => new(new FixedSecrets(Ring(active, keys))); + + private static string Ring(string active, Dictionary keys, bool extra = false) + { + var encoded = keys.ToDictionary(pair => pair.Key, pair => Convert.ToBase64String(pair.Value)); + return extra + ? JsonSerializer.Serialize(new { active, keys = encoded, legacy = true }) + : JsonSerializer.Serialize(new { active, keys = encoded }); + } + + private static byte[] Key(int seed) => Enumerable.Repeat((byte)seed, DataRequestLimits.KeyBytes).ToArray(); + + private static byte[] Plaintext(int length) => Enumerable.Range(0, length).Select(index => (byte)(index % 251)).ToArray(); + + private static byte[] Flip(byte[] value) + { + var copy = value.ToArray(); + copy[0] ^= 0x01; + return copy; + } + + private sealed class FixedSecrets(string? ring) : ISecretProvider + { + public string? GetSecret(string key) => key == DataExportCipher.KeyRingSecret ? ring : null; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs b/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs index dffa9042..870fd60b 100644 --- a/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs @@ -3,6 +3,8 @@ using LearnStack.Infrastructure.Jobs; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; using LearnStack.Modules.Identity.Infrastructure.Invitations; using LearnStack.SharedKernel.Jobs; using Xunit; @@ -11,13 +13,20 @@ namespace LearnStack.Tests.Unit; public sealed class InvitationEmailRegistryTests { + private static readonly string[] InvitationKeys = ["identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1"]; + + private static readonly string[] DataExportKeys = + [ + "identity.data_export_tenant.v1", "identity.data_export_organization.v1", + "identity.data_export_purge_tenant.v1", "identity.data_export_purge_organization.v1", + ]; + [Fact] - public void Actual_Registry_Binds_Exactly_Two_Active_Definitions_And_Four_Scoped_Ordinary_Roots() + public void Actual_Registry_Binds_Exactly_Six_Active_Definitions_And_Eight_Scoped_Ordinary_Roots() { var registry = InvitationEmailRegistration.CreateRegistry(); - registry.DefinitionKeys.Should().BeEquivalentTo( - "identity.invitation_email_tenant.v1", "identity.invitation_email_organization.v1"); - var definitions = registry.DefinitionKeys.Select(key => registry.Resolve(key).Definition!).ToArray(); + registry.DefinitionKeys.Should().BeEquivalentTo(InvitationKeys.Concat(DataExportKeys)); + var definitions = InvitationKeys.Select(key => registry.Resolve(key).Definition!).ToArray(); definitions.Should().OnlyContain(definition => definition.Readiness == BackgroundJobDefinitionReadiness.Active && definition.Profile == BackgroundJobExecutionProfile.External && definition.Queue == "external" && definition.OwnerModule == "identity" && definition.CapacityGroup == "identity.invitation_email" @@ -29,7 +38,9 @@ public void Actual_Registry_Binds_Exactly_Two_Active_Definitions_And_Four_Scoped registry.All.Where(request => request.Classification == BackgroundJobRequestClassification.Ordinary) .Select(request => request.RequestType).Should().BeEquivalentTo( new[] { typeof(PrepareTenantInvitationEmailCommand), typeof(FinalizeTenantInvitationEmailCommand), - typeof(PrepareOrganizationInvitationEmailCommand), typeof(FinalizeOrganizationInvitationEmailCommand) }); + typeof(PrepareOrganizationInvitationEmailCommand), typeof(FinalizeOrganizationInvitationEmailCommand), + typeof(RunTenantDataExportCommand), typeof(RunOrganizationDataExportCommand), + typeof(PurgeTenantDataExportCommand), typeof(PurgeOrganizationDataExportCommand) }); foreach (var definition in definitions) { definition.ProfileRegistration.PlanType.Should().Be(); @@ -47,6 +58,53 @@ public void Actual_Registry_Binds_Exactly_Two_Active_Definitions_And_Four_Scoped } } + [Theory] + [InlineData("identity.data_export_tenant.v1", "tenant", "export")] + [InlineData("identity.data_export_organization.v1", "organization", "export")] + [InlineData("identity.data_export_purge_tenant.v1", "tenant", "purge")] + [InlineData("identity.data_export_purge_organization.v1", "organization", "purge")] + public void Actual_Registry_Binds_The_Data_Export_Definitions_As_Transactional_Identifier_Only_Roots(string key, string scope, string purpose) + { + var registry = InvitationEmailRegistration.CreateRegistry(); + var expectedScope = scope == "tenant" ? BackgroundJobScope.TenantWide : BackgroundJobScope.Organization; + var expectedRoot = (purpose, scope) switch + { + ("export", "tenant") => typeof(RunTenantDataExportCommand), + ("export", _) => typeof(RunOrganizationDataExportCommand), + (_, "tenant") => typeof(PurgeTenantDataExportCommand), + _ => typeof(PurgeOrganizationDataExportCommand), + }; + + var definition = registry.Resolve(key).Definition!; + + definition.Readiness.Should().Be(BackgroundJobDefinitionReadiness.Active); + definition.Profile.Should().Be(BackgroundJobExecutionProfile.Transactional); + definition.Queue.Should().Be("transactional"); + definition.CapacityGroup.Should().BeNull(); + definition.OwnerModule.Should().Be("identity"); + definition.Scope.Should().Be(expectedScope); + definition.ParameterType.Should().Be(purpose == "export" ? typeof(DataExportJobParameters) : typeof(DataExportPurgeParameters)); + definition.RootRequestTypes.Should().Equal(expectedRoot); + definition.NestedRequestTypes.Should().BeEmpty(); + registry.TryGet(expectedRoot, out var request).Should().BeTrue(); + request!.Scope.Should().Be(expectedScope); + request.Classification.Should().Be(BackgroundJobRequestClassification.Ordinary); + } + + [Fact] + public void Data_Export_Parameters_Carry_Only_One_Canonical_Identifier() + { + var id = Guid.Parse("019712ac-1234-7000-8000-000000000009"); + foreach (var payload in new object[] { new DataExportJobParameters(id), new DataExportPurgeParameters(id) }) + { + var json = BackgroundJobPayloadContract.Serialize(payload, payload.GetType(), BackgroundJobPayloadKind.Parameters); + BackgroundJobPayloadContract.Read(json, payload.GetType(), BackgroundJobPayloadKind.Parameters).Should().Be(payload); + using var wire = JsonDocument.Parse(json); + var property = wire.RootElement.EnumerateObject().Should().ContainSingle().Subject; + property.Value.GetString().Should().Be(id.ToString("D")); + } + } + [Fact] public void Actual_Registry_Preserves_Two_External_Workers_And_Four_Tenant_Capacity_Slots() { diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 2555160e..d7d8e4a1 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -131,6 +131,13 @@ Both KVKK Madde 11 ("kişisel verileri elde etme") and GDPR Article 15 require g - The bundle is an encrypted private artifact, retrievable only by the subject through a 15-minute ticketed download in their live session, readable for 7 days after completion and revocable (ADR-0107 § 4); no URL is a bearer credential. +- Delivered (P03-10 Step 1): the export job (`identity.data_export_tenant.v1` / + `identity.data_export_organization.v1`) runs on the group's own transaction; Identity, + Tenancy and Audit export sections, Customization and Education only describe + `attribution_reference`. Every identifier in the bundle but the request's own is + written `self` or `third_party`. The ceiling is `DataExport:MaxBytes`, the chunks are + sealed under the `DataExport:KeyRing` secret, both checked at API startup, and a capped + section is stated in the bundle and in the artifact's `truncation` receipt column. - Exports include: identity, memberships, profiles, enrollments, progress, attempts, bookings, attendance, recordings (metadata + signed download links), audit entries where the user is the actor. - Exports exclude: another user's data, tenant-internal admin notes about the user, internal system identifiers that have no meaning outside LearnStack. @@ -308,7 +315,7 @@ govern personal data; exclusion here grants no erasure exemption. | `invitations` | Synchronous scoped Identity offer and acceptance result, including sensitive recipient/verifier and job linkage; the invitation inventory below owns fulfillment constraints | | `federation_connections` | Synchronous tenant-owned federation configuration (ADR-0099): public IdP identifiers, nonsecret digests and lifecycle, with pseudonymous pending/test actor identifiers; no secret, token or assertion and no queued payload | | `data_subject_requests` | Synchronous organization-scoped subject request receipt (ADR-0106): subject and requester UserId, frozen Membership identifiers, closed status/refusal/failure codes, participant progress and retained-kind counts; retained as `request_receipt` with Phase 11 retention, and the job parameters carry identifiers only | -| `data_export_artifacts` | Synchronous export receipt metadata (ADR-0107 § 4): subject, request, size, chunk count, key-ring label and lifecycle; no content or key; retained as `request_receipt` after its chunks are purged | +| `data_export_artifacts` | Synchronous export receipt metadata (ADR-0107 § 4): subject, request, size, chunk count, key-ring label, lifecycle and the immutable closed truncation statement (ADR-0107 § 3: collection names and counts); no content or key; retained as `request_receipt` after its chunks are purged | | `data_export_tickets` | Synchronous session-bound download cursor (ADR-0107 § 4): subject, artifact and credential digests only, never the ticket value; retained as `request_receipt` | | `data_export_chunks` | Synchronous encrypted export bundle (ADR-0107 § 4): PII-Sensitive AES-256-GCM ciphertext of the subject's own data, never in an EF snapshot or audit row; purged at revocation, expiry or erasure, not an asynchronous delivery copy | diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 5086243d..a9df6541 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -69,6 +69,9 @@ The [phase Status](../../roadmap/phase-03-identity-admin.md) owns delivery. | Invitation | `identity.invitation.accept` | **MUST** (`security-event`) | `AcceptInvitationCommand`; central capture includes accepted actor, original Membership and `acceptanceDisposition`. The row shares the grant transaction. | | Original Membership outcome | `identity.membership.admit_invitation` | **MUST** (`security-event`) | Second central intent on acceptance. New Membership includes tracked children; `already_member` identifies the unchanged original Membership with a subject-only row, no fabricated change or arbitrary handler metadata. | | Invitation preparation | `identity.invitation.prepare_email` | **MUST** (`security-event`) | `PrepareTenantInvitationEmailCommand` / `PrepareOrganizationInvitationEmailCommand`; ordinary module-owned preparation records the exact current-generation submission intent before the external stage. No SMTP socket is opened inside its business transaction. | +| Data export fulfilment | `identity.data_request.fulfill_export` | **MUST** (`security-event`) | `RunTenantDataExportCommand` / `RunOrganizationDataExportCommand` ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 2); one row about the `DataSubjectRequest`, written on the job's transaction with `requested → fulfilling → completed` (or `failed` with `export_too_large`). A missing, cancelled or terminal request writes the row as a recorded no-op with no subject. | +| Data export storage | `identity.data_export.store` | **MUST** (`security-event`) | Same two roots, second intent: one row about the stored `DataExportArtifact` (designated by the artifact store); the subject's earlier artifact revoked in the same run travels in its `changes`. Ciphertext is never tracked, so no chunk reaches a row. | +| Data export purge | `identity.data_export.purge` | **MUST** (`delete`) | `PurgeTenantDataExportCommand` / `PurgeOrganizationDataExportCommand`, scheduled at the artifact's expiry; deletes the chunks and records the artifact `purged`. An already revoked or purged artifact is a recorded no-op. | | Invitation submission outcome | `identity.invitation.email_submission` | **MUST** (`security-event`) | `FinalizeTenantInvitationEmailCommand` / `FinalizeOrganizationInvitationEmailCommand`; ordinary owner applies validated durable provider evidence to the exact Invitation. SMTP acceptance is submission only; ambiguous outcomes remain uncertain and retain occupancy. No private audit INSERT or provider receipt substitutes for this row. | | Invitation directory | `identity.invitation.list` | **MUST** (`read-sensitive`) | Administrative bounded offer list under current exact-scope authority before other-person disclosure. | | Invitation detail/status | `identity.invitation.read` | **MUST** (`read-sensitive`) | Administrative detail and bounded normalized current-generation submission evidence, through the owning port; no encrypted body, raw link or another envelope is disclosed. | diff --git a/docs/modules/identity/providers.md b/docs/modules/identity/providers.md index c761da53..96dc9eb3 100644 --- a/docs/modules/identity/providers.md +++ b/docs/modules/identity/providers.md @@ -310,6 +310,15 @@ SMTP settings are `InvitationEmail:Smtp:Host`, `Port`, `Sender`, and `Tls` composition. Missing configuration prevents startup. No connection is made by configuration validation. +The export artifact key ring `DataExport:KeyRing` +([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 4) +has the same shape and rules, resolves through `ISecretProvider` and is checked at +startup by `DataExportStartupService`; rotation adds a key, makes it active and removes +the old one only once every artifact sealed under it has expired (seven days). The bundle +ceiling `DataExport:MaxBytes` is an optional whole number of bytes from 1 MiB to 64 MiB, +16 MiB when absent; any other value refuses composition. The paired launcher selects both +keys for the API alone, with the same single-line, 8 KiB bound. + The paired local API launcher selects only these seven email configuration keys from matching private-file/process sources. Values are compact single-line strings of at most 8 KiB in UTF-8; SMTP credentials may be empty for explicit diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index b20b3538..2ea40c11 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 -**397 test methods run in +**399 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. -**294 rules in this catalogue are Implemented, and 175 of them are in that assembly.** +**296 rules in this catalogue are Implemented, and 177 of them are in that assembly.** The other 119 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 @@ -8007,3 +8007,32 @@ names for the package's obligations are assigned with the step that introduces t [OwnDataRequestScopeConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs), [OwnDataRequestPolicyTests.cs](../../backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs). - **Phase:** 03 (P03-10, retained own scope). + +#### `Every_Module_With_A_Person_Reference_Registers_One_User_Data_Participant` + +- **Asserts:** every module whose model maps a person reference (a `UserId` or + `MembershipId` property, or creator, updater and deleter attribution on a + tenant-owned entity) registers exactly one `IUserDataParticipant` through the + composition root, from inside its own boundary. A module that stops registering, a + second participant in one module and a participant outside every module are each named + by a planted violation. +- **Source:** [ADR-0107 § 1](../decisions/0107-data-request-fulfillment-and-account-closure.md). +- **Type:** composition-root census over the compiled registrations with planted + violations. **Kind:** both. +- **Status:** **Implemented** (`UserDataParticipantCensusTests`). +- **Test owners:** + [UserDataParticipantCensusTests.cs](../../backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs). +- **Phase:** 03 (P03-10, export engine). + +#### `No_Module_References_Another_Modules_User_Data_Participant` + +- **Asserts:** no module assembly references another module's participant assembly, so + the participant registrations stay outside the four cross-module mechanisms of + [ADR-0010](../decisions/0010-cross-module-communication.md). A planted reference from + one module to another's participant assembly is named. +- **Source:** [ADR-0107 § 1](../decisions/0107-data-request-fulfillment-and-account-closure.md). +- **Type:** compiled assembly-reference census with a planted violation. **Kind:** both. +- **Status:** **Implemented** (`UserDataParticipantCensusTests`). +- **Test owners:** + [UserDataParticipantCensusTests.cs](../../backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs). +- **Phase:** 03 (P03-10, export engine). diff --git a/frontend/apps/web/src/server/ingress.ts b/frontend/apps/web/src/server/ingress.ts index 4ea195b1..fac1645f 100644 --- a/frontend/apps/web/src/server/ingress.ts +++ b/frontend/apps/web/src/server/ingress.ts @@ -437,6 +437,28 @@ export function loadLocalEnvironment( result[key] = value; } } + // The export key ring (ADR-0107 § 4) and bundle ceiling belong only to the + // selected API, which validates both at startup. + const dataExportKeys = ['DataExport__KeyRing', 'DataExport__MaxBytes']; + for (const key of dataExportKeys) delete result[key]; + if (options.apiAuthentication) { + for (const key of dataExportKeys) { + const values = [source[key], projection[key], environment[key]].filter( + (value): value is string => value !== undefined, + ); + if (new Set(values).size > 1) throw new Error('Conflicting API data export configuration'); + const value = values[0]; + if (value === undefined) continue; + if ( + typeof value !== 'string' || + !value.trim() || + containsControl(value) || + Buffer.byteLength(value) > 8192 + ) + throw new Error('Invalid API data export configuration'); + result[key] = value; + } + } // Only the API launcher selects this closed secret namespace. Invalid or // conflicting selected values remain invalid for the operation-local API // check instead of preventing unrelated routes from starting. diff --git a/frontend/apps/web/src/test/public-api-environment.test.ts b/frontend/apps/web/src/test/public-api-environment.test.ts index 564ae282..118f271c 100644 --- a/frontend/apps/web/src/test/public-api-environment.test.ts +++ b/frontend/apps/web/src/test/public-api-environment.test.ts @@ -635,6 +635,30 @@ describe('selected invitation email API environment', () => { ).not.toThrow(); }); + it('selects the export key ring and ceiling for the API alone and refuses conflicts and blanks', () => { + const root = temporary(); + const dataExport = { + DataExport__KeyRing: JSON.stringify({ + active: 'owned', + keys: { owned: randomBytes(32).toString('base64') }, + }), + DataExport__MaxBytes: '16777216', + }; + writeEnvironment(root, '.env', { ...apiIdentity, ...dataExport }); + expect(loadLocalEnvironment(root, {}, { apiAuthentication: true })).toMatchObject(dataExport); + for (const key of Object.keys(dataExport)) + expect(loadLocalEnvironment(root, {})).not.toHaveProperty(key); + expect(() => + loadLocalEnvironment(root, { DataExport__MaxBytes: '1048576' }, { apiAuthentication: true }), + ).toThrow(/^Conflicting API data export configuration$/); + expect(publicApiEnvironment({ ...selected(), ...dataExport }, configuration, {})).toMatchObject( + dataExport, + ); + expect(() => + publicApiEnvironment({ ...selected(), DataExport__KeyRing: ' ' }, configuration, {}), + ).toThrow(/^Invalid API data export configuration$/); + }); + it('bounds selected UTF-8 configuration and preserves empty development credentials', () => { const values = { ...selected(), diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 8ab362ea..524e7bc9 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -79,6 +79,9 @@ "LearnStack.Tests.Integration.Database.CustomizationProjectionTests", "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests", "LearnStack.Tests.Integration.Database.CustomizationSchemaTests", + "LearnStack.Tests.Integration.Database.DataExportArtifactStoreTests", + "LearnStack.Tests.Integration.Database.DataExportExecutionTests", + "LearnStack.Tests.Integration.Database.DataExportParticipantTests", "LearnStack.Tests.Integration.Database.DataRequestStorageControlTests", "LearnStack.Tests.Integration.Database.DataRequestStorageTests", "LearnStack.Tests.Integration.Database.DatabaseQualificationProofTests", diff --git a/scripts/demo.mjs b/scripts/demo.mjs index 55bc81da..ea513061 100644 --- a/scripts/demo.mjs +++ b/scripts/demo.mjs @@ -392,6 +392,11 @@ export async function startDemo(mode) { values.InvitationEmail__Smtp__Tls = 'ImplicitTls'; values.InvitationEmail__Smtp__Username = 'synthetic-ci'; values.InvitationEmail__Smtp__Password = randomBytes(24).toString('base64url'); + // The export key ring is checked at API startup like the invitation one. + values.DataExport__KeyRing = JSON.stringify({ + active: 'ci', + keys: { ci: randomBytes(32).toString('base64') }, + }); values.LEARNSTACK_PUBLIC_HOP_SECRET = randomBytes(32).toString('base64url'); values.LEARNSTACK_PUBLIC_TLS_CERT = join(privateRoot, 'leaf.pem'); values.LEARNSTACK_PUBLIC_TLS_KEY = join(privateRoot, 'leaf-key.pem'); diff --git a/scripts/public-runtime.mjs b/scripts/public-runtime.mjs index 445ba764..67bf16d4 100644 --- a/scripts/public-runtime.mjs +++ b/scripts/public-runtime.mjs @@ -54,6 +54,20 @@ export function publicApiEnvironment(values, configuration, base = process.env) throw new Error('Invalid API invitation email configuration'); environment[key] = value; } + // The export key ring and bundle ceiling (ADR-0107 § 4) belong only to the + // selected API, which validates both at startup. + for (const key of ['DataExport__KeyRing', 'DataExport__MaxBytes']) { + const value = values[key]; + if (value === undefined) continue; + if ( + typeof value !== 'string' || + /[\x00-\x1f\x7f]/.test(value) || + Buffer.byteLength(value) > 8192 || + !value.trim() + ) + throw new Error('Invalid API data export configuration'); + environment[key] = value; + } // The API alone receives selected custom-field HMAC configuration. Invalid // material remains invalid for the API's per-operation check; it must not // prevent unrelated routes from starting or borrow ambient values. From 4fb4fc59ec11a763403284adef817e13f9875f13 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 09:06:23 +0300 Subject: [PATCH 07/61] feat(identity): add the data export request API P03-10 Step 1, unit 4a: the live-session API for subject data exports: self and administrator creation, receipts and pages, cancellation, artifact revocation, the 15-minute download ticket and the chunk read, the default eligibility and hold source, the MUST audit entries, the write-store split that keeps each executor on one aggregate, the additive OpenAPI and SDK contract, and the end-to-end tests. Also fixes the stale census pins of the earlier units (hosted startup services, job definition constructors, capture-origin sites, platform head). ADR: 0106, 0107 Module: Identity, Api, SharedKernel Co-Authored-By: Claude Sonnet 5.5 --- backend/openapi/v1.json | 4357 ++++++++++++++++- .../HttpDataExportSessionBinding.cs | 63 + .../HttpIdentitySelfEntryAdmission.cs | 3 + .../OperationHttpClassification.cs | 13 + .../Common/AdministrationHttpSurface.cs | 14 +- .../ProtectedAdministrationOperation.cs | 36 + .../ProtectedAdministrationResult.cs | 20 +- .../Idempotency/ProtectedIdempotencyFilter.cs | 2 +- .../ProtectedReceiptReplayDispatcher.cs | 5 + .../ProtectedReplayHttpAdmission.cs | 5 + .../DataRequestDocumentTransformer.cs | 309 ++ .../Identity/DataRequestResponses.cs | 87 + .../Identity/DataRequestsController.cs | 265 + .../Versioning/ApiVersioningExtensions.cs | 1 + ...000_add_data_request_protected_receipts.cs | 39 + .../Idempotency/IdempotencyReplayTarget.cs | 1 + .../DataRequests/DataRequestOperations.cs | 153 + .../DataRequests/IDataExportSessionBinding.cs | 34 + .../Audit/IdentityAuditCatalogSource.cs | 19 + .../DataRequests/DataExportDownloadService.cs | 163 + .../DataRequests/DataExportJobs.cs | 2 +- .../DataRequests/DataExportTicketCodec.cs | 80 + .../DataRequests/DataRequestAuthorization.cs | 70 + .../DataRequests/DataRequestCursorCodec.cs | 85 + .../DataRequests/DataRequestEligibility.cs | 61 + .../DataRequestFailureReconciler.cs | 33 +- .../DataRequestFulfillmentScheduler.cs | 28 +- .../DataRequests/DataRequestHandlers.cs | 184 + .../DataRequests/DataRequestService.cs | 450 ++ .../DataRequests/DataRequestValidators.cs | 117 + .../DataRequests/IDataRequestStore.cs | 90 +- .../IdentityOperationPolicySource.cs | 32 + .../IdentityFoundationRegistration.cs | 12 + .../DataRequests/DataExportTicketStore.cs | 106 + .../DataRequests/DataRequestJobPhaseReader.cs | 89 +- .../DataRequests/DataRequestReader.cs | 176 + .../DataRequests/DataRequestSql.cs | 43 + .../DataRequests/DataRequestStore.cs | 125 +- .../AggregateWriteTests.cs | 52 + ...dHttpSurfaceTests.DescriptorInterpreter.cs | 2 +- ...edHttpSurfaceTests.ProtectedDescriptors.cs | 20 +- .../AuthenticatedHttpSurfaceTests.cs | 45 +- .../IdempotencyConventionTests.cs | 9 + ...itConventionTests.AuthorizationEvidence.cs | 10 +- .../IdentityFoundationConventionTests.cs | 9 + .../OperationPermissionConventionTests.cs | 7 + .../OperationPolicyOwnershipTests.cs | 5 +- .../OutboxDispatchObservationTests.cs | 10 + .../PersistenceConventionTests.Enrollment.cs | 6 +- .../OpenApiContractTests.DataRequests.cs | 119 + .../OpenApiContractTests.cs | 6 +- .../Api/OperationHttpClassificationTests.cs | 23 +- ...ticatedHttpSurfaceRuntimeTests.Metadata.cs | 3 +- .../AuthenticatedHttpSurfaceRuntimeTests.cs | 35 +- .../Database/DataExportExecutionTests.cs | 4 +- .../DataRequestHttpTests.Administration.cs | 219 + .../Database/DataRequestHttpTests.Export.cs | 123 + .../DataRequestHttpTests.Mutations.cs | 145 + .../Database/DataRequestHttpTests.Tickets.cs | 148 + .../Database/DataRequestHttpTests.cs | 221 + .../DataRequestServiceStorageTests.cs | 87 + .../Database/MigrationRollbackTests.cs | 8 +- .../HttpDataExportSessionBindingTests.cs | 75 + .../OperationClauseWitnessTests.cs | 2 +- .../OperationPolicyCatalogTests.cs | 15 +- .../Identity/DataRequestCodecTests.cs | 73 + .../DataRequestFulfillmentSchedulerTests.cs | 8 +- .../Identity/DataRequestServiceTests.cs | 573 +++ docs/modules/identity/README.md | 72 + docs/modules/identity/audit.md | 23 + docs/modules/identity/permissions.md | 23 + .../21-architecture-tests-catalogue.md | 12 +- .../sdk/src/administration-contract.ts | 4 + .../sdk/src/authenticated-contract.test.ts | 8 + .../packages/sdk/src/generated/schema.d.ts | 1905 +++++++ scripts/ci-test-shards-plan.json | 2 + 76 files changed, 11351 insertions(+), 132 deletions(-) create mode 100644 backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs create mode 100644 backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs create mode 100644 backend/src/LearnStack.Api/Identity/DataRequestResponses.cs create mode 100644 backend/src/LearnStack.Api/Identity/DataRequestsController.cs create mode 100644 backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261122160000_add_data_request_protected_receipts.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IDataExportSessionBinding.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportDownloadService.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTicketCodec.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestAuthorization.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestCursorCodec.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestEligibility.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestHandlers.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestValidators.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestReader.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestSql.cs create mode 100644 backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Export.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Mutations.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Api/Authentication/HttpDataExportSessionBindingTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataRequestCodecTests.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs diff --git a/backend/openapi/v1.json b/backend/openapi/v1.json index 733e312a..e209654e 100644 --- a/backend/openapi/v1.json +++ b/backend/openapi/v1.json @@ -6175,6 +6175,3683 @@ "x-version-introduced": "v1" } }, + "/api/v1/identity/me/data-requests/exports": { + "post": { + "tags": [ + "OwnDataRequests" + ], + "description": "The subject files an export of their own data in the session\u0027s group (ADR-0106 \u00A7 3). Requires an Active Membership in exactly that group; no permission key. The request holds the frozen snapshot of the subject\u0027s Memberships of any status in the group and its job is submitted on the same transaction. Strict empty JSON object. MUST audited.", + "operationId": "CreateOwnDataExport", + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "Accepted: the request\u0027s initial resource. Its export runs as a background job; read the Location for its status.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Location": { + "description": "Exact same-API relative location of the new request\u0027s receipt.", + "required": true, + "schema": { + "pattern": "^/api/v1/identity/me/data-requests/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataRequestAcceptedResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests": { + "get": { + "tags": [ + "OwnDataRequests" + ], + "description": "The subject\u0027s own requests in the session\u0027s group, newest first. A request whose job died is shown failed. Audit Off. No request body.", + "operationId": "ListOwnDataRequests", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "schema": { + "maxLength": 1024, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + "schema": { + "maximum": 2147483647, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnDataRequestPage" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests/{id}": { + "get": { + "tags": [ + "OwnDataRequests" + ], + "description": "The subject\u0027s own request receipt: identity, kind, origin, status, timestamps, the recorded refusal or failure code, the closed retained-reference kinds and counts and the artifact\u0027s metadata. No content. Audit Off. No request body.", + "operationId": "GetOwnDataRequest", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnDataRequestResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests/{id}/cancellations": { + "post": { + "tags": [ + "OwnDataRequests" + ], + "description": "The subject cancels a requested export (requested to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited.", + "operationId": "CancelOwnDataRequest", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests/{id}/artifact/revocations": { + "post": { + "tags": [ + "OwnDataRequests" + ], + "description": "The subject revokes an unexpired available artifact of a request about them, which deletes its chunks at once; the metadata stays as the receipt. Strict empty JSON object. MUST audited.", + "operationId": "RevokeOwnDataExport", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal artifact version (the receipt\u0027s artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The artifact\u0027s version after the revocation.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests/{id}/artifact/tickets": { + "post": { + "tags": [ + "OwnDataExportTickets" + ], + "description": "The subject mints a fifteen-minute download cursor over their own available, unexpired artifact, bound to the credential of this session; an administrator never gets one. Stored only as a digest; not keyed and never replayed; no If-Match. Strict empty JSON object. MUST read-sensitive audited; refused when the row cannot be written.", + "operationId": "MintOwnDataExportTicket", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportTicketResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/me/data-requests/{id}/artifact/chunks": { + "post": { + "tags": [ + "OwnDataExportChunks" + ], + "description": "Reads one decrypted chunk through a ticket presented in the body, never the URL, in the session that minted it. Any index below count may be read while the ticket is unconsumed and unexpired; serving the final chunk (count - 1) consumes it, and a resumed download mints a new ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written.", + "operationId": "ReadOwnDataExportChunk", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportChunkInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportChunkResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no live session the ticket can bind.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-requests/exports": { + "post": { + "tags": [ + "DataRequests" + ], + "description": "An administrator holding identity.membership.admin over the group files an export for the person who holds or held the named Membership, of any status, in the group; never for themselves. The administrator sees status and counts only and never receives the bundle. Strict JSON object with membershipId only. MUST audited.", + "operationId": "CreateDataExportForSubject", + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportForSubjectInput" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "Accepted: the request\u0027s initial resource. Its export runs as a background job; read the Location for its status.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Location": { + "description": "Exact same-API relative location of the new request\u0027s receipt.", + "required": true, + "schema": { + "pattern": "^/api/v1/identity/data-requests/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataRequestAcceptedResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke).", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-requests": { + "get": { + "tags": [ + "DataRequests" + ], + "description": "The group\u0027s export and erasure requests, newest first: status and counts only, never content, never a closure. MUST read-sensitive audited; refused when the row cannot be written. No request body.", + "operationId": "ListDataRequests", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "schema": { + "maxLength": 1024, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + "schema": { + "maximum": 2147483647, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataRequestPage" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke).", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-requests/{id}": { + "get": { + "tags": [ + "DataRequests" + ], + "description": "One request of the group: status and counts only, never content. MUST read-sensitive audited; refused when the row cannot be written. No request body.", + "operationId": "GetDataRequest", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataRequestResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke).", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-requests/{id}/cancellations": { + "post": { + "tags": [ + "DataRequests" + ], + "description": "The administrator who filed an export cancels it while it is still requested. Strict empty JSON object. MUST audited.", + "operationId": "CancelDataRequest", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke).", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-requests/{id}/artifact/revocations": { + "post": { + "tags": [ + "DataRequests" + ], + "description": "The administrator who filed an export revokes its unexpired available artifact, which deletes its chunks at once. Strict empty JSON object. MUST audited.", + "operationId": "RevokeDataExport", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase RFC UUIDv7 of a request of the context\u0027s group. Another group\u0027s request is absent.", + "required": true, + "schema": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal artifact version (the receipt\u0027s artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The artifact\u0027s version after the revocation.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke).", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 16 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, "/api/v1/identity/federation": { "get": { "tags": [ @@ -22829,87 +26506,510 @@ } ] }, - "CustomFieldValueEnvelope": { + "CustomFieldValueEnvelope": { + "required": [ + "value" + ], + "type": "object", + "properties": { + "value": { + "$ref": "#/components/schemas/CustomFieldValueNode0" + } + }, + "additionalProperties": false + }, + "CustomFieldValueNode0": { + "anyOf": [ + { + "maxLength": 256, + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "maxItems": 10, + "type": "array", + "items": { + "$ref": "#/components/schemas/CustomFieldValueNode1" + } + }, + { + "maxProperties": 10, + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CustomFieldValueNode1" + } + } + ] + }, + "CustomFieldValueNode1": { + "anyOf": [ + { + "maxLength": 256, + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "maxItems": 10, + "type": "array", + "items": { + "$ref": "#/components/schemas/CustomFieldValueNode2" + } + }, + { + "maxProperties": 10, + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CustomFieldValueNode2" + } + } + ] + }, + "CustomFieldValueNode2": { + "anyOf": [ + { + "maxLength": 256, + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ] + }, + "DataExportArtifactResponse": { + "required": [ + "id", + "status", + "expiresAt", + "purgedAt", + "byteCount", + "chunkCount", + "truncations", + "version", + "readable" + ], + "type": "object", + "properties": { + "id": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "status": { + "enum": [ + "available", + "revoked", + "expired", + "purged" + ], + "type": "string" + }, + "expiresAt": { + "type": "string", + "format": "date-time" + }, + "purgedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "byteCount": { + "maximum": 67108864, + "minimum": 1, + "type": "integer", + "format": "int64" + }, + "chunkCount": { + "maximum": 512, + "minimum": 1, + "type": "integer", + "format": "int32" + }, + "truncations": { + "maxItems": 32, + "type": "array", + "items": { + "$ref": "#/components/schemas/DataExportTruncationResponse" + } + }, + "version": { + "maxLength": 19, + "minLength": 1, + "pattern": "^(0|[1-9][0-9]{0,18})$", + "type": "string", + "description": "Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number." + }, + "readable": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "DataExportChunkInput": { + "required": [ + "ticket", + "index" + ], + "type": "object", + "properties": { + "ticket": { + "maxLength": 43, + "minLength": 43, + "pattern": "^[A-Za-z0-9_-]{43}$", + "type": "string", + "description": "Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log." + }, + "index": { + "maximum": 511, + "minimum": 0, + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "DataExportChunkResponse": { + "required": [ + "index", + "count", + "bytes" + ], + "type": "object", + "properties": { + "index": { + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "count": { + "minimum": 1, + "type": "integer", + "format": "int32" + }, + "bytes": { + "contentEncoding": "base64", + "maxLength": 174764, + "minLength": 4, + "type": "string", + "description": "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk in index order yields the bundle." + } + }, + "additionalProperties": false + }, + "DataExportForSubjectInput": { + "required": [ + "membershipId" + ], + "type": "object", + "properties": { + "membershipId": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "DataExportTicketResponse": { + "required": [ + "ticket", + "expiresAt", + "chunkCount", + "byteCount" + ], + "type": "object", + "properties": { + "ticket": { + "maxLength": 43, + "minLength": 43, + "pattern": "^[A-Za-z0-9_-]{43}$", + "type": "string", + "description": "Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log." + }, + "expiresAt": { + "type": "string", + "format": "date-time" + }, + "chunkCount": { + "maximum": 512, + "minimum": 1, + "type": "integer", + "format": "int32" + }, + "byteCount": { + "maximum": 67108864, + "minimum": 1, + "type": "integer", + "format": "int64" + } + }, + "additionalProperties": false + }, + "DataExportTruncationResponse": { + "required": [ + "collection", + "included", + "total" + ], + "type": "object", + "properties": { + "collection": { + "maxLength": 65, + "type": "string" + }, + "included": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer", + "format": "int64" + }, + "total": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer", + "format": "int64" + } + }, + "additionalProperties": false + }, + "DataRequestAcceptedResponse": { + "required": [ + "id", + "kind", + "status", + "version" + ], + "type": "object", + "properties": { + "id": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "kind": { + "enum": [ + "export" + ], + "type": "string" + }, + "status": { + "enum": [ + "requested" + ], + "type": "string" + }, + "version": { + "maxLength": 19, + "minLength": 1, + "pattern": "^(0|[1-9][0-9]{0,18})$", + "type": "string", + "description": "Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number." + } + }, + "additionalProperties": false + }, + "DataRequestPage": { "required": [ - "value" + "items", + "pageInfo" ], "type": "object", "properties": { - "value": { - "$ref": "#/components/schemas/CustomFieldValueNode0" + "items": { + "maxItems": 100, + "type": "array", + "items": { + "$ref": "#/components/schemas/DataRequestResponse" + } + }, + "pageInfo": { + "$ref": "#/components/schemas/PageInfo" } }, "additionalProperties": false }, - "CustomFieldValueNode0": { - "anyOf": [ - { - "maxLength": 256, + "DataRequestResponse": { + "required": [ + "id", + "kind", + "origin", + "status", + "createdAt", + "updatedAt", + "completedAt", + "lastRefusal", + "failureReason", + "retained", + "artifact", + "version", + "requestedByYou", + "membershipIds" + ], + "type": "object", + "properties": { + "id": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "kind": { + "enum": [ + "export", + "erasure", + "closure" + ], "type": "string" }, - { - "type": "number" + "origin": { + "enum": [ + "self", + "administrator", + "closure_fanout" + ], + "type": "string" }, - { - "type": "boolean" + "status": { + "enum": [ + "requested", + "scheduled", + "fulfilling", + "awaiting_privileged_step", + "completed", + "blocked", + "failed", + "cancelled" + ], + "type": "string" }, - { - "maxItems": 10, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "completedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastRefusal": { + "enum": [ + "blocked_window", + "blocked_hold", + "blocked_last_administrator", + null + ], + "type": [ + "null", + "string" + ] + }, + "failureReason": { + "enum": [ + "export_too_large", + "execution_failed", + null + ], + "type": [ + "null", + "string" + ] + }, + "retained": { + "maxItems": 16, "type": "array", "items": { - "$ref": "#/components/schemas/CustomFieldValueNode1" + "$ref": "#/components/schemas/DataRequestRetainedResponse" } }, - { - "maxProperties": 10, - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/CustomFieldValueNode1" - } - } - ] - }, - "CustomFieldValueNode1": { - "anyOf": [ - { - "maxLength": 256, - "type": "string" + "artifact": { + "oneOf": [ + { + "$ref": "#/components/schemas/DataExportArtifactResponse" + }, + { + "type": "null" + } + ] }, - { - "type": "number" + "version": { + "maxLength": 19, + "minLength": 1, + "pattern": "^(0|[1-9][0-9]{0,18})$", + "type": "string", + "description": "Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number." }, - { + "requestedByYou": { "type": "boolean" }, - { - "maxItems": 10, + "membershipIds": { + "maxItems": 256, "type": "array", "items": { - "$ref": "#/components/schemas/CustomFieldValueNode2" - } - }, - { - "maxProperties": 10, - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/CustomFieldValueNode2" + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" } } - ] + }, + "additionalProperties": false }, - "CustomFieldValueNode2": { - "anyOf": [ - { - "maxLength": 256, + "DataRequestRetainedResponse": { + "required": [ + "kind", + "count" + ], + "type": "object", + "properties": { + "kind": { + "enum": [ + "consent_evidence", + "invitation_record", + "invitation_envelope", + "audit_actor_reference", + "audit_entity_reference", + "audit_metadata_reference", + "unscoped_audit_rows", + "transport_evidence", + "execution_evidence", + "provider_event_record", + "idempotency_cache", + "attribution_reference", + "federation_actor_reference", + "request_receipt", + "external_copy", + "unserved_group" + ], "type": "string" }, - { - "type": "number" - }, - { - "type": "boolean" + "count": { + "minimum": 0, + "type": "integer", + "format": "int64" } - ] + }, + "additionalProperties": false }, "DefaultOrganizationInput": { "required": [ @@ -24542,6 +28642,145 @@ }, "additionalProperties": false }, + "OwnDataRequestPage": { + "required": [ + "items", + "pageInfo" + ], + "type": "object", + "properties": { + "items": { + "maxItems": 100, + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnDataRequestResponse" + } + }, + "pageInfo": { + "$ref": "#/components/schemas/PageInfo" + } + }, + "additionalProperties": false + }, + "OwnDataRequestResponse": { + "required": [ + "id", + "kind", + "origin", + "status", + "createdAt", + "updatedAt", + "completedAt", + "lastRefusal", + "failureReason", + "retained", + "artifact", + "version" + ], + "type": "object", + "properties": { + "id": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "kind": { + "enum": [ + "export", + "erasure", + "closure" + ], + "type": "string" + }, + "origin": { + "enum": [ + "self", + "administrator", + "closure_fanout" + ], + "type": "string" + }, + "status": { + "enum": [ + "requested", + "scheduled", + "fulfilling", + "awaiting_privileged_step", + "completed", + "blocked", + "failed", + "cancelled" + ], + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "completedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastRefusal": { + "enum": [ + "blocked_window", + "blocked_hold", + "blocked_last_administrator", + null + ], + "type": [ + "null", + "string" + ] + }, + "failureReason": { + "enum": [ + "export_too_large", + "execution_failed", + null + ], + "type": [ + "null", + "string" + ] + }, + "retained": { + "maxItems": 16, + "type": "array", + "items": { + "$ref": "#/components/schemas/DataRequestRetainedResponse" + } + }, + "artifact": { + "oneOf": [ + { + "$ref": "#/components/schemas/DataExportArtifactResponse" + }, + { + "type": "null" + } + ] + }, + "version": { + "maxLength": 19, + "minLength": 1, + "pattern": "^(0|[1-9][0-9]{0,18})$", + "type": "string", + "description": "Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number." + } + }, + "additionalProperties": false + }, "OwnFieldConsentCurrentResponse": { "required": [ "consent" @@ -25564,6 +29803,18 @@ { "name": "PublicSite" }, + { + "name": "OwnDataRequests" + }, + { + "name": "OwnDataExportTickets" + }, + { + "name": "OwnDataExportChunks" + }, + { + "name": "DataRequests" + }, { "name": "Federation" }, diff --git a/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs b/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs new file mode 100644 index 00000000..fb05a842 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs @@ -0,0 +1,63 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Api.Authentication; + +/// +/// Binds a download ticket to the live session that minted it (ADR-0107 § 4): a SHA-256 digest, domain-separated and +/// length-prefixed, of the announced group, the actor, the verified issuer and subject, and the digest of the exact +/// bearer credential this request presented and the tenant scheme validated. +/// +/// +/// +/// Nothing a caller chooses selects it: the credential feature is set only by the stock token validation of this +/// request, and the actor must be the one its binding normalized. A request without a validated tenant credential, +/// with a second Authorization value, or for another actor gets no binding, so no ticket is minted or honoured. +/// +/// +/// The raw credential never leaves this method; only its digest enters the binding, and the binding is itself only +/// a digest on the ticket row, which the audit capture redacts. +/// +/// +internal sealed class HttpDataExportSessionBinding(IHttpContextAccessor accessor) : IDataExportSessionBinding +{ + private const string Domain = "learnstack.data_export.session.v1"; + private const string Prefix = "Bearer "; + + public string? Capture(UserId actor, TenantId tenant, OrganizationId? organization) + { + var http = accessor.HttpContext; + if (http is null || http.RequestAborted.IsCancellationRequested + || http.Features.Get() is not { VerifiedSubject: { } subject, Identity: { } identity } + || identity.ActorUserId != actor || actor == UserId.SystemActor + || http.Request.Headers.Authorization is not { Count: 1 } values || values[0] is not { } header + || !header.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) || header.Length <= Prefix.Length) + { + return null; + } + + using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Append(digest, Domain); + Append(digest, tenant.Value.ToString("D")); + Append(digest, organization?.Value.ToString("D") ?? string.Empty); + Append(digest, actor.Value.ToString("D")); + Append(digest, subject.Issuer); + Append(digest, subject.Subject); + Append(digest, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(header[Prefix.Length..])))); + return Convert.ToHexStringLower(digest.GetHashAndReset()); + } + + private static void Append(IncrementalHash digest, string value) + { + var bytes = Encoding.UTF8.GetBytes(value); + Span length = stackalloc byte[sizeof(int)]; + BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length); + digest.AppendData(length); + digest.AppendData(bytes); + } + + public override string ToString() => nameof(HttpDataExportSessionBinding); +} diff --git a/backend/src/LearnStack.Api/Authentication/HttpIdentitySelfEntryAdmission.cs b/backend/src/LearnStack.Api/Authentication/HttpIdentitySelfEntryAdmission.cs index 8f6191ea..53b685be 100644 --- a/backend/src/LearnStack.Api/Authentication/HttpIdentitySelfEntryAdmission.cs +++ b/backend/src/LearnStack.Api/Authentication/HttpIdentitySelfEntryAdmission.cs @@ -88,6 +88,9 @@ internal static IServiceCollection AddLearnStackIdentitySelfEntry(this IServiceC services.AddScoped>(provider => () => provider.GetRequiredService()); services.Replace(ServiceDescriptor.Scoped(provider => provider.GetRequiredService())); services.Replace(ServiceDescriptor.Scoped(provider => provider.GetRequiredService())); + // ADR-0107 § 4: a download ticket binds the validated credential of the request that minted it. + services.Replace(ServiceDescriptor.Scoped()); services.AddSingleton(provider => new NativeEntryOriginOptions(provider.GetRequiredService())); return services; } diff --git a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs index 677f0ef0..e736dd46 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs @@ -14,6 +14,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Federation; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Account; using LearnStack.Modules.Tenancy.Application.Contracts.PublicReads; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; @@ -210,6 +211,18 @@ private static bool IsFrameworkMethodRejection(Endpoint endpoint) => endpoint.Ge var pair when pair == (typeof(InvitableRolesController), nameof(InvitableRolesController.List)) => (typeof(ListInvitableRolesQuery), "ListInvitableRoles", "GET"), var pair when pair == (typeof(InvitationPolicyController), nameof(InvitationPolicyController.Get)) => (typeof(GetTenantInvitationPolicyQuery), "GetTenantInvitationPolicy", "GET"), var pair when pair == (typeof(InvitationPolicyController), nameof(InvitationPolicyController.Set)) => (typeof(SetTenantInvitationLifetimeCommand), "SetTenantInvitationLifetime", "PUT"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.Create)) => (typeof(CreateOwnDataExportCommand), "CreateOwnDataExport", "POST"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.List)) => (typeof(ListOwnDataRequestsQuery), "ListOwnDataRequests", "GET"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.Get)) => (typeof(GetOwnDataRequestQuery), "GetOwnDataRequest", "GET"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.Cancel)) => (typeof(CancelOwnDataRequestCommand), "CancelOwnDataRequest", "POST"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.Revoke)) => (typeof(RevokeOwnDataExportCommand), "RevokeOwnDataExport", "POST"), + var pair when pair == (typeof(OwnDataExportTicketsController), nameof(OwnDataExportTicketsController.MintTicket)) => (typeof(MintOwnDataExportTicketCommand), "MintOwnDataExportTicket", "POST"), + var pair when pair == (typeof(OwnDataExportChunksController), nameof(OwnDataExportChunksController.ReadChunk)) => (typeof(ReadOwnDataExportChunkCommand), "ReadOwnDataExportChunk", "POST"), + var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Create)) => (typeof(CreateDataExportForSubjectCommand), "CreateDataExportForSubject", "POST"), + var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.List)) => (typeof(ListDataRequestsQuery), "ListDataRequests", "GET"), + var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Get)) => (typeof(GetDataRequestQuery), "GetDataRequest", "GET"), + var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Cancel)) => (typeof(CancelDataRequestCommand), "CancelDataRequest", "POST"), + var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Revoke)) => (typeof(RevokeDataExportCommand), "RevokeDataExport", "POST"), var pair when pair == (typeof(FederationController), nameof(FederationController.Get)) => (typeof(GetFederationConnectionQuery), "GetFederationConnection", "GET"), var pair when pair == (typeof(FederationController), nameof(FederationController.Configure)) => (typeof(BeginConfigureFederationCommand), "ConfigureFederation", "PUT"), var pair when pair == (typeof(FederationController), nameof(FederationController.RotateSecret)) => (typeof(BeginRotateFederationSecretCommand), "RotateFederationSecret", "POST"), diff --git a/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs index 42e70e93..0113db07 100644 --- a/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs +++ b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs @@ -29,7 +29,19 @@ internal static bool IsPath(PathString path) ("identity", "memberships" or "roles", 6) => true, ("identity", "memberships", 7) => parts[6].ToLowerInvariant() is "profile" or "role-assignments" or "status" or "custom-fields", ("identity", "roles", 7) => parts[6].ToLowerInvariant() is "grants" or "manifest-adoptions", - ("identity", "me", 6) => parts[5].ToLowerInvariant() is "profile" or "contexts" or "capabilities" or "custom-fields", + ("identity", "me", 6) => parts[5].ToLowerInvariant() is "profile" or "contexts" or "capabilities" or "custom-fields" or "data-requests", + // ADR-0106, ADR-0107 § 4: the subject's own data requests, their artifact and its ticketed download. + ("identity", "me", 7) => parts[5].Equals("data-requests", StringComparison.OrdinalIgnoreCase), + ("identity", "me", 8) => parts[5].Equals("data-requests", StringComparison.OrdinalIgnoreCase) + && parts[7].Equals("cancellations", StringComparison.OrdinalIgnoreCase), + ("identity", "me", 9) => parts[5].Equals("data-requests", StringComparison.OrdinalIgnoreCase) + && parts[7].Equals("artifact", StringComparison.OrdinalIgnoreCase) + && parts[8].ToLowerInvariant() is "revocations" or "tickets" or "chunks", + // The administrator's view of the group's data requests: status and counts, never content. + ("identity", "data-requests", 5 or 6) => true, + ("identity", "data-requests", 7) => parts[6].Equals("cancellations", StringComparison.OrdinalIgnoreCase), + ("identity", "data-requests", 8) => parts[6].Equals("artifact", StringComparison.OrdinalIgnoreCase) + && parts[7].Equals("revocations", StringComparison.OrdinalIgnoreCase), ("tenancy", "organizations" or "default-organization", 5) => true, ("tenancy", "organizations", 6) => true, ("tenancy", "organizations", 7) => parts[6].Equals("archive", StringComparison.OrdinalIgnoreCase), diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs index ac88fd6f..50d0e8fc 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs @@ -7,6 +7,7 @@ using LearnStack.Modules.Tenancy.Application.Contracts.Settings; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Idempotency; @@ -38,6 +39,12 @@ public enum ProtectedAdministrationOperation SetOwnCustomFields = 21, GrantOwnFieldConsent = 22, WithdrawOwnFieldConsent = 23, + CreateOwnDataExport = 24, + CreateDataExportForSubject = 25, + CancelOwnDataRequest = 26, + CancelDataRequest = 27, + RevokeOwnDataExport = 28, + RevokeDataExport = 29, } internal sealed record ProtectedAdministrationDescriptor( @@ -49,6 +56,16 @@ or ProtectedAdministrationOperation.RetireCustomFieldRevision or ProtectedAdmini or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministrationOperation.SetOwnCustomFields or ProtectedAdministrationOperation.GrantOwnFieldConsent or ProtectedAdministrationOperation.WithdrawOwnFieldConsent; internal bool IsConsent => Operation is ProtectedAdministrationOperation.GrantOwnFieldConsent or ProtectedAdministrationOperation.WithdrawOwnFieldConsent; + + /// + /// ADR-0106 § 10: a data-request creation is accepted, not finished — 202 with the request's initial resource, its + /// Location and its ETag. Every other keyed creation answers 201 and every other mutation 200. + /// + internal bool IsDataRequestCreation => Operation is ProtectedAdministrationOperation.CreateOwnDataExport + or ProtectedAdministrationOperation.CreateDataExportForSubject; + + internal int SuccessStatus => IsDataRequestCreation ? StatusCodes.Status202Accepted + : Creates ? StatusCodes.Status201Created : StatusCodes.Status200OK; private static readonly ProtectedAdministrationDescriptor[] Descriptors = Enum.GetValues().Select(For).ToArray(); @@ -84,6 +101,12 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra ProtectedAdministrationOperation.SetOwnCustomFields => new(operation, typeof(SetOwnMembershipCustomFieldsCommand), IdempotencyReplayTargetKind.Membership), ProtectedAdministrationOperation.GrantOwnFieldConsent => new(operation, typeof(GrantOwnMembershipFieldConsentCommand), IdempotencyReplayTargetKind.MembershipFieldConsent), ProtectedAdministrationOperation.WithdrawOwnFieldConsent => new(operation, typeof(WithdrawOwnMembershipFieldConsentCommand), IdempotencyReplayTargetKind.MembershipFieldConsent), + ProtectedAdministrationOperation.CreateOwnDataExport => new(operation, typeof(CreateOwnDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CreateDataExportForSubject => new(operation, typeof(CreateDataExportForSubjectCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CancelOwnDataRequest => new(operation, typeof(CancelOwnDataRequestCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.CancelDataRequest => new(operation, typeof(CancelDataRequestCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.RevokeOwnDataExport => new(operation, typeof(RevokeOwnDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.RevokeDataExport => new(operation, typeof(RevokeDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; @@ -112,6 +135,12 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra SetOwnMembershipCustomFieldsCommand => ProtectedAdministrationOperation.SetOwnCustomFields, GrantOwnMembershipFieldConsentCommand => ProtectedAdministrationOperation.GrantOwnFieldConsent, WithdrawOwnMembershipFieldConsentCommand => ProtectedAdministrationOperation.WithdrawOwnFieldConsent, + CreateOwnDataExportCommand => ProtectedAdministrationOperation.CreateOwnDataExport, + CreateDataExportForSubjectCommand => ProtectedAdministrationOperation.CreateDataExportForSubject, + CancelOwnDataRequestCommand => ProtectedAdministrationOperation.CancelOwnDataRequest, + CancelDataRequestCommand => ProtectedAdministrationOperation.CancelDataRequest, + RevokeOwnDataExportCommand => ProtectedAdministrationOperation.RevokeOwnDataExport, + RevokeDataExportCommand => ProtectedAdministrationOperation.RevokeDataExport, _ => null, }; @@ -137,6 +166,11 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra DiscardCustomFieldDefinitionDraftCommand command => command.ExpectedVersion, SetMembershipCustomFieldsCommand command => command.ExpectedVersion, SetOwnMembershipCustomFieldsCommand command => command.ExpectedVersion, + CreateOwnDataExportCommand or CreateDataExportForSubjectCommand => null, + CancelOwnDataRequestCommand command => command.ExpectedVersion, + CancelDataRequestCommand command => command.ExpectedVersion, + RevokeOwnDataExportCommand command => command.ExpectedArtifactVersion, + RevokeDataExportCommand command => command.ExpectedArtifactVersion, _ => throw new ArgumentException("The protected operation is not registered.", nameof(request)), }; internal bool TryReadPrecondition(HttpRequest request, out long? expected) @@ -155,6 +189,8 @@ internal bool TryReadPrecondition(HttpRequest request, out long? expected) { ProtectedAdministrationOperation.CreateInvitation => "/api/v1/identity/invitations/" + id.ToString("D"), ProtectedAdministrationOperation.RegisterCustomFieldDefinition => "/api/v1/customization/custom-field-definitions/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateOwnDataExport => "/api/v1/identity/me/data-requests/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateDataExportForSubject => "/api/v1/identity/data-requests/" + id.ToString("D"), _ => OrganizationLocationFor(id), }; internal static string OrganizationLocationFor(Guid id) => "/api/v1/tenancy/organizations/" + id.ToString("D"); diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs index f1c922b8..51b1d84f 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs @@ -8,6 +8,7 @@ using LearnStack.Api.Common; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Idempotency; using LearnStack.SharedKernel.Identifiers; @@ -83,9 +84,22 @@ internal static async Task ExecuteAsync(HttpContext http, ISender SetOwnMembershipCustomFieldsCommand command => Membership(await sender.Send(command, cancellationToken), null), GrantOwnMembershipFieldConsentCommand command => Consent(await sender.Send(command, cancellationToken), true), WithdrawOwnMembershipFieldConsentCommand command => Consent(await sender.Send(command, cancellationToken), false), + CreateOwnDataExportCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CreateDataExportForSubjectCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CancelOwnDataRequestCommand command => DataRequest(await sender.Send(command, cancellationToken), command.RequestId), + CancelDataRequestCommand command => DataRequest(await sender.Send(command, cancellationToken), command.RequestId), + RevokeOwnDataExportCommand command => Artifact(await sender.Send(command, cancellationToken), command.RequestId), + RevokeDataExportCommand command => Artifact(await sender.Send(command, cancellationToken), command.RequestId), _ => throw new InvalidOperationException("The protected operation is not registered."), }; + // ADR-0106 § 10: the replay target of every data-request receipt is the request; an artifact revocation's + // version is the artifact's, which its ETag and the next If-Match carry. + IActionResult DataRequest(Result result, Guid? requested) => result.IsFailure + ? new ProblemDetailsActionResult(result.Error) : Create(result.Value.RequestId, result.Value.Version, requested); + IActionResult Artifact(Result result, Guid requested) => result.IsFailure + ? new ProblemDetailsActionResult(result.Error) : Create(result.Value.RequestId, result.Value.Version, requested); + IActionResult Definition(Result result, Guid target) => result.IsFailure ? new ProblemDetailsActionResult(result.Error) : Create(result.Value.DefinitionId, result.Value.Version, target); IActionResult Consent(Result result, bool granted) => result.IsFailure @@ -122,7 +136,9 @@ internal bool Matches(ProtectedAdministrationDescriptor descriptor, ITenantConte internal static byte[] BodyFor(long version) => Encoding.UTF8.GetBytes( "{\"version\":\"" + version.ToString(CultureInfo.InvariantCulture) + "\"}"); internal static byte[] BodyFor(ProtectedAdministrationDescriptor descriptor, Guid id, long version) => - !descriptor.UsesCustomFieldFingerprint ? BodyFor(version) : Encoding.UTF8.GetBytes(descriptor.IsConsent + descriptor.IsDataRequestCreation ? Encoding.UTF8.GetBytes("{\"id\":\"" + id.ToString("D") + + "\",\"kind\":\"export\",\"status\":\"requested\",\"version\":\"" + version.ToString(CultureInfo.InvariantCulture) + "\"}") + : !descriptor.UsesCustomFieldFingerprint ? BodyFor(version) : Encoding.UTF8.GetBytes(descriptor.IsConsent ? "{\"evidenceId\":\"" + id.ToString("D") + "\",\"sequence\":\"" + version.ToString(CultureInfo.InvariantCulture) + "\",\"isGranted\":" + (descriptor.Operation == ProtectedAdministrationOperation.GrantOwnFieldConsent ? "true" : "false") + "}" : "{\"id\":\"" + id.ToString("D") + "\",\"version\":\"" + version.ToString(CultureInfo.InvariantCulture) + "\"}"); @@ -132,7 +148,7 @@ public async Task ExecuteResultAsync(ActionContext context) { ArgumentNullException.ThrowIfNull(context); var response = context.HttpContext.Response; - response.StatusCode = Descriptor.Creates ? StatusCodes.Status201Created : StatusCodes.Status200OK; + response.StatusCode = Descriptor.SuccessStatus; response.ContentType = "application/json; charset=utf-8"; if (!Descriptor.IsConsent) response.Headers.ETag = EntityTag.For(Version); if (Descriptor.Creates) response.Headers.Location = Descriptor.LocationFor(Target.Id); diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs index 2d7bd56e..9df5cd54 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs @@ -271,7 +271,7 @@ internal static bool ValidStoredResponse(IdempotentResponse stored, ProtectedAdm if (stored.Body is null || stored.Headers is null || stored.ReplayTarget is not { } target || target.Kind != descriptor.TargetKind || target.Id == Guid.Empty || target.Id.Version != 7 || target.Kind == IdempotencyReplayTargetKind.Tenant && target.Id != tenant.Value - || stored.StatusCode != (descriptor.Creates ? StatusCodes.Status201Created : StatusCodes.Status200OK) + || stored.StatusCode != descriptor.SuccessStatus || stored.ContentType != "application/json; charset=utf-8" || stored.Body.Length > MaxReceiptBytes || !stored.Body.AsSpan().SequenceEqual(ProtectedAdministrationResult.BodyFor(descriptor, target.Id, version))) return false; if (descriptor.Creates ? !TryHeader(stored, "Location", out var location) diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs index ac5520a2..505015b9 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs @@ -6,6 +6,7 @@ using LearnStack.Modules.Tenancy.Application.Contracts.Settings; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Idempotency; using LearnStack.SharedKernel.Identifiers; @@ -46,6 +47,10 @@ or ProtectedAdministrationOperation.PublishCustomFieldRevision or ProtectedAdmin ProtectedAdministrationOperation.WithdrawOwnFieldConsent when http?.Features.Get()?.Request is ReadOwnWithdrawnFieldConsentReceiptQuery request && request.EvidenceId == target.Id => sender.Send(request, cancellationToken), ProtectedAdministrationOperation.WithdrawOwnFieldConsent => Task.FromResult(Result.Fail(new Error(LocalizedMessage.Of("lockey_forbidden")))), + ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CancelOwnDataRequest + or ProtectedAdministrationOperation.RevokeOwnDataExport => sender.Send(new ReadOwnDataRequestReceiptQuery(target.Id), cancellationToken), + ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CancelDataRequest + or ProtectedAdministrationOperation.RevokeDataExport => sender.Send(new ReadDataRequestReceiptQuery(target.Id), cancellationToken), _ => throw new ArgumentOutOfRangeException(nameof(descriptor)), }; } diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs index b6c4ed49..90e35ec8 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs @@ -7,6 +7,7 @@ using LearnStack.Application.Authorization; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Idempotency; using LearnStack.SharedKernel.Identifiers; @@ -139,6 +140,10 @@ or ProtectedAdministrationOperation.PublishCustomFieldRevision or ProtectedAdmin or ProtectedAdministrationOperation.DiscardCustomFieldDraft => typeof(ReadCustomFieldDefinitionReceiptQuery), ProtectedAdministrationOperation.GrantOwnFieldConsent => typeof(ReadOwnGrantedFieldConsentReceiptQuery), ProtectedAdministrationOperation.WithdrawOwnFieldConsent => typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), + ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CancelOwnDataRequest + or ProtectedAdministrationOperation.RevokeOwnDataExport => typeof(ReadOwnDataRequestReceiptQuery), + ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CancelDataRequest + or ProtectedAdministrationOperation.RevokeDataExport => typeof(ReadDataRequestReceiptQuery), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; diff --git a/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs new file mode 100644 index 00000000..cd1434f1 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs @@ -0,0 +1,309 @@ +using System.Text.Json.Nodes; +using LearnStack.Api.Authentication; +using LearnStack.Api.Idempotency; +using LearnStack.Api.PublicReads; +using LearnStack.SharedKernel.DataProtection; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; + +namespace LearnStack.Api.Identity; + +/// +/// The exact wire contract of the live-session data-request API (ADR-0106 § 10, ADR-0107 § 4): the subject's own +/// requests, their artifact and its ticketed download under identity/me/data-requests, and the administrator's +/// status-only view under identity/data-requests. Request bodies are read without MVC binding. +/// +internal sealed class DataRequestDocumentTransformer : IOpenApiDocumentTransformer +{ + private enum Shape { Read, Page, Create, Mutation, Ticket, Chunk } + + private static readonly string[] SuccessStatuses = ["200", "201", "202"]; + + private sealed record Contract(string Path, HttpMethod Method, string Name, Shape Shape, string Response, string? Body, bool Own); + + private static readonly Contract[] Contracts = + [ + new("identity/me/data-requests/exports", HttpMethod.Post, "CreateOwnDataExport", Shape.Create, "DataRequestAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/me/data-requests", HttpMethod.Get, "ListOwnDataRequests", Shape.Page, "OwnDataRequestPage", null, true), + new("identity/me/data-requests/{id}", HttpMethod.Get, "GetOwnDataRequest", Shape.Read, "OwnDataRequestResponse", null, true), + new("identity/me/data-requests/{id}/cancellations", HttpMethod.Post, "CancelOwnDataRequest", Shape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput", true), + new("identity/me/data-requests/{id}/artifact/revocations", HttpMethod.Post, "RevokeOwnDataExport", Shape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput", true), + new("identity/me/data-requests/{id}/artifact/tickets", HttpMethod.Post, "MintOwnDataExportTicket", Shape.Ticket, "DataExportTicketResponse", "EmptyAdministrationInput", true), + new("identity/me/data-requests/{id}/artifact/chunks", HttpMethod.Post, "ReadOwnDataExportChunk", Shape.Chunk, "DataExportChunkResponse", "DataExportChunkInput", true), + new("identity/data-requests/exports", HttpMethod.Post, "CreateDataExportForSubject", Shape.Create, "DataRequestAcceptedResponse", "DataExportForSubjectInput", false), + new("identity/data-requests", HttpMethod.Get, "ListDataRequests", Shape.Page, "DataRequestPage", null, false), + new("identity/data-requests/{id}", HttpMethod.Get, "GetDataRequest", Shape.Read, "DataRequestResponse", null, false), + new("identity/data-requests/{id}/cancellations", HttpMethod.Post, "CancelDataRequest", Shape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput", false), + new("identity/data-requests/{id}/artifact/revocations", HttpMethod.Post, "RevokeDataExport", Shape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput", false), + ]; + + public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(document); + if (context.DocumentName != "v1" || !document.Paths.ContainsKey("/api/v1/identity/me/data-requests")) return Task.CompletedTask; + document.Components ??= new(); + document.Components.Schemas ??= new Dictionary(); + Schemas(document); + foreach (var contract in Contracts) + { + if (!document.Paths.TryGetValue("/api/v1/" + contract.Path, out var path) + || path.Operations?.TryGetValue(contract.Method, out var operation) != true || operation is null) continue; + Describe(document, path, operation, contract); + } + return Task.CompletedTask; + } + + private static void Describe(OpenApiDocument document, IOpenApiPathItem path, OpenApiOperation operation, Contract contract) + { + operation.OperationId = contract.Name; + operation.Security = [new OpenApiSecurityRequirement { [new OpenApiSecuritySchemeReference(TenantAuthenticationRegistration.Scheme, document)] = [] }]; + operation.Description = Description(contract); + operation.Parameters = []; + if (contract.Path.Contains("{id}", StringComparison.Ordinal)) operation.Parameters.Add(new OpenApiParameter + { + Name = "id", + In = ParameterLocation.Path, + Required = true, + Schema = Uuid(), + Description = "Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent.", + }); + if (contract.Shape == Shape.Page) + { + operation.Parameters.Add(new OpenApiParameter + { + Name = "cursor", + In = ParameterLocation.Query, + Schema = new OpenApiSchema { Type = JsonSchemaType.String, MinLength = 1, MaxLength = 1024 }, + Description = "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + }); + operation.Parameters.Add(new OpenApiParameter + { + Name = "limit", + In = ParameterLocation.Query, + Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = "2147483647", Default = JsonValue.Create(20) }, + Description = "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + }); + } + if (contract.Body is not null) + { + operation.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary { ["application/json"] = new() { Schema = Ref(document, contract.Body) } }, + }; + if (contract.Shape is Shape.Create or Shape.Mutation) operation.Parameters.Add(new OpenApiParameter + { + Name = IdempotentAttribute.HeaderName, + In = ParameterLocation.Header, + Required = true, + Schema = new OpenApiSchema { Type = JsonSchemaType.String, MinLength = 8, MaxLength = 128, Pattern = "^[!-~]{8,128}$" }, + Description = "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + }); + if (contract.Shape == Shape.Mutation) operation.Parameters.Add(new OpenApiParameter + { + Name = "If-Match", + In = ParameterLocation.Header, + Required = true, + Schema = EntityTag(), + Description = contract.Name.StartsWith("Revoke", StringComparison.Ordinal) + ? "One canonical strong quoted decimal artifact version (the receipt's artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409." + : "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + }); + } + else operation.RequestBody = null; + + operation.Responses ??= []; + var status = contract.Shape == Shape.Create ? "202" : "200"; + foreach (var other in SuccessStatuses.Where(code => code != status)) operation.Responses.Remove(other); + operation.Responses[status] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create => "Accepted: the request's initial resource. Its export runs as a background job; read the Location for its status.", + Shape.Ticket => "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", + Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + Shape.Mutation => "Committed receipt, or the retained receipt of a completed exact-key replay.", + _ => "Current receipt-safe projection: status and counts, never content.", + }, + Content = new Dictionary { ["application/json"] = new() { Schema = Ref(document, contract.Response) } }, + }; + var methods = string.Join(", ", path.Operations!.Keys.Select(method => method.Method).Order(StringComparer.Ordinal)); + PublicReadDocumentTransformer.DocumentResponses(document, operation, contract.Method, + [ + ("400", "validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation."), + ("401", "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge."), + ("403", contract.Own ? "forbidden when the request carries no live session the ticket can bind." + : "forbidden without current identity.membership.admin covering the context's group."), + ("404", contract.Own ? "not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike." + : "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke)."), + ("405", "method_not_allowed after earlier host, credential and scope gates."), + ("413", "payload_too_large; request bodies are at most 16 KiB."), + ("429", "rate_limited by the existing visitor/subject admission."), + ("500", "internal_error without provider, query, identity, ticket or submitted-value diagnostics."), + ("503", "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row."), + ], methods); + if (contract.Body is not null) operation.Responses["409"] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create => "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + Shape.Ticket => "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + Shape.Chunk => "Never: a chunk refusal is not_found.", + _ => "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + }, + Headers = new Dictionary { ["Cache-Control"] = new OpenApiHeader { Required = true, Schema = Enum("no-store") } }, + Content = new Dictionary { ["application/problem+json"] = new() { Schema = Ref(document, "ProblemDetails") } }, + }; + if (contract.Shape == Shape.Chunk) operation.Responses.Remove("409"); + if (operation.Responses["503"] is OpenApiResponse unavailable) unavailable.Headers?.Remove("Retry-After"); + if (operation.Responses[status] is not OpenApiResponse success) return; + success.Headers ??= new Dictionary(); + if (contract.Shape is Shape.Read or Shape.Create or Shape.Mutation) success.Headers["ETag"] = new OpenApiHeader + { + Required = true, + Schema = EntityTag(), + Description = contract.Name.StartsWith("Revoke", StringComparison.Ordinal) ? "The artifact's version after the revocation." : "The request's version.", + }; + if (contract.Shape is Shape.Create or Shape.Mutation) success.Headers[IdempotentAttribute.ReplayedHeaderName] = new OpenApiHeader + { + Required = false, + Schema = Enum("true"), + Description = "Present only after fresh original-request disclosure on a replay.", + }; + if (contract.Shape == Shape.Create) success.Headers["Location"] = new OpenApiHeader + { + Required = true, + Schema = new OpenApiSchema + { + Type = JsonSchemaType.String, + Pattern = "^/api/v1/identity/" + (contract.Own ? "me/data-requests" : "data-requests") + + "/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + }, + Description = "Exact same-API relative location of the new request's receipt.", + }; + } + + private static string Description(Contract contract) => contract.Shape switch + { + Shape.Create when contract.Own => "The subject files an export of their own data in the session's group (ADR-0106 § 3). Requires an Active Membership in exactly that group; no permission key. The request holds the frozen snapshot of the subject's Memberships of any status in the group and its job is submitted on the same transaction. Strict empty JSON object. MUST audited.", + Shape.Create => "An administrator holding identity.membership.admin over the group files an export for the person who holds or held the named Membership, of any status, in the group; never for themselves. The administrator sees status and counts only and never receives the bundle. Strict JSON object with membershipId only. MUST audited.", + Shape.Page when contract.Own => "The subject's own requests in the session's group, newest first. A request whose job died is shown failed. Audit Off. No request body.", + Shape.Page => "The group's export and erasure requests, newest first: status and counts only, never content, never a closure. MUST read-sensitive audited; refused when the row cannot be written. No request body.", + Shape.Read when contract.Own => "The subject's own request receipt: identity, kind, origin, status, timestamps, the recorded refusal or failure code, the closed retained-reference kinds and counts and the artifact's metadata. No content. Audit Off. No request body.", + Shape.Read => "One request of the group: status and counts only, never content. MUST read-sensitive audited; refused when the row cannot be written. No request body.", + Shape.Mutation when contract.Name.StartsWith("Cancel", StringComparison.Ordinal) => contract.Own + ? "The subject cancels a requested export (requested to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited." + : "The administrator who filed an export cancels it while it is still requested. Strict empty JSON object. MUST audited.", + Shape.Mutation => contract.Own + ? "The subject revokes an unexpired available artifact of a request about them, which deletes its chunks at once; the metadata stays as the receipt. Strict empty JSON object. MUST audited." + : "The administrator who filed an export revokes its unexpired available artifact, which deletes its chunks at once. Strict empty JSON object. MUST audited.", + Shape.Ticket => "The subject mints a fifteen-minute download cursor over their own available, unexpired artifact, bound to the credential of this session; an administrator never gets one. Stored only as a digest; not keyed and never replayed; no If-Match. Strict empty JSON object. MUST read-sensitive audited; refused when the row cannot be written.", + _ => "Reads one decrypted chunk through a ticket presented in the body, never the URL, in the session that minted it. Any index below count may be read while the ticket is unconsumed and unexpired; serving the final chunk (count - 1) consumes it, and a resumed download mints a new ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written.", + }; + + private static void Schemas(OpenApiDocument document) + { + var schemas = document.Components!.Schemas!; + schemas.TryAdd("ProblemDetails", PublicReadDocumentTransformer.Problem()); + schemas.TryAdd("EmptyAdministrationInput", Object()); + schemas.TryAdd("PageInfo", Object(("nextCursor", Text(true)), ("previousCursor", Text(true)), + ("hasNext", new OpenApiSchema { Type = JsonSchemaType.Boolean }), ("hasPrevious", new OpenApiSchema { Type = JsonSchemaType.Boolean }))); + schemas.TryAdd("AdministrationVersionReceipt", Object(("version", Version()))); + var kind = Enum([.. DataRequestCodes.Kinds.Codes]); + var status = Enum([.. DataRequestCodes.Statuses.Codes]); + var origin = Enum([.. DataRequestCodes.Origins.Codes]); + schemas["DataRequestAcceptedResponse"] = Object(("id", Uuid()), ("kind", Enum("export")), ("status", Enum("requested")), ("version", Version())); + schemas["DataRequestRetainedResponse"] = Object(("kind", Enum([.. DataRequestCodes.RetainedKinds.Codes])), + ("count", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int64", Minimum = "0" })); + schemas["DataExportTruncationResponse"] = Object(("collection", Text(false, 65)), ("included", Count()), ("total", Count())); + schemas["DataExportArtifactResponse"] = Object(("id", Uuid()), ("status", Enum([.. DataRequestCodes.ArtifactStatuses.Codes])), + ("expiresAt", DateTime()), ("purgedAt", DateTime(true)), + ("byteCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int64", Minimum = "1", Maximum = DataRequestLimits.MaximumBundleBytes.ToString(System.Globalization.CultureInfo.InvariantCulture) }), + ("chunkCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = DataRequestLimits.MaximumChunkCount.ToString(System.Globalization.CultureInfo.InvariantCulture) }), + ("truncations", Array(Ref(document, "DataExportTruncationResponse"), DataRequestLimits.MaximumTruncatedCollections)), + ("version", Version()), ("readable", new OpenApiSchema { Type = JsonSchemaType.Boolean })); + (string, IOpenApiSchema)[] receipt = + [ + ("id", Uuid()), ("kind", kind), ("origin", origin), ("status", status), ("createdAt", DateTime()), ("updatedAt", DateTime(true)), + ("completedAt", DateTime(true)), ("lastRefusal", Nullable(Enum([.. DataRequestCodes.Refusals.Codes]))), + ("failureReason", Nullable(Enum([.. DataRequestCodes.FailureReasons.Codes]))), + ("retained", Array(Ref(document, "DataRequestRetainedResponse"), DataRequestCodes.RetainedKinds.Codes.Length)), + ("artifact", NullableRef(document, "DataExportArtifactResponse")), ("version", Version()), + ]; + schemas["OwnDataRequestResponse"] = Object(receipt); + schemas["OwnDataRequestPage"] = Object(("items", Array(Ref(document, "OwnDataRequestResponse"), 100)), ("pageInfo", Ref(document, "PageInfo"))); + schemas["DataRequestResponse"] = Object([.. receipt, ("requestedByYou", new OpenApiSchema { Type = JsonSchemaType.Boolean }), + ("membershipIds", Array(Uuid(), DataRequestLimits.MaximumSnapshotMemberships))]); + schemas["DataRequestPage"] = Object(("items", Array(Ref(document, "DataRequestResponse"), 100)), ("pageInfo", Ref(document, "PageInfo"))); + schemas["DataExportForSubjectInput"] = Object(("membershipId", Uuid())); + schemas["DataExportTicketResponse"] = Object(("ticket", Ticket()), ("expiresAt", DateTime()), + ("chunkCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = DataRequestLimits.MaximumChunkCount.ToString(System.Globalization.CultureInfo.InvariantCulture) }), + ("byteCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int64", Minimum = "1", Maximum = DataRequestLimits.MaximumBundleBytes.ToString(System.Globalization.CultureInfo.InvariantCulture) })); + schemas["DataExportChunkInput"] = Object(("ticket", Ticket()), + ("index", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "0", Maximum = (DataRequestLimits.MaximumChunkCount - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) })); + schemas["DataExportChunkResponse"] = Object( + ("index", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "0" }), + ("count", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1" }), + ("bytes", new OpenApiSchema + { + Type = JsonSchemaType.String, + ContentEncoding = "base64", + MinLength = 4, + MaxLength = 174764, + Description = "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk in index order yields the bundle." + })); + } + + private static OpenApiSchema Ticket() => new() + { + Type = JsonSchemaType.String, + MinLength = 43, + MaxLength = 43, + Pattern = "^[A-Za-z0-9_-]{43}$", + Description = "Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log.", + }; + + private static OpenApiSchemaReference Ref(OpenApiDocument document, string name) => new(name, document); + private static OpenApiSchema NullableRef(OpenApiDocument document, string name) => + new() { OneOf = [Ref(document, name), new OpenApiSchema { Type = JsonSchemaType.Null }] }; + + private static OpenApiSchema Nullable(OpenApiSchema schema) + { + schema.Type |= JsonSchemaType.Null; + schema.Enum?.Add(null!); + return schema; + } + + private static OpenApiSchema Object(params (string Name, IOpenApiSchema Schema)[] fields) => new() + { + Type = JsonSchemaType.Object, + AdditionalPropertiesAllowed = false, + Required = fields.Select(field => field.Name).ToHashSet(StringComparer.Ordinal), + Properties = fields.ToDictionary(field => field.Name, field => field.Schema, StringComparer.Ordinal), + }; + + private static OpenApiSchema Array(IOpenApiSchema item, int maximum) => new() { Type = JsonSchemaType.Array, Items = item, MaxItems = maximum }; + private static OpenApiSchema Count() => new() { Type = JsonSchemaType.Integer, Format = "int64", Minimum = "0", Maximum = "9007199254740991" }; + private static OpenApiSchema Text(bool nullable = false, int? maximum = null) => new() + { Type = nullable ? JsonSchemaType.String | JsonSchemaType.Null : JsonSchemaType.String, MaxLength = maximum }; + private static OpenApiSchema Uuid() => new() + { + Type = JsonSchemaType.String, + Format = "uuid", + Pattern = "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + }; + private static OpenApiSchema Version() => new() + { + Type = JsonSchemaType.String, + MinLength = 1, + MaxLength = 19, + Pattern = "^(0|[1-9][0-9]{0,18})$", + Description = "Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number.", + }; + private static OpenApiSchema DateTime(bool nullable = false) => new() + { Type = nullable ? JsonSchemaType.String | JsonSchemaType.Null : JsonSchemaType.String, Format = "date-time" }; + private static OpenApiSchema EntityTag() => new() + { Type = JsonSchemaType.String, MinLength = 3, MaxLength = 21, Pattern = "^\"(0|[1-9][0-9]{0,18})\"$" }; + private static OpenApiSchema Enum(params string[] values) => new() + { Type = JsonSchemaType.String, Enum = values.Select(value => (JsonNode)JsonValue.Create(value)!).ToList() }; +} diff --git a/backend/src/LearnStack.Api/Identity/DataRequestResponses.cs b/backend/src/LearnStack.Api/Identity/DataRequestResponses.cs new file mode 100644 index 00000000..3b6c771a --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestResponses.cs @@ -0,0 +1,87 @@ +using System.Globalization; +using LearnStack.Api.Common; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Pagination; + +namespace LearnStack.Api.Identity; + +/// The 202 answer to a data-request creation: the request's initial resource (ADR-0106 § 10). +public sealed record DataRequestAcceptedResponse(string Id, string Kind, string Status, string Version); + +public sealed record DataRequestRetainedResponse(string Kind, long Count); + +public sealed record DataExportTruncationResponse(string Collection, long Included, long Total); + +/// An artifact's receipt-safe metadata: no content, no key and no key version. +public sealed record DataExportArtifactResponse(string Id, string Status, string ExpiresAt, string? PurgedAt, long ByteCount, + int ChunkCount, IReadOnlyList Truncations, string Version, bool Readable); + +/// The subject's own request receipt (ADR-0106 § 9): no personal data and no internal identifier but the request's. +public sealed record OwnDataRequestResponse(string Id, string Kind, string Origin, string Status, string CreatedAt, string? UpdatedAt, + string? CompletedAt, string? LastRefusal, string? FailureReason, IReadOnlyList Retained, + DataExportArtifactResponse? Artifact, string Version); + +public sealed record OwnDataRequestPage(IReadOnlyList Items, PageInfo PageInfo); + +/// +/// An administrator's view of a request of the group (ADR-0106 § 6, § 13): status and counts only, never content; the +/// frozen Membership identifiers name the subject in the vocabulary the administrator already reads. +/// +public sealed record DataRequestResponse(string Id, string Kind, string Origin, string Status, string CreatedAt, string? UpdatedAt, + string? CompletedAt, string? LastRefusal, string? FailureReason, IReadOnlyList Retained, + DataExportArtifactResponse? Artifact, string Version, bool RequestedByYou, IReadOnlyList MembershipIds); + +public sealed record DataRequestPage(IReadOnlyList Items, PageInfo PageInfo); + +/// A minted download cursor (ADR-0107 § 4). The ticket is returned once and never stored, logged or replayed. +public sealed record DataExportTicketResponse +{ + public DataExportTicketResponse(string ticket, string expiresAt, int chunkCount, long byteCount) + { + Ticket = ticket; + ExpiresAt = expiresAt; + ChunkCount = chunkCount; + ByteCount = byteCount; + } + + [PiiSensitive] + public string Ticket { get; } + + public string ExpiresAt { get; } + public int ChunkCount { get; } + public long ByteCount { get; } + + public override string ToString() => nameof(DataExportTicketResponse); +} + +/// The wire shape of one chunk: index, count and base64 bytes of at most 128 KiB of plaintext. +public sealed record DataExportChunkResponse(int Index, int Count, [property: PiiSensitive] string Bytes) +{ + public override string ToString() => nameof(DataExportChunkResponse); +} + +internal static class DataRequestProjection +{ + internal static OwnDataRequestResponse Own(DataRequestView view) => new(view.RequestId.ToString("D"), view.Kind, view.Origin, + view.Status, Instant(view.CreatedAt), Instant(view.UpdatedAt), Instant(view.CompletedAt), view.LastRefusal, view.FailureReason, + Retained(view), Artifact(view.Artifact), AdministrationHttpInput.Version(view.Version)); + + internal static DataRequestResponse Administration(DataRequestView view) => new(view.RequestId.ToString("D"), view.Kind, + view.Origin, view.Status, Instant(view.CreatedAt), Instant(view.UpdatedAt), Instant(view.CompletedAt), view.LastRefusal, + view.FailureReason, Retained(view), Artifact(view.Artifact), AdministrationHttpInput.Version(view.Version), view.RequestedByCaller, + (view.MembershipIds ?? throw new InvalidOperationException("An administrator view names its Membership snapshot.")) + .Select(id => id.ToString("D")).ToArray()); + + private static DataRequestRetainedResponse[] Retained(DataRequestView view) => + view.Retained.Select(item => new DataRequestRetainedResponse(item.Kind, item.Count)).ToArray(); + + private static DataExportArtifactResponse? Artifact(DataExportArtifactView? artifact) => artifact is null ? null + : new(artifact.ArtifactId.ToString("D"), artifact.Status, Instant(artifact.ExpiresAt), Instant(artifact.PurgedAt), artifact.ByteCount, + artifact.ChunkCount, artifact.Truncations.Select(item => new DataExportTruncationResponse(item.Collection, item.Included, item.Total)).ToArray(), + AdministrationHttpInput.Version(artifact.Version), artifact.Readable); + + internal static string Instant(DateTimeOffset value) => value.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture); + + private static string? Instant(DateTimeOffset? value) => value is { } instant ? Instant(instant) : null; +} diff --git a/backend/src/LearnStack.Api/Identity/DataRequestsController.cs b/backend/src/LearnStack.Api/Identity/DataRequestsController.cs new file mode 100644 index 00000000..3e0471f3 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestsController.cs @@ -0,0 +1,265 @@ +using System.Security.Cryptography; +using System.Text.Json; +using LearnStack.Api.Authentication; +using LearnStack.Api.Common; +using LearnStack.Api.Idempotency; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace LearnStack.Api.Identity; + +/// +/// The subject's own data requests through a live session (ADR-0106 § 3, § 9; ADR-0107 § 4): key-less +/// OwnDataRequest operations confined to the session's group. The ticket and the chunk travel only in request +/// and response bodies, never in a URL, and neither is keyed, so no secret reaches an idempotency receipt. +/// +[Route("identity/me/data-requests")] +public sealed class OwnDataRequestsController(ISender sender, ITenantContext tenant) : ApiControllerBase +{ + [HttpPost("exports", Name = "CreateOwnDataExport")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataExportCreateOperation)] + [OperationPolicy(typeof(CreateOwnDataExportCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateOwnDataExport)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task Create(CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null) return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, new CreateOwnDataExportCommand(), cancellationToken); + } + + [HttpGet(Name = "ListOwnDataRequests")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataRequestListOperation)] + [OperationPolicy(typeof(ListOwnDataRequestsQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task List(CancellationToken cancellationToken) + { + if (!AdministrationHttpInput.TryPage(Request, out var cursor, out var limit) + || !await AdministrationHttpInput.ReadHasNoBodyAsync(HttpContext)) return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new ListOwnDataRequestsQuery(cursor, limit), cancellationToken); + return result.IsFailure ? result.ToActionResult() + : Ok(new OwnDataRequestPage(result.Value.Items.Select(DataRequestProjection.Own).ToArray(), result.Value.PageInfo)); + } + + [HttpGet("{id}", Name = "GetOwnDataRequest")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataRequestReadOperation)] + [OperationPolicy(typeof(GetOwnDataRequestQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Get(string id, CancellationToken cancellationToken) + { + if (!AdministrationHttpInput.TryId(id, out var target) || Request.Query.Count != 0 + || !await AdministrationHttpInput.ReadHasNoBodyAsync(HttpContext)) return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new GetOwnDataRequestQuery(target), cancellationToken); + if (result.IsFailure) return result.ToActionResult(); + Response.Headers.ETag = EntityTag.For(result.Value.Version); + return Ok(DataRequestProjection.Own(result.Value)); + } + + [HttpPost("{id}/cancellations", Name = "CancelOwnDataRequest")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataRequestCancelOperation)] + [OperationPolicy(typeof(CancelOwnDataRequestCommand))] + [Idempotent(ProtectedAdministrationOperation.CancelOwnDataRequest)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Cancel(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || !ProtectedEntityTag.TryRead(Request, out var version)) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, + new CancelOwnDataRequestCommand(target, version), cancellationToken); + } + + [HttpPost("{id}/artifact/revocations", Name = "RevokeOwnDataExport")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataExportRevokeOperation)] + [OperationPolicy(typeof(RevokeOwnDataExportCommand))] + [Idempotent(ProtectedAdministrationOperation.RevokeOwnDataExport)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Revoke(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || !ProtectedEntityTag.TryRead(Request, out var version)) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, + new RevokeOwnDataExportCommand(target, version), cancellationToken); + } +} + +/// +/// ADR-0107 § 4: the subject mints a download cursor over their own available artifact. Not keyed and not conditional: +/// the answer carries a secret that is returned once and never retained for a replay. +/// +[Route("identity/me/data-requests")] +public sealed class OwnDataExportTicketsController(ISender sender) : ApiControllerBase +{ + [HttpPost("{id}/artifact/tickets", Name = "MintOwnDataExportTicket")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataExportTicketOperation)] + [OperationPolicy(typeof(MintOwnDataExportTicketCommand))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task MintTicket(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || DataExportDownloadInput.HasPrecondition(Request)) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new MintOwnDataExportTicketCommand(target), cancellationToken); + return result.IsFailure ? result.ToActionResult() + : Ok(new DataExportTicketResponse(result.Value.Ticket, DataRequestProjection.Instant(result.Value.ExpiresAt), + result.Value.ChunkCount, result.Value.ByteCount)); + } +} + +/// +/// ADR-0107 § 4: one decrypted chunk through a ticket presented in the body, never in the URL. Not keyed and not +/// conditional; the plaintext buffer is cleared once written. +/// +[Route("identity/me/data-requests")] +public sealed class OwnDataExportChunksController(ISender sender) : ApiControllerBase +{ + [HttpPost("{id}/artifact/chunks", Name = "ReadOwnDataExportChunk")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataExportChunkOperation)] + [OperationPolicy(typeof(ReadOwnDataExportChunkCommand))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task ReadChunk(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext, "ticket", "index"); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || DataExportDownloadInput.HasPrecondition(Request) + || !AdministrationHttpInput.TryText(body.RootElement, "ticket", false, 64, out var ticket) + || body.RootElement.GetProperty("index") is not { ValueKind: JsonValueKind.Number } index + || !index.TryGetInt32(out var position) || position < 0 + || !string.Equals(index.GetRawText(), position.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal)) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new ReadOwnDataExportChunkCommand(target, ticket!, position), cancellationToken); + return result.IsFailure ? result.ToActionResult() : new DataExportChunkResult(result.Value); + } +} + +internal static class DataExportDownloadInput +{ + /// The ticket operations are not conditional and not keyed: a precondition or key on them is a client error. + internal static bool HasPrecondition(HttpRequest request) => + request.Headers.IfMatch.Count != 0 || request.Headers.IfNoneMatch.Count != 0 + || request.Headers.ContainsKey(IdempotentAttribute.HeaderName); +} + +/// +/// An administrator's data requests for the group (ADR-0106 § 3, § 6, § 13): Protected on the existing +/// identity.membership.admin alternatives. Status and counts only, never content, never a ticket. +/// +[Route("identity/data-requests")] +public sealed class DataRequestsController(ISender sender, ITenantContext tenant) : ApiControllerBase +{ + [HttpPost("exports", Name = "CreateDataExportForSubject")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataExportCreateOperation)] + [OperationPolicy(typeof(CreateDataExportForSubjectCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateDataExportForSubject)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task Create(CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext, "membershipId"); + if (body is null || !AdministrationHttpInput.TryText(body.RootElement, "membershipId", false, 36, out var text) + || !AdministrationHttpInput.TryId(text, out var membership)) return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, + new CreateDataExportForSubjectCommand(membership), cancellationToken); + } + + [HttpGet(Name = "ListDataRequests")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataRequestListOperation)] + [OperationPolicy(typeof(ListDataRequestsQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task List(CancellationToken cancellationToken) + { + if (!AdministrationHttpInput.TryPage(Request, out var cursor, out var limit) + || !await AdministrationHttpInput.ReadHasNoBodyAsync(HttpContext)) return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new ListDataRequestsQuery(cursor, limit), cancellationToken); + return result.IsFailure ? result.ToActionResult() + : Ok(new DataRequestPage(result.Value.Items.Select(DataRequestProjection.Administration).ToArray(), result.Value.PageInfo)); + } + + [HttpGet("{id}", Name = "GetDataRequest")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataRequestReadOperation)] + [OperationPolicy(typeof(GetDataRequestQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Get(string id, CancellationToken cancellationToken) + { + if (!AdministrationHttpInput.TryId(id, out var target) || Request.Query.Count != 0 + || !await AdministrationHttpInput.ReadHasNoBodyAsync(HttpContext)) return AdministrationHttpInput.Invalid(); + var result = await sender.Send(new GetDataRequestQuery(target), cancellationToken); + if (result.IsFailure) return result.ToActionResult(); + Response.Headers.ETag = EntityTag.For(result.Value.Version); + return Ok(DataRequestProjection.Administration(result.Value)); + } + + [HttpPost("{id}/cancellations", Name = "CancelDataRequest")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataRequestCancelOperation)] + [OperationPolicy(typeof(CancelDataRequestCommand))] + [Idempotent(ProtectedAdministrationOperation.CancelDataRequest)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Cancel(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || !ProtectedEntityTag.TryRead(Request, out var version)) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, + new CancelDataRequestCommand(target, version), cancellationToken); + } + + [HttpPost("{id}/artifact/revocations", Name = "RevokeDataExport")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataExportRevokeOperation)] + [OperationPolicy(typeof(RevokeDataExportCommand))] + [Idempotent(ProtectedAdministrationOperation.RevokeDataExport)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Revoke(string id, CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null || !AdministrationHttpInput.TryId(id, out var target) || !ProtectedEntityTag.TryRead(Request, out var version)) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, + new RevokeDataExportCommand(target, version), cancellationToken); + } +} + +/// +/// Writes one decrypted chunk as {index, count, bytes} straight from the plaintext buffer, then clears the +/// buffer (ADR-0107 § 4): the base64 is encoded into the response without an intermediate string, and the buffer is +/// zeroed whether or not the write completes. +/// +internal sealed class DataExportChunkResult(DataExportChunkView chunk) : IActionResult +{ + public async Task ExecuteResultAsync(ActionContext context) + { + ArgumentNullException.ThrowIfNull(context); + try + { + var response = context.HttpContext.Response; + response.StatusCode = StatusCodes.Status200OK; + response.ContentType = "application/json; charset=utf-8"; + response.Headers.CacheControl = "no-store"; + await using var writer = new Utf8JsonWriter(response.Body); + writer.WriteStartObject(); + writer.WriteNumber("index", chunk.Index); + writer.WriteNumber("count", chunk.Count); + writer.WriteBase64String("bytes", chunk.Bytes); + writer.WriteEndObject(); + await writer.FlushAsync(context.HttpContext.RequestAborted); + } + finally + { + CryptographicOperations.ZeroMemory(chunk.Bytes); + } + } +} diff --git a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs index 615ecf9d..02d91cc0 100644 --- a/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs +++ b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs @@ -131,6 +131,7 @@ public static IServiceCollection AddLearnStackOpenApiDocument( options.AddDocumentTransformer(new Identity.AdministrationDocumentTransformer()); options.AddDocumentTransformer(new Customization.CustomFieldDocumentTransformer()); options.AddDocumentTransformer(new Identity.FederationDocumentTransformer()); + options.AddDocumentTransformer(new Identity.DataRequestDocumentTransformer()); options.AddDocumentTransformer((document, _, _) => { diff --git a/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261122160000_add_data_request_protected_receipts.cs b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261122160000_add_data_request_protected_receipts.cs new file mode 100644 index 00000000..496d372a --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/Migrations/20261122160000_add_data_request_protected_receipts.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Infrastructure.Persistence.Migrations +{ + /// + /// ADR-0106 § 10: a keyed data-request creation, cancellation or artifact revocation retains its receipt against the + /// request it concerns, so the closed replay-target vocabulary gains DataSubjectRequest. Nothing else of the + /// constraint changes: a receipt still holds a bounded success body and no secret. + /// + [DbContext(typeof(PlatformDbContext))] + [Migration("20261122160000_add_data_request_protected_receipts")] + public partial class add_data_request_protected_receipts : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(""" + ALTER TABLE public.idempotency_keys DROP CONSTRAINT ck_idempotency_keys_replay_target; + ALTER TABLE public.idempotency_keys ADD CONSTRAINT ck_idempotency_keys_replay_target CHECK ( + (replay_target_kind IS NULL AND replay_target_id IS NULL) + OR (replay_target_kind IS NOT NULL AND replay_target_id IS NOT NULL + AND replay_target_kind IN ('Membership','Role','Organization','Tenant','Invitation','TenantSetting', + 'CustomFieldDefinition','MembershipFieldConsent','DataSubjectRequest') + AND replay_target_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND state = 'completed' AND status_code BETWEEN 200 AND 299 + AND body IS NOT NULL AND octet_length(body) <= 1024)); + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + throw new NotSupportedException("Retained data request receipts require a reviewed forward migration."); + } + } +} diff --git a/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs b/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs index c530827c..8c49969b 100644 --- a/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs +++ b/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs @@ -11,6 +11,7 @@ public enum IdempotencyReplayTargetKind TenantSetting, CustomFieldDefinition, MembershipFieldConsent, + DataSubjectRequest, } /// Internal immutable result metadata; it grants no disclosure authority. diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs new file mode 100644 index 00000000..343ab643 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs @@ -0,0 +1,153 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Idempotency; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Contracts.DataRequests; + +// The live-session data-request API of ADR-0106 and ADR-0107 § 4: one request type per operation and policy kind. +// The subject's own operations carry no permission key (OwnDataRequest); the administrator's are Protected on the +// existing identity.membership.admin alternatives. The retained-entry operations of ADR-0106 § 9 add thin request +// types of their own over the same handler cores. + +/// The receipt of a request mutation: the request and its version after the change. +public sealed record DataRequestMutationResult(Guid RequestId, long Version); + +/// The receipt of an artifact revocation: the request it belongs to and the artifact's version after it. +public sealed record DataExportArtifactMutationResult(Guid RequestId, Guid ArtifactId, long Version); + +/// One capped collection of a bundle: what the bundle states, never a value (ADR-0107 § 3). +public sealed record DataExportTruncationView(string Collection, long Included, long Total); + +/// One closed retained-reference kind and its count (ADR-0107 § 6); never a row identifier. +public sealed record DataRequestRetainedView(string Kind, long Count); + +/// +/// An export artifact's receipt-safe metadata: no plaintext, no ciphertext, no key and no key version. +/// is the time check against the database clock (ADR-0107 § 4). +/// +public sealed record DataExportArtifactView(Guid ArtifactId, string Status, DateTimeOffset ExpiresAt, DateTimeOffset? PurgedAt, + long ByteCount, int ChunkCount, IReadOnlyList Truncations, long Version, bool Readable); + +/// +/// A request's receipt (ADR-0106 § 9): identity, kind, origin, status, timestamps, the recorded refusal or failure +/// code, the closed retained-reference kinds and counts, and the artifact's metadata. No personal data, no bundle +/// content. is the frozen snapshot and is shown only to an administrator. +/// +public sealed record DataRequestView(Guid RequestId, string Kind, string Origin, string Status, DateTimeOffset CreatedAt, + DateTimeOffset? UpdatedAt, DateTimeOffset? CompletedAt, DateTimeOffset? ExecuteAt, string? LastRefusal, string? FailureReason, + IReadOnlyList Retained, DataExportArtifactView? Artifact, long Version, bool RequestedByCaller, + IReadOnlyList? MembershipIds); + +/// A minted download cursor: the opaque ticket, returned exactly once, and what it authorizes. +/// The ticket is a bearer value only together with the session it is bound to; it never prints. +public sealed record DataExportTicketGrant +{ + public DataExportTicketGrant(string ticket, DateTimeOffset expiresAt, int chunkCount, long byteCount) + { + Ticket = ticket; + ExpiresAt = expiresAt; + ChunkCount = chunkCount; + ByteCount = byteCount; + } + + [PiiSensitive] + public string Ticket { get; } + + public DateTimeOffset ExpiresAt { get; } + public int ChunkCount { get; } + public long ByteCount { get; } + + public override string ToString() => nameof(DataExportTicketGrant); +} + +/// +/// One decrypted chunk of a ticketed download (ADR-0107 § 4). The owner of the bytes clears them once they are +/// written; the type never prints them. +/// +public sealed record DataExportChunkView +{ + public DataExportChunkView(int index, int count, byte[] bytes) + { + Index = index; + Count = count; + Bytes = bytes; + } + + public int Index { get; } + public int Count { get; } + + [PiiSensitive] + public byte[] Bytes { get; } + + public override string ToString() => nameof(DataExportChunkView); +} + +// ---- The subject, through a live session (OperationPolicyKind.OwnDataRequest) ---- + +/// The person files an export of their own data in the session's group (ADR-0106 § 3). +public sealed record CreateOwnDataExportCommand : IRequest>; + +/// The person's own requests in the session's group, newest first. +public sealed record ListOwnDataRequestsQuery(string? Cursor = null, int Limit = 20) : IRequest>>; + +/// The person's own request receipt in the session's group. +public sealed record GetOwnDataRequestQuery(Guid RequestId) : IRequest>; + +/// requested → cancelled by the subject (ADR-0106 § 8, § 11). +public sealed record CancelOwnDataRequestCommand(Guid RequestId, long ExpectedVersion) : IRequest>; + +/// The subject revokes an unexpired export artifact of their own request, which purges it at once (ADR-0107 § 4). +public sealed record RevokeOwnDataExportCommand(Guid RequestId, long ExpectedArtifactVersion) + : IRequest>; + +/// Mints a fifteen-minute download cursor over the subject's available artifact (ADR-0107 § 4). +public sealed record MintOwnDataExportTicketCommand(Guid RequestId) : IRequest>; + +/// Reads one decrypted chunk through a ticket; the ticket travels only in a request body. +public sealed record ReadOwnDataExportChunkCommand : IRequest> +{ + public ReadOwnDataExportChunkCommand(Guid requestId, string ticket, int index) + { + RequestId = requestId; + Ticket = ticket; + Index = index; + } + + public Guid RequestId { get; } + + [PiiSensitive] + public string Ticket { get; } + + public int Index { get; } + + public override string ToString() => nameof(ReadOwnDataExportChunkCommand); +} + +/// Authorizes only disclosure of a stored receipt for the subject's own original request. +public sealed record ReadOwnDataRequestReceiptQuery(Guid RequestId) : IRequest>, IIdempotencyReceiptRead; + +// ---- An administrator of the group (Protected, identity.membership.admin at Tenant or Organization) ---- + +/// +/// A holder of identity.membership.admin covering the group files an export for the person who holds or held +/// the named Membership of any status in the group (ADR-0106 § 3); never for themselves. +/// +public sealed record CreateDataExportForSubjectCommand(Guid MembershipId) : IRequest>; + +/// The group's export and erasure requests: status and counts only, never content. +public sealed record ListDataRequestsQuery(string? Cursor = null, int Limit = 20) : IRequest>>; + +/// One request of the group: status and counts only, never content. +public sealed record GetDataRequestQuery(Guid RequestId) : IRequest>; + +/// requested → cancelled by the administrator who filed the request. +public sealed record CancelDataRequestCommand(Guid RequestId, long ExpectedVersion) : IRequest>; + +/// The administrator who filed an export revokes its unexpired artifact, which purges it at once. +public sealed record RevokeDataExportCommand(Guid RequestId, long ExpectedArtifactVersion) + : IRequest>; + +/// Authorizes only disclosure of a stored receipt for the administrator's original request. +public sealed record ReadDataRequestReceiptQuery(Guid RequestId) : IRequest>, IIdempotencyReceiptRead; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IDataExportSessionBinding.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IDataExportSessionBinding.cs new file mode 100644 index 00000000..14e14a26 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IDataExportSessionBinding.cs @@ -0,0 +1,34 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.Contracts.DataRequests; + +/// +/// The session a download ticket is bound to +/// (ADR-0107 § 4). +/// +/// +/// +/// The API sees no session identifier of its own: a live session reaches it as the stock-validated bearer credential +/// the BFF presents for that session. The binding is therefore a SHA-256 digest of that exact presented credential +/// together with the actor and the announced group, computed by the transport that validated it. A ticket minted in +/// one session is refused in another, and a ticket alone is not a bearer credential. A credential the BFF refreshes +/// mid-download ends that download's cursor; the resumed download mints a new ticket, as ADR-0107 § 4 requires anyway. +/// +/// +/// The default registration answers nothing, so outside the HTTP composition no ticket can be minted or used. +/// +/// +public interface IDataExportSessionBinding +{ + /// + /// The lower-case hex SHA-256 binding of the current request's validated credential for exactly this actor and + /// group, or when the current request carries none. + /// + string? Capture(UserId actor, TenantId tenant, OrganizationId? organization); +} + +/// The fail-closed default: no session, so no ticket is minted or honoured. +public sealed class UnavailableDataExportSessionBinding : IDataExportSessionBinding +{ + public string? Capture(UserId actor, TenantId tenant, OrganizationId? organization) => null; +} 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 546ef8e6..5b1df7e1 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.DataRequests; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Seeding; using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Memberships; @@ -45,6 +46,24 @@ public void Describe(IAuditCatalogBuilder builder) builder.MustAudit("identity.data_export.store", OperationType.SecurityEvent, typeof(DataExportArtifact)); builder.MustAudit("identity.data_export.purge", OperationType.Delete, typeof(DataExportArtifact)); builder.MustAudit("identity.data_export.purge", OperationType.Delete, typeof(DataExportArtifact)); + // ADR-0106 § 13, ADR-0107 § 4: every creation, cancellation and revocation is a MUST row about its aggregate; an + // administrator's read of the group's requests and every ticket mint and chunk read are MUST read-sensitive rows + // that refuse the disclosure when they cannot be written. The ticket rows name the ticket, whose digests the + // capture redacts; no row carries a ticket, plaintext or ciphertext. The subject's own reads are Off. + builder.MustAudit("identity.data_request.create_export", OperationType.Create, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.create_export", OperationType.Create, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.cancel", OperationType.Update, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.cancel", OperationType.Update, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_export.revoke", OperationType.Delete, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_export.revoke", OperationType.Delete, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_export.mint_ticket", OperationType.ReadSensitive, typeof(DataExportTicket)); + builder.MustAudit("identity.data_export.read_chunk", OperationType.ReadSensitive, typeof(DataExportTicket)); + builder.MustAudit("identity.data_request.list", OperationType.ReadSensitive, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.read", OperationType.ReadSensitive, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.read_receipt", OperationType.ReadSensitive, typeof(DataSubjectRequest)); + builder.Off(); + builder.Off(); + builder.Off(); builder.MustAudit(IdentityOperationPolicySource.NativeSessionAdmissionOperation, OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportDownloadService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportDownloadService.cs new file mode 100644 index 00000000..16d14dba --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportDownloadService.cs @@ -0,0 +1,163 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The ticketed download cores of ADR-0107 § 4: the subject mints a fifteen-minute cursor bound to the session and reads +/// the artifact's chunks through it. The one aggregate this executor writes is the , through +/// ; the artifact and its chunks are read through their own ports. +/// +/// +/// A ticket is returned once and stored only as its digest; a chunk's plaintext is handed to the transport, which clears it +/// once written. Neither reaches a log, an exception, an audit row or an idempotency receipt: neither operation is keyed, +/// and the audit capture redacts the ticket's digests. +/// +public sealed class DataExportDownloadService(IDataRequestReader reader, IDataExportTicketStore tickets, IDataExportArtifactStore artifacts, + IDataExportSessionBinding sessions, ITenantContext context, IAuditSubject audit, IGuidFactory ids, IClock clock) +{ + private DataRequestScopeGroup Group => new(context.TenantId, context.OrganizationId); + + /// + /// Mints a fifteen-minute download cursor bound to the session, over the subject's own readable artifact + /// (ADR-0107 § 4). Only the subject is ever served: an administrator who filed the export never gets a ticket. + /// + public async Task> MintTicketAsync(DataRequestCaller caller, Guid requestId, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (caller.Role != DataRequestRole.Subject) + { + return DataRequestService.Fail("lockey_forbidden"); + } + + var request = await DataRequestService.FindVisibleAsync(reader, caller, requestId, cancellationToken).ConfigureAwait(false); + var found = request is { Kind: DataRequestKind.Export } + ? await reader.FindArtifactLockedAsync(request.Id, cancellationToken).ConfigureAwait(false) + : null; + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result.Fail(current.Error); + } + + if (request is null || request.Kind != DataRequestKind.Export) + { + return DataRequestService.Fail("lockey_not_found"); + } + + if (found is null || !found.Readable || found.Artifact.SubjectUserId != caller.Actor) + { + return DataRequestService.Rule("artifact", "lockey_data_export_unavailable"); + } + + var binding = sessions.Capture(caller.Actor, context.TenantId, context.OrganizationId); + if (binding is null) + { + return DataRequestService.Fail("lockey_forbidden"); + } + + var (ticket, digest) = DataExportTicketCodec.Mint(); + var minted = DataExportTicket.Mint(DataExportTicketId.From(DataRequestService.NewId(ids)), found.Artifact, digest, binding, clock.UtcNow, caller.Actor); + if (minted.IsFailure) + { + return DataRequestService.Rule("artifact", "lockey_data_export_unavailable"); + } + + audit.Designate(minted.Value); + await tickets.AddAsync(minted.Value, cancellationToken).ConfigureAwait(false); + return Result.Ok(new DataExportTicketGrant(ticket, minted.Value.ExpiresAt, found.Artifact.ChunkCount, found.Artifact.ByteCount)); + } + + /// + /// Serves one decrypted chunk through a ticket (ADR-0107 § 4). The ticket is a download cursor: while it is unconsumed, + /// unexpired and presented in the session that minted it, it authorizes the reads of that artifact's chunks; serving + /// the final chunk (index count - 1) consumes it on the same transaction, after which every read through it is + /// refused and a resumed or repeated download mints a new ticket. Every refusal is the same not_found. + /// + public async Task> ReadChunkAsync(DataRequestCaller caller, Guid requestId, string ticket, int index, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + var digest = DataExportTicketCodec.TryDigest(ticket); + if (digest is null || index < 0 || !DataRequestService.ValidId(requestId)) + { + return DataRequestService.Fail("lockey_validation_failed"); + } + + if (caller.Role != DataRequestRole.Subject) + { + return DataRequestService.Fail("lockey_forbidden"); + } + + var request = await DataRequestService.FindVisibleAsync(reader, caller, requestId, cancellationToken).ConfigureAwait(false); + var artifact = request is { Kind: DataRequestKind.Export } + ? (await reader.ReadArtifactsAsync([request.Id], cancellationToken).ConfigureAwait(false)).GetValueOrDefault(request.Id) + : null; + var found = artifact is null ? null + : await tickets.FindLockedAsync(artifact.Artifact.Id, digest, cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result.Fail(current.Error); + } + + if (found is null) + { + return DataRequestService.Fail("lockey_not_found"); + } + + audit.Designate(found); + var binding = sessions.Capture(caller.Actor, context.TenantId, context.OrganizationId); + var now = clock.UtcNow; + if (binding is null || !found.Matches(digest, binding) || found.CreatedBy != caller.Actor || !found.IsUsable(now) + || !artifact!.Readable || index >= artifact.Artifact.ChunkCount) + { + return DataRequestService.Fail("lockey_not_found"); + } + + var chunk = await artifacts.ReadChunkAsync(new DataExportArtifactLocator(artifact.Artifact.Id.Value, Group), index, cancellationToken) + .ConfigureAwait(false); + if (chunk is null) + { + return DataRequestService.Fail("lockey_not_found"); + } + + var bytes = MemoryMarshal.TryGetArray(chunk.Bytes, out var segment) && segment.Offset == 0 && segment.Count == segment.Array!.Length + ? segment.Array : chunk.Bytes.ToArray(); + try + { + if (chunk.Index == chunk.Count - 1) + { + var consumed = found.Consume(now); + if (consumed.IsFailure) + { + CryptographicOperations.ZeroMemory(bytes); + return DataRequestService.Fail("lockey_not_found"); + } + + await tickets.UpdateAsync(found, cancellationToken).ConfigureAwait(false); + } + } + catch + { + CryptographicOperations.ZeroMemory(bytes); + throw; + } + + if (!ReferenceEquals(bytes, segment.Array) && segment.Array is { } source) + { + CryptographicOperations.ZeroMemory(source); + } + + return Result.Ok(new DataExportChunkView(chunk.Index, chunk.Count, bytes)); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs index 93feff96..2e25a075 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs @@ -159,7 +159,7 @@ private async Task StoreAsync(DataSubjectRequest request, IDataExportBundle bund throw new InvalidOperationException("The stored export artifact does not match its request."); } - await scheduler.SchedulePurgeAsync(DataExportArtifactId.From(artifactId), stored.ExpiresAt, cancellationToken) + await scheduler.SchedulePurgeAsync(artifactId, stored.ExpiresAt, cancellationToken) .ConfigureAwait(false); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTicketCodec.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTicketCodec.cs new file mode 100644 index 00000000..0a1da734 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTicketCodec.cs @@ -0,0 +1,80 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The opaque download ticket of ADR-0107 § 4: 32 random bytes, spelled as 43 unpadded base64url characters, and +/// stored only as a domain-separated SHA-256 digest. +/// +/// +/// Neither the ticket nor its bytes are kept after the response that returns it; the digest alone is stored, and the +/// session binding (IDataExportSessionBinding) is a second digest the ticket row also holds. +/// +public static class DataExportTicketCodec +{ + /// The ticket's entropy. + public const int TicketBytes = 32; + + /// The exact length of the wire spelling. + public const int TicketLength = 43; + + private static readonly byte[] Domain = Encoding.ASCII.GetBytes("learnstack.data_export.ticket.v1"); + + /// Mints a fresh ticket and its digest. The caller returns the ticket once and stores only the digest. + public static (string Ticket, string Digest) Mint() + { + Span secret = stackalloc byte[TicketBytes]; + try + { + RandomNumberGenerator.Fill(secret); + return (Encode(secret), Digest(secret)); + } + finally + { + CryptographicOperations.ZeroMemory(secret); + } + } + + /// The digest of a presented ticket, or when it is not a canonical ticket spelling. + public static string? TryDigest(string? ticket) + { + if (ticket is not { Length: TicketLength } + || ticket.Any(character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_'))) + { + return null; + } + + Span secret = stackalloc byte[TicketBytes]; + try + { + var padded = ticket.Replace('-', '+').Replace('_', '/') + "="; + if (!Convert.TryFromBase64String(padded, secret, out var written) || written != TicketBytes + || !string.Equals(Encode(secret), ticket, StringComparison.Ordinal)) + { + return null; + } + + return Digest(secret); + } + finally + { + CryptographicOperations.ZeroMemory(secret); + } + } + + private static string Encode(ReadOnlySpan secret) => + Convert.ToBase64String(secret).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static string Digest(ReadOnlySpan secret) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Span length = stackalloc byte[sizeof(int)]; + BinaryPrimitives.WriteInt32BigEndian(length, Domain.Length); + hash.AppendData(length); + hash.AppendData(Domain); + hash.AppendData(secret); + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestAuthorization.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestAuthorization.cs new file mode 100644 index 00000000..307ff9cf --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestAuthorization.cs @@ -0,0 +1,70 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The live-session data-request operations' own admission and fresh recheck +/// (ADR-0106 § 3–§ 4): +/// the subject's key-less operations and the administrator's +/// ones, each bound to the exact current invocation and re-evaluated +/// after the handler's fences, so authority lost while waiting refuses the act. +/// +/// +/// It confers nothing on its own: the policy decided coverage before the handler ran, and every handler still +/// confines its rows to the announced group and to the subject or requester it serves. +/// +public sealed class DataRequestAuthorization(IOperationInvocationContext invocations, IOperationPolicyCatalog catalog, + IProtectedOperationAuthorizer authorizer, ITenantContext context, IAuthorizationRefusalReporter refusals) +{ + internal async Task> AdmitAsync(object request, CancellationToken cancellationToken) + { + if (invocations.CurrentInvocation is not { } invocation || !Matches(request, invocation)) return Fail("lockey_forbidden"); + var check = await RecheckAsync(request, invocation, cancellationToken); + return check.IsFailure ? Result.Fail(check.Error) : Result.Ok(invocation); + } + + internal async Task> RecheckAsync(object request, OperationInvocation invocation, CancellationToken cancellationToken) + { + if (!Matches(request, invocation)) return Fail("lockey_forbidden"); + var decision = await authorizer.AuthorizeAsync(invocation, invocation.Policy, invocation.Candidate!, cancellationToken); + if (!Matches(request, invocation) || !decision.IsActive || !ReferenceEquals(decision.Invocation, invocation)) return Fail("lockey_dependency_unavailable"); + if (decision.Outcome == ProtectedOperationOutcome.Allowed) { refusals.ReportRecheck(decision); return Result.Ok(None.Value); } + if (decision.Outcome is ProtectedOperationOutcome.Forbidden or ProtectedOperationOutcome.NotCovered) + refusals.ReportResourceRefusal(decision, AuthorizationRefusalReason.Capability); + return Fail(decision.Outcome == ProtectedOperationOutcome.Forbidden ? "lockey_forbidden" + : decision.Outcome == ProtectedOperationOutcome.NotCovered ? "lockey_not_found" : "lockey_dependency_unavailable"); + } + + /// The administrator's request types; every other admitted type is the subject's own. + internal static bool IsAdministration(object request) => request is CreateDataExportForSubjectCommand or ListDataRequestsQuery + or GetDataRequestQuery or CancelDataRequestCommand or RevokeDataExportCommand or ReadDataRequestReceiptQuery; + + private static bool IsOwn(object request) => request is CreateOwnDataExportCommand or ListOwnDataRequestsQuery or GetOwnDataRequestQuery + or CancelOwnDataRequestCommand or RevokeOwnDataExportCommand or MintOwnDataExportTicketCommand + or ReadOwnDataExportChunkCommand or ReadOwnDataRequestReceiptQuery; + + private bool Matches(object request, OperationInvocation invocation) => + (IsAdministration(request) || IsOwn(request)) + && ReferenceEquals(invocations.CurrentInvocation, invocation) && invocation.IsActive + && invocation.EntryKind == OperationEntryKind.Application && invocation.TrustedSource is null + && ReferenceEquals(invocation.Operation, request) && ReferenceEquals(invocation.Context, context) + && catalog.TryGet(request.GetType(), out var policy) && ReferenceEquals(policy, invocation.Policy) + && (IsAdministration(request) + ? policy.Kind == OperationPolicyKind.Protected && policy.ReadScope == OperationReadScope.Scoped + && policy.Alternatives.All(clause => clause.ReadScope == OperationReadScope.Scoped) + : policy.Kind == OperationPolicyKind.OwnDataRequest) + && invocation.Candidate is { IsActive: true, SourceKind: AuthorizationSourceKind.Http } candidate + && context.IsResolved && context.TenantId != TenantId.PlatformSentinel && context.UserId is { } actor && actor != UserId.SystemActor + && context.Origin is TenantContextOrigin.HostAndClaim or TenantContextOrigin.ClaimAndMembership or TenantContextOrigin.HostAndNativeSessionScope + && candidate.Actor == actor && candidate.TenantId == context.TenantId && candidate.OrganizationId == context.OrganizationId + && invocation.Actor == actor && invocation.TenantId == context.TenantId && invocation.OrganizationId == context.OrganizationId + && invocations.CurrentDecision is { IsActive: true, Outcome: ProtectedOperationOutcome.Allowed } decision && ReferenceEquals(decision.Invocation, invocation); + + internal static Result Fail(string key) => Result.Fail(new Error(LocalizedMessage.Of(key))); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestCursorCodec.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestCursorCodec.cs new file mode 100644 index 00000000..dfa2d11e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestCursorCodec.cs @@ -0,0 +1,85 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The canonical seek cursor of a data-request page: the last request identifier of the previous page, bound to the +/// operation, the actor and the announced group. It carries no authority, secrecy or snapshot. +/// +/// +/// Requests are ordered newest first by their UUIDv7 identifier, which is time-ordered and unique, so the seek is +/// id < after. A cursor minted for another operation, actor or group is refused, never reinterpreted. +/// +public static class DataRequestCursorCodec +{ + public const int MaximumEncodedLength = 1024; + private const int MaximumDecodedLength = 768; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + private static readonly JsonDocumentOptions Options = new() { MaxDepth = 2 }; + + public static string Scope(string operation, UserId actor, TenantId tenant, OrganizationId? organization) => + Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new object?[] + { + 1, operation, actor.Value.ToString("D"), tenant.Value.ToString("D"), organization?.Value.ToString("D"), "request_id:desc", + }))); + + public static string Encode(string scope, Guid after) => Base64Url(JsonSerializer.SerializeToUtf8Bytes(new + { + v = 1, + scope, + id = after.ToString("D"), + })); + + public static bool TryDecode(string raw, string expectedScope, out Guid after) + { + after = Guid.Empty; + if (string.IsNullOrEmpty(raw) || raw.Length > MaximumEncodedLength + || raw.Any(character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_'))) + { + return false; + } + + try + { + var bytes = Convert.FromBase64String(raw.Replace('-', '+').Replace('_', '/') + new string('=', (4 - raw.Length % 4) % 4)); + if (bytes.Length > MaximumDecodedLength || Base64Url(bytes) != raw) + { + return false; + } + + using var document = JsonDocument.Parse(StrictUtf8.GetString(bytes), Options); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.EnumerateObject().Select(property => property.Name).SequenceEqual(["v", "scope", "id"]) + || root.GetProperty("v").ValueKind != JsonValueKind.Number || !root.GetProperty("v").TryGetInt32(out var version) + || version != 1 || root.GetProperty("scope").ValueKind != JsonValueKind.String + || root.GetProperty("id").ValueKind != JsonValueKind.String) + { + return false; + } + + var scope = root.GetProperty("scope").GetString()!; + var text = root.GetProperty("id").GetString()!; + if (!string.Equals(scope, expectedScope, StringComparison.Ordinal) + || !Guid.TryParseExact(text, "D", out var id) || id == Guid.Empty || id.Version != 7 + || !string.Equals(id.ToString("D"), text, StringComparison.Ordinal) + || !string.Equals(Encode(scope, id), raw, StringComparison.Ordinal)) + { + return false; + } + + after = id; + return true; + } + catch (Exception failure) when (failure is FormatException or JsonException or DecoderFallbackException + or InvalidOperationException) + { + return false; + } + } + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestEligibility.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestEligibility.cs new file mode 100644 index 00000000..8f410974 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestEligibility.cs @@ -0,0 +1,61 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// The default : structure only +/// (ADR-0106 § 7). +/// +/// +/// +/// What it judges. The subject holds a Membership of any status in the group (a Revoked tombstone counts); +/// at creation no non-terminal request of the same kind, subject and group exists, and at execution none but the +/// executing one; and the registered reports no hold. It reads on the caller's +/// announced group transaction as learnstack_app and confers no authority. +/// +/// +/// A dead job is reconciled by the caller, first. ADR-0106 § 8 reads failed from the job phase, but the +/// one-active index frees the slot only for a stored terminal status; the creation path locks the existing request +/// and stores its failure through under the fences it already holds before +/// it asks, so this judgment sees the stored outcome. The partial unique index remains the race's backstop. +/// +/// +/// Export only, for now. The erasure's last-administrator rule is P03-10 Step 2's and the closure's +/// structure Step 3's; asked about either kind this refuses to answer rather than call it eligible. +/// +/// +public sealed class DataRequestEligibility(IDataRequestStore store, IDataRequestHoldSource holds, ITenantContext tenant) + : IDataRequestEligibility +{ + public async Task EvaluateAsync(DataRequestEligibilityQuery query, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + if (!tenant.IsResolved || query.Group.TenantId != tenant.TenantId || query.Group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Eligibility is judged only inside the request's own announced group."); + } + + if (query.Kind != DataRequestKind.Export) + { + throw new InvalidOperationException("Erasure and closure eligibility land with their own steps (ADR-0106 § 7, ADR-0107 § 5, § 7)."); + } + + var memberships = await store.ReadSubjectMembershipsAsync(query.SubjectUserId, cancellationToken).ConfigureAwait(false); + if (memberships.Count == 0) + { + return DataRequestEligibilityDecision.Refused(DataRequestIneligibility.NoMembership); + } + + var active = await store.FindActiveLockedAsync(query.SubjectUserId, query.Kind, cancellationToken).ConfigureAwait(false); + if (active is not null && (query.Stage == DataRequestEligibilityStage.Creation || active.Id.Value != query.RequestId)) + { + return DataRequestEligibilityDecision.Refused(DataRequestIneligibility.RequestAlreadyActive); + } + + return await holds.HasHoldAsync(new DataRequestHoldQuery(query.Kind, query.SubjectUserId, query.Group), cancellationToken) + .ConfigureAwait(false) + ? DataRequestEligibilityDecision.Refused(DataRequestIneligibility.BlockedHold) + : DataRequestEligibilityDecision.Eligible; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs index 5f9cd2f7..32d70cf0 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs @@ -47,7 +47,20 @@ public static DataRequestStatus EffectiveStatus(DataSubjectRequest request, Data /// transaction, so the row is locked against a job that is, after all, still committing. /// /// Whether the request was moved to failed. - public async Task ReconcileAsync(DataSubjectRequest request, CancellationToken cancellationToken) + public Task ReconcileAsync(DataSubjectRequest request, CancellationToken cancellationToken) => + ReconcileAsync(request, null, cancellationToken); + + /// + /// Stores failed for a tracked, non-terminal request whose job is dead, on a transaction whose caller already + /// holds the Identity tenant fence through . + /// + /// + /// A transaction holds one lock plan (), so a creation path that took the + /// subject's User fence and the tenant fence before it judges the one-active rule (ADR-0106 § 7) hands its plan in + /// and this proves the plan is still current instead of acquiring a second one. + /// + public async Task ReconcileAsync(DataSubjectRequest request, IdentityMutationLockPlan? heldPlan, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); if (request.IsTerminal || !CanFail(request) || request.TenantId != tenant.TenantId @@ -56,13 +69,25 @@ public async Task ReconcileAsync(DataSubjectRequest request, CancellationT return false; } - if (await phases.ReadAsync(request, cancellationToken).ConfigureAwait(false) != DataRequestJobPhase.Dead) + if (await phases.ReadAsync(request.Id, request.Kind, cancellationToken).ConfigureAwait(false) != DataRequestJobPhase.Dead) { return false; } - await locks.AcquireAsync(new IdentityMutationLockPlan([], tenant.TenantId, IdentityTenantLockMode.Shared), cancellationToken) - .ConfigureAwait(false); + if (heldPlan is null) + { + await locks.AcquireAsync(new IdentityMutationLockPlan([], tenant.TenantId, IdentityTenantLockMode.Shared), cancellationToken) + .ConfigureAwait(false); + } + else if (heldPlan.TenantId != tenant.TenantId) + { + throw new InvalidOperationException("A held lock plan must fence the request's own tenant."); + } + else + { + locks.RequireCurrent(heldPlan); + } + var now = clock.UtcNow; var actor = tenant.UserId ?? UserId.SystemActor; if (request.Status == DataRequestStatus.Requested) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs index c0f8c57c..88af6e57 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs @@ -38,42 +38,48 @@ public static BackgroundJobKey ExportFor(DataRequestSco public interface IDataRequestFulfillmentScheduler { /// Submits the job of the request's kind and group; only an export has one in this step. + /// + /// Takes the request's identity, kind, status and group as values rather than the aggregate: submitting a job writes + /// no request, and the aggregate write port stays the one the census counts. + /// /// /// The request is not a requested export of the announced group: a programming error, because the creation /// path decides the kind and the group before it submits. /// - ValueTask SubmitAsync(DataSubjectRequest request, CancellationToken cancellationToken); + ValueTask SubmitAsync(Guid requestId, DataRequestKind kind, DataRequestStatus status, DataRequestScopeGroup group, + CancellationToken cancellationToken); /// Schedules the purge of an artifact's chunks at , its expiry (ADR-0107 § 4). - ValueTask SchedulePurgeAsync(DataExportArtifactId artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken); + ValueTask SchedulePurgeAsync(Guid artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken); } /// The default , over the typed job scheduler. public sealed class DataRequestFulfillmentScheduler(IBackgroundJobScheduler scheduler, ITenantContext tenant) : IDataRequestFulfillmentScheduler { - public async ValueTask SubmitAsync(DataSubjectRequest request, CancellationToken cancellationToken) + public async ValueTask SubmitAsync(Guid requestId, DataRequestKind kind, DataRequestStatus status, DataRequestScopeGroup group, + CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(request); - if (request.Kind != DataRequestKind.Export || request.Status != DataRequestStatus.Requested - || request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId) + ArgumentNullException.ThrowIfNull(group); + if (requestId == Guid.Empty || requestId.Version != 7 || kind != DataRequestKind.Export || status != DataRequestStatus.Requested + || group.TenantId != tenant.TenantId || group.OrganizationId != tenant.OrganizationId) { throw new InvalidOperationException("Only a requested export of the announced group has a fulfilment job in this step."); } - await scheduler.EnqueueAsync(DataExportJobKeys.ExportFor(request.Group), - new DataExportJobParameters(request.Id.Value), cancellationToken).ConfigureAwait(false); + await scheduler.EnqueueAsync(DataExportJobKeys.ExportFor(group), new DataExportJobParameters(requestId), cancellationToken) + .ConfigureAwait(false); } - public async ValueTask SchedulePurgeAsync(DataExportArtifactId artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) + public async ValueTask SchedulePurgeAsync(Guid artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) { - if (artifactId.Value == Guid.Empty || artifactId.Value.Version != 7 || dueAt == default) + if (artifactId == Guid.Empty || artifactId.Version != 7 || dueAt == default) { throw new InvalidOperationException("A purge is scheduled for an artifact at its expiry."); } var key = tenant.OrganizationId is null ? DataExportJobKeys.TenantPurge : DataExportJobKeys.OrganizationPurge; - await scheduler.ScheduleAsync(key, new DataExportPurgeParameters(artifactId.Value), dueAt, cancellationToken) + await scheduler.ScheduleAsync(key, new DataExportPurgeParameters(artifactId), dueAt, cancellationToken) .ConfigureAwait(false); } } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestHandlers.cs new file mode 100644 index 00000000..bdcdb9fd --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestHandlers.cs @@ -0,0 +1,184 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +// The live-session request types are thin: each admits its own exact invocation, builds the caller the core serves +// and hands over. The retained-entry types of ADR-0106 § 9 add their own admission over the same cores. + +/// Admits a live-session data-request operation and builds the caller its core serves. +public sealed class LiveDataRequestAdmission(DataRequestAuthorization authorization, ITenantContext context) +{ + internal async Task> AdmitAsync(object request, CancellationToken cancellationToken) + { + var admitted = await authorization.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + if (admitted.IsFailure) + { + return Result.Fail(admitted.Error); + } + + var invocation = admitted.Value; + var role = DataRequestAuthorization.IsAdministration(request) ? DataRequestRole.Administrator : DataRequestRole.Subject; + return Result.Ok(new DataRequestCaller(context.UserId!.Value, role, + token => authorization.RecheckAsync(request, invocation, token))); + } +} + +public sealed class CreateOwnDataExportCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateOwnDataExportCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateExportAsync(caller.Value, caller.Value.Actor, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ListOwnDataRequestsQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler>> +{ + public async Task>> Handle(ListOwnDataRequestsQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result>.Fail(caller.Error) + : await service.ListAsync(caller.Value, IdentityOperationPolicySource.OwnDataRequestListOperation, request.Cursor, request.Limit, + cancellationToken).ConfigureAwait(false); + } +} + +public sealed class GetOwnDataRequestQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(GetOwnDataRequestQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.GetAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class CancelOwnDataRequestCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CancelOwnDataRequestCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CancelAsync(caller.Value, request.RequestId, request.ExpectedVersion, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class RevokeOwnDataExportCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(RevokeOwnDataExportCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.RevokeAsync(caller.Value, request.RequestId, request.ExpectedArtifactVersion, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class MintOwnDataExportTicketCommandHandler(LiveDataRequestAdmission admission, DataExportDownloadService service) + : IRequestHandler> +{ + public async Task> Handle(MintOwnDataExportTicketCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.MintTicketAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ReadOwnDataExportChunkCommandHandler(LiveDataRequestAdmission admission, DataExportDownloadService service) + : IRequestHandler> +{ + public async Task> Handle(ReadOwnDataExportChunkCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.ReadChunkAsync(caller.Value, request.RequestId, request.Ticket, request.Index, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ReadOwnDataRequestReceiptQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(ReadOwnDataRequestReceiptQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.ReadReceiptAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class CreateDataExportForSubjectCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateDataExportForSubjectCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateExportForMembershipAsync(caller.Value, request.MembershipId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ListDataRequestsQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler>> +{ + public async Task>> Handle(ListDataRequestsQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result>.Fail(caller.Error) + : await service.ListAsync(caller.Value, IdentityOperationPolicySource.DataRequestListOperation, request.Cursor, request.Limit, + cancellationToken).ConfigureAwait(false); + } +} + +public sealed class GetDataRequestQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(GetDataRequestQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.GetAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class CancelDataRequestCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CancelDataRequestCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CancelAsync(caller.Value, request.RequestId, request.ExpectedVersion, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class RevokeDataExportCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(RevokeDataExportCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.RevokeAsync(caller.Value, request.RequestId, request.ExpectedArtifactVersion, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ReadDataRequestReceiptQueryHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(ReadDataRequestReceiptQuery request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.ReadReceiptAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs new file mode 100644 index 00000000..3ab3c13b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs @@ -0,0 +1,450 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// Whom an operation serves: the request's subject, or the administrator who filed it. +public enum DataRequestRole +{ + /// The person the request is about; reaches only their own requests. + Subject = 1, + + /// A holder of identity.membership.admin covering the group; mutates only the requests they filed. + Administrator = 2, +} + +/// +/// The caller a handler core serves, independent of how its context was established: the live-session handlers +/// build it from , and a retained-entry path from its own witness. The core +/// calls once its fences are held, so authority lost while waiting refuses the act. +/// +public sealed class DataRequestCaller +{ + private readonly Func>> _recheck; + + public DataRequestCaller(UserId actor, DataRequestRole role, Func>> recheck) + { + ArgumentNullException.ThrowIfNull(recheck); + if (!StronglyTypedId.IsAssigned(actor) || actor == UserId.SystemActor || !Enum.IsDefined(role)) + { + throw new ArgumentException("A data request caller is a real person in a closed role.", nameof(actor)); + } + + Actor = actor; + Role = role; + _recheck = recheck; + } + + public UserId Actor { get; } + public DataRequestRole Role { get; } + + public Task> RecheckAsync(CancellationToken cancellationToken) => _recheck(cancellationToken); + + public override string ToString() => nameof(DataRequestCaller); +} + +/// +/// The handler cores of the data-request API +/// (ADR-0106, +/// ADR-0107 § 4): +/// one core per operation, each confined to the announced group and to the caller's role. +/// +/// +/// +/// The group is the context's. Every row is read and written in the announced tenant and exactly the announced +/// organization or none; a request of another group is absent, never refused, so its existence is not disclosed. +/// +/// +/// Roles. A subject reaches only requests about themselves. An administrator reads every export and erasure +/// of the group (status and counts only, never content, never a closure) and cancels or revokes only what they filed. +/// The subject also revokes an artifact an administrator's export produced; nobody else does. +/// +/// +/// Secrets. A ticket is returned once and stored only as its digest; a chunk's plaintext is handed to the +/// transport, which clears it once written. Neither reaches a log, an exception, an audit row or an idempotency +/// receipt: the ticket operations are not keyed, and the audit capture redacts the ticket's digests. +/// +/// +public sealed class DataRequestService(IDataRequestStore store, IDataRequestReader reader, IDataRequestJobPhaseReader phases, + DataRequestFailureReconciler reconciler, IDataRequestEligibility eligibility, IDataRequestFulfillmentScheduler scheduler, + IDataExportArtifactStore artifacts, IIdentityMutationLocks locks, ITenantContext context, IAuditSubject audit, IGuidFactory ids, + IClock clock) +{ + private DataRequestScopeGroup Group => new(context.TenantId, context.OrganizationId); + + /// + /// Files an export of 's data in the announced group under the subject's exclusive User + /// fence and the shared tenant fence, with the frozen Membership snapshot, and submits its job on the same + /// transaction (ADR-0106 § 7, § 8, § 10; ADR-0107 § 2). + /// + public async Task> CreateExportAsync(DataRequestCaller caller, UserId subject, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (!StronglyTypedId.IsAssigned(subject) || subject == UserId.SystemActor + || (caller.Role == DataRequestRole.Subject) != (subject == caller.Actor)) + { + // The subject files only for themselves; an administrator never for themselves (ADR-0106 § 3). + return Rule("$", "lockey_business_rule_violation"); + } + + try + { + var plan = new IdentityMutationLockPlan([subject], context.TenantId, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan, cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result.Fail(current.Error); + } + + // ADR-0106 § 8: a dead job's request is stored failed under these fences before the one-active rule is + // judged, so a person whose export died is never locked out. + if (await store.FindActiveLockedAsync(subject, DataRequestKind.Export, cancellationToken).ConfigureAwait(false) is { } existing) + { + await reconciler.ReconcileAsync(existing, plan, cancellationToken).ConfigureAwait(false); + } + + var origin = caller.Role == DataRequestRole.Subject ? DataRequestOrigin.Self : DataRequestOrigin.Administrator; + var decision = await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, origin, subject, + Group, DataRequestEligibilityStage.Creation), cancellationToken).ConfigureAwait(false); + if (!decision.IsEligible) + { + return decision.Reason switch + { + DataRequestIneligibility.NoMembership => Fail("lockey_not_found"), + DataRequestIneligibility.RequestAlreadyActive => AlreadyActive(), + DataRequestIneligibility.BlockedHold => Rule("$", "lockey_blocked_hold"), + _ => Rule("$", "lockey_blocked_last_administrator"), + }; + } + + var memberships = await store.ReadSubjectMembershipsAsync(subject, cancellationToken).ConfigureAwait(false); + if (memberships.Count == 0) + { + return Fail("lockey_not_found"); + } + + if (memberships.Count > DataRequestLimits.MaximumSnapshotMemberships) + { + return Rule("$", "lockey_business_rule_violation"); + } + + var id = NewId(ids); + var now = clock.UtcNow; + var created = caller.Role == DataRequestRole.Subject + ? DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(id), DataRequestKind.Export, subject, Group, memberships, now) + : DataSubjectRequest.FileForSubject(DataSubjectRequestId.From(id), DataRequestKind.Export, caller.Actor, subject, Group, + memberships, now); + if (created.IsFailure) + { + return Result.Fail(created.Error); + } + + var request = created.Value; + audit.Designate(request); + locks.RequireCurrent(plan); + if (!await store.TryAddAsync(request, cancellationToken).ConfigureAwait(false)) + { + return AlreadyActive(); + } + + await scheduler.SubmitAsync(request.Id.Value, request.Kind, request.Status, request.Group, cancellationToken).ConfigureAwait(false); + return Result.Ok(new DataRequestMutationResult(request.Id.Value, request.Version)); + } + catch (IdentityMutationLockException) + { + return Fail("lockey_dependency_unavailable"); + } + } + + /// + /// An administrator files an export for the person who holds or held , of any status, + /// in the announced group (ADR-0106 § 3): a Revoked tombstone still names its person. A Membership of another group + /// is absent. + /// + public async Task> CreateExportForMembershipAsync(DataRequestCaller caller, Guid membershipId, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (caller.Role != DataRequestRole.Administrator) + { + return Fail("lockey_forbidden"); + } + + if (!ValidId(membershipId)) + { + return Fail("lockey_validation_failed"); + } + + var subject = await reader.FindMembershipSubjectAsync(MembershipId.From(membershipId), cancellationToken).ConfigureAwait(false); + return subject is { } person + ? await CreateExportAsync(caller, person, cancellationToken).ConfigureAwait(false) + : Fail("lockey_not_found"); + } + + /// The caller's page of the group's requests, newest first, with each one's displayed status. + public async Task>> ListAsync(DataRequestCaller caller, string operation, string? cursor, int limit, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + ArgumentException.ThrowIfNullOrWhiteSpace(operation); + var scope = DataRequestCursorCodec.Scope(operation, caller.Actor, context.TenantId, context.OrganizationId); + Guid? before = null; + if (limit is < 1 or > CursorPagination.MaxLimit) + { + return Fail>("lockey_validation_failed"); + } + + if (cursor is not null) + { + if (!DataRequestCursorCodec.TryDecode(cursor, scope, out var anchor)) + { + return Fail>("lockey_validation_failed"); + } + + before = anchor; + } + + var rows = await reader.ListAsync(caller.Role == DataRequestRole.Subject ? caller.Actor : null, before, limit + 1, cancellationToken) + .ConfigureAwait(false); + var page = rows.Take(limit).ToArray(); + var views = await ViewsAsync(caller, page, cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result>.Fail(current.Error); + } + + var next = rows.Count > limit ? DataRequestCursorCodec.Encode(scope, page[^1].Id.Value) : null; + return Result.Ok(new Page(views, new PageInfo(next, null, next is not null, false))); + } + + /// One request's receipt, or not_found when the caller's role does not reach it in this group. + public async Task> GetAsync(DataRequestCaller caller, Guid requestId, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + var request = await FindVisibleAsync(caller, requestId, cancellationToken).ConfigureAwait(false); + if (request is null) + { + return Fail("lockey_not_found"); + } + + audit.Designate(request); + var view = (await ViewsAsync(caller, [request], cancellationToken).ConfigureAwait(false))[0]; + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + return current.IsFailure ? Result.Fail(current.Error) : Result.Ok(view); + } + + /// Disclosure of an original request a keyed replay names: the caller must still reach it. + public async Task> ReadReceiptAsync(DataRequestCaller caller, Guid requestId, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + var request = await FindVisibleAsync(caller, requestId, cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return current; + } + + if (request is null || !Mutates(caller, request)) + { + return Fail("lockey_not_found"); + } + + audit.Designate(request); + return Result.Ok(None.Value); + } + + /// requested → cancelled under the shared tenant fence the request guard requires (ADR-0106 § 8, § 11). + public async Task> CancelAsync(DataRequestCaller caller, Guid requestId, long expectedVersion, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (!ValidId(requestId) || expectedVersion < 0) + { + return Fail("lockey_validation_failed"); + } + + try + { + var plan = new IdentityMutationLockPlan([], context.TenantId, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan, cancellationToken).ConfigureAwait(false); + var request = await store.FindLockedAsync(DataSubjectRequestId.From(requestId), cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result.Fail(current.Error); + } + + if (request is null || !Mutates(caller, request)) + { + return Fail("lockey_not_found"); + } + + audit.Designate(request); + if (request.Version != expectedVersion) + { + return Fail("lockey_concurrency_conflict"); + } + + var cancelled = request.Cancel(clock.UtcNow, caller.Actor); + if (cancelled.IsFailure) + { + return Result.Fail(cancelled.Error); + } + + locks.RequireCurrent(plan); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return Result.Ok(new DataRequestMutationResult(request.Id.Value, request.Version)); + } + catch (IdentityMutationLockException) + { + return Fail("lockey_dependency_unavailable"); + } + } + + /// + /// Revokes an unexpired artifact, which deletes its chunks at once (ADR-0107 § 4). The subject revokes any + /// artifact about them; an administrator only one an export they filed produced. + /// + public async Task> RevokeAsync(DataRequestCaller caller, Guid requestId, + long expectedArtifactVersion, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (!ValidId(requestId) || expectedArtifactVersion < 0) + { + return Fail("lockey_validation_failed"); + } + + var request = await FindVisibleAsync(caller, requestId, cancellationToken).ConfigureAwait(false); + var found = request is not null && request.Kind == DataRequestKind.Export && Mutates(caller, request) + ? await reader.FindArtifactLockedAsync(request.Id, cancellationToken).ConfigureAwait(false) + : null; + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return Result.Fail(current.Error); + } + + if (found is null) + { + return Fail("lockey_not_found"); + } + + var artifact = found.Artifact; + audit.Designate(artifact); + if (artifact.Version != expectedArtifactVersion) + { + return Fail("lockey_concurrency_conflict"); + } + + if (!found.Readable) + { + return Rule("artifact", "lockey_data_export_unavailable"); + } + + var outcome = await artifacts.PurgeAsync(new DataExportArtifactLocator(artifact.Id.Value, Group), DataExportArtifactStatus.Revoked, + cancellationToken).ConfigureAwait(false); + return outcome is DataExportArtifactStatus.Revoked or DataExportArtifactStatus.Purged + ? Result.Ok(new DataExportArtifactMutationResult(request!.Id.Value, artifact.Id.Value, artifact.Version)) + : Fail("lockey_not_found"); + } + + private Task FindVisibleAsync(DataRequestCaller caller, Guid requestId, CancellationToken cancellationToken) => + FindVisibleAsync(reader, caller, requestId, cancellationToken); + + /// The request when the caller's role reaches it in the announced group; otherwise. + internal static async Task FindVisibleAsync(IDataRequestReader reader, DataRequestCaller caller, Guid requestId, + CancellationToken cancellationToken) + { + if (!ValidId(requestId)) + { + return null; + } + + var request = await reader.FindAsync(DataSubjectRequestId.From(requestId), cancellationToken).ConfigureAwait(false); + return request is not null && Reaches(caller, request) ? request : null; + } + + /// A subject reaches requests about them; an administrator every export and erasure of the group, never a closure. + private static bool Reaches(DataRequestCaller caller, DataSubjectRequest request) => caller.Role == DataRequestRole.Subject + ? request.SubjectUserId == caller.Actor + : request.Kind != DataRequestKind.Closure; + + /// A subject mutates requests about them; an administrator only an export or erasure they filed. + private static bool Mutates(DataRequestCaller caller, DataSubjectRequest request) => caller.Role == DataRequestRole.Subject + ? request.SubjectUserId == caller.Actor + : request.Kind != DataRequestKind.Closure && request.Origin == DataRequestOrigin.Administrator + && request.RequesterUserId == caller.Actor; + + private async Task ViewsAsync(DataRequestCaller caller, DataSubjectRequest[] requests, + CancellationToken cancellationToken) + { + if (requests.Length == 0) + { + return []; + } + + var phase = await phases.ReadManyAsync(requests.Where(request => request.Kind == DataRequestKind.Export) + .Select(request => request.Id).ToArray(), cancellationToken).ConfigureAwait(false); + var stored = await reader.ReadArtifactsAsync(requests.Select(request => request.Id).ToArray(), cancellationToken).ConfigureAwait(false); + return requests.Select(request => View(caller, request, phase.GetValueOrDefault(request.Id, DataRequestJobPhase.Unavailable), + stored.GetValueOrDefault(request.Id))).ToArray(); + } + + /// + /// A receipt shows the status the reconciler would store: failed for a request whose job is dead, without writing + /// (ADR-0106 § 8). No personal data, no content; the Membership snapshot only to an administrator. + /// + internal static DataRequestView View(DataRequestCaller caller, DataSubjectRequest request, DataRequestJobPhase phase, + DataRequestArtifactRow? artifact) + { + var status = DataRequestFailureReconciler.EffectiveStatus(request, phase); + var failure = request.FailureReason + ?? (status == DataRequestStatus.Failed && request.Status != DataRequestStatus.Failed ? DataRequestFailureReason.ExecutionFailed : null); + return new DataRequestView(request.Id.Value, DataRequestCodes.Kinds.ToCode(request.Kind), DataRequestCodes.Origins.ToCode(request.Origin), + DataRequestCodes.Statuses.ToCode(status), request.CreatedAt, request.UpdatedAt, request.CompletedAt, request.ExecuteAt, + request.LastRefusal is { } refusal ? DataRequestCodes.Refusals.ToCode(refusal) : null, + failure is { } reason ? DataRequestCodes.FailureReasons.ToCode(reason) : null, + request.RetainedReport.Select(entry => new DataRequestRetainedView(DataRequestCodes.RetainedKinds.ToCode(entry.Key), entry.Value)) + .OrderBy(entry => entry.Kind, StringComparer.Ordinal).ToArray(), + artifact is null ? null : new DataExportArtifactView(artifact.Artifact.Id.Value, + DataRequestCodes.ArtifactStatuses.ToCode(artifact.Readable || artifact.Artifact.Status != DataExportArtifactStatus.Available + ? artifact.Artifact.Status : DataExportArtifactStatus.Expired), + artifact.Artifact.ExpiresAt, artifact.Artifact.PurgedAt, artifact.Artifact.ByteCount, artifact.Artifact.ChunkCount, + artifact.Artifact.Truncations.Select(item => new DataExportTruncationView(item.Collection, item.Included, item.Total)).ToArray(), + artifact.Artifact.Version, artifact.Readable), + request.Version, + request.RequesterUserId == caller.Actor, + caller.Role == DataRequestRole.Administrator ? request.SnapshotMembershipIds.Select(member => member.Value).ToArray() : null); + } + + internal static Guid NewId(IGuidFactory factory) + { + var id = factory.NewUuidV7(); + return id != Guid.Empty && id.Version == 7 ? id : throw new InvalidOperationException("The identity factory must return a UUIDv7."); + } + + internal static bool ValidId(Guid id) => id != Guid.Empty && id.Version == 7; + + private static Result AlreadyActive() => Rule("$", "lockey_request_already_active"); + + /// A 409 with the reason on the field it concerns; the status map is closed, so the code stays the business rule's. + internal static Result Rule(string field, string reason) => Result.Fail(new Error( + LocalizedMessage.Of("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) { [field] = [LocalizedMessage.Of(reason)] })); + + internal static Result Fail(string key) => Result.Fail(new Error(LocalizedMessage.Of(key))); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestValidators.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestValidators.cs new file mode 100644 index 00000000..5e59161e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestValidators.cs @@ -0,0 +1,117 @@ +using FluentValidation; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Pagination; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +// Shape only: a canonical UUIDv7 target, a non-negative version, a bounded page, a canonical ticket spelling and a +// non-negative chunk index. Authority, scope and state are the handlers'. + +internal sealed class ListOwnDataRequestsValidator : AbstractValidator +{ + public ListOwnDataRequestsValidator() + { + RuleFor(request => request.Limit).InclusiveBetween(1, CursorPagination.MaxLimit).WithErrorCode("lockey_invalid_value"); + RuleFor(request => request.Cursor).Must(DataRequestInput.Cursor).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class ListDataRequestsValidator : AbstractValidator +{ + public ListDataRequestsValidator() + { + RuleFor(request => request.Limit).InclusiveBetween(1, CursorPagination.MaxLimit).WithErrorCode("lockey_invalid_value"); + RuleFor(request => request.Cursor).Must(DataRequestInput.Cursor).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class GetOwnDataRequestValidator : AbstractValidator +{ + public GetOwnDataRequestValidator() => + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class GetDataRequestValidator : AbstractValidator +{ + public GetDataRequestValidator() => + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class ReadOwnDataRequestReceiptValidator : AbstractValidator +{ + public ReadOwnDataRequestReceiptValidator() => + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class ReadDataRequestReceiptValidator : AbstractValidator +{ + public ReadDataRequestReceiptValidator() => + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class CreateDataExportForSubjectValidator : AbstractValidator +{ + public CreateDataExportForSubjectValidator() => + RuleFor(request => request.MembershipId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class CancelOwnDataRequestValidator : AbstractValidator +{ + public CancelOwnDataRequestValidator() + { + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); + RuleFor(request => request.ExpectedVersion).GreaterThanOrEqualTo(0).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class CancelDataRequestValidator : AbstractValidator +{ + public CancelDataRequestValidator() + { + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); + RuleFor(request => request.ExpectedVersion).GreaterThanOrEqualTo(0).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class RevokeOwnDataExportValidator : AbstractValidator +{ + public RevokeOwnDataExportValidator() + { + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); + RuleFor(request => request.ExpectedArtifactVersion).GreaterThanOrEqualTo(0).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class RevokeDataExportValidator : AbstractValidator +{ + public RevokeDataExportValidator() + { + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); + RuleFor(request => request.ExpectedArtifactVersion).GreaterThanOrEqualTo(0).WithErrorCode("lockey_invalid_value"); + } +} + +internal sealed class MintOwnDataExportTicketValidator : AbstractValidator +{ + public MintOwnDataExportTicketValidator() => + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); +} + +internal sealed class ReadOwnDataExportChunkValidator : AbstractValidator +{ + public ReadOwnDataExportChunkValidator() + { + RuleFor(request => request.RequestId).Must(DataRequestInput.Id).WithErrorCode("lockey_identifier_required"); + RuleFor(request => request.Index).GreaterThanOrEqualTo(0).WithErrorCode("lockey_invalid_value"); + // The ticket is checked for its canonical spelling only; its value never reaches a message or a log. + RuleFor(request => request.Ticket).Must(ticket => DataExportTicketCodec.TryDigest(ticket) is not null) + .WithErrorCode("lockey_invalid_value").WithMessage("The ticket is not a canonical download ticket."); + } +} + +internal static class DataRequestInput +{ + internal static bool Id(Guid id) => id != Guid.Empty && id.Version == 7; + + internal static bool Cursor(string? value) => value is null || value.Length is > 0 and <= DataRequestCursorCodec.MaximumEncodedLength; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs index e779fe05..3e8cf6fb 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs @@ -1,6 +1,8 @@ using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Persistence; namespace LearnStack.Modules.Identity.Application.DataRequests; @@ -9,12 +11,19 @@ namespace LearnStack.Modules.Identity.Application.DataRequests; /// learnstack_app (ADR-0106 § 8). /// /// +/// +/// The write port: it derives so the +/// cross-aggregate census counts every holder. A ticket is written through , an +/// artifact only through . +/// +/// /// Every read is confined to the announced tenant and organization, by the predicate and by the row policy, so a /// request or artifact of another group is absent rather than refused. Writes go through tracked aggregates only: /// each transition is saved on its own, because the request and artifact guards admit exactly one arrow and one /// row-version step per UPDATE. +/// /// -public interface IDataRequestStore +public interface IDataRequestStore : IAggregateWriteStore { /// The executing data-request job: refuses a caller that is not one of the module's job roots. BackgroundJobId RequireCurrentJob(); @@ -30,8 +39,74 @@ public interface IDataRequestStore /// Saves the changes of a request this scope loaded and tracks. Task SaveAsync(DataSubjectRequest request, CancellationToken cancellationToken); + + /// + /// The subject's Memberships of any status in the ambient group, Revoked tombstones included: exactly the set the + /// creation guard demands as the frozen snapshot (ADR-0106 § 8). At most + /// plus one. + /// + Task> ReadSubjectMembershipsAsync(UserId subject, CancellationToken cancellationToken); + + /// The subject's non-terminal request of the kind in the ambient group, tracked and locked for update. + Task FindActiveLockedAsync(UserId subject, DataRequestKind kind, CancellationToken cancellationToken); + + /// + /// Inserts a new request of the ambient group. when the one-active partial unique index + /// refused it (ADR-0106 § 7): the transaction is then rollback-only and nothing was stored. + /// + Task TryAddAsync(DataSubjectRequest request, CancellationToken cancellationToken); + + /// + Task IAggregateWriteStore.UpdateAsync(DataSubjectRequest aggregate, + CancellationToken cancellationToken) => SaveAsync(aggregate, cancellationToken); +} + +/// +/// The write port (ADR-0107 § 4): a minted ticket is inserted with its digests only, +/// and the one later change is its consumption. +/// +public interface IDataExportTicketStore : IAggregateWriteStore +{ + /// The artifact's ticket with this digest in the ambient group, tracked and locked for update. + Task FindLockedAsync(DataExportArtifactId artifactId, string digest, CancellationToken cancellationToken); +} + +/// +/// Reads of the ambient group's requests, artifacts and Memberships for the receipts, pages and handler cores +/// (ADR-0106 § 9, § 13). +/// +/// +/// Every read names the announced tenant and organization_id IS NOT DISTINCT FROM the announced +/// organization: the canonical row policy also shows an organization context the tenant-wide group's rows, so the +/// predicate, not the policy, keeps one group's requests out of another's pages. Nothing is written here; the one +/// locking read, , retains the artifact row for the revocation or ticket mint +/// that follows on the same transaction, as the Role lock read does. +/// +public interface IDataRequestReader +{ + /// + /// The group's requests newest first, strictly older than when given: only the + /// subject's when is given, otherwise every export and erasure (never a closure). + /// + Task> ListAsync(UserId? subject, Guid? before, int take, CancellationToken cancellationToken); + + /// One request of the group; when the group holds no such request. + Task FindAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken); + + /// The artifacts of the given requests in the group, each with its readability by the database clock. + Task> ReadArtifactsAsync( + IReadOnlyCollection requestIds, CancellationToken cancellationToken); + + /// The request's export artifact in the ambient group, tracked and locked for update; when none. + Task FindArtifactLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken); + + /// The person who holds or held the Membership, of any status, in the ambient group; otherwise. + Task FindMembershipSubjectAsync(MembershipId membership, CancellationToken cancellationToken); } +/// An artifact and whether it is readable now: stored available and before its expiry by the database clock. +public sealed record DataRequestArtifactRow(DataExportArtifact Artifact, bool Readable); + /// /// Where a data request's fulfilment job stands, read from the job's own row /// (ADR-0106 § 8). @@ -55,7 +130,18 @@ public enum DataRequestJobPhase /// Reads the phase of a request's fulfilment job without writing anything, so a receipt can show failed /// for a dead job before the reconciler has stored it. /// +/// +/// Keyed by the request's typed identity and kind, never by the aggregate: it reads, and the group is the announced one. +/// public interface IDataRequestJobPhaseReader { - Task ReadAsync(DataSubjectRequest request, CancellationToken cancellationToken); + /// The phase of the request's fulfilment job; a kind with no fulfilment job is . + Task ReadAsync(DataSubjectRequestId requestId, DataRequestKind kind, CancellationToken cancellationToken); + + /// + /// The phases of a page of the group's export requests in one statement; a request with no job is + /// . + /// + Task> ReadManyAsync(IReadOnlyCollection exportRequestIds, + CancellationToken cancellationToken); } 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 18ee8a57..abeaf97a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -6,6 +6,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Federation; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Domain; using LearnStack.Modules.Identity.Application.Invitations; using LearnStack.Modules.Identity.Application.DataRequests; @@ -41,6 +42,23 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource public static PermissionDefinition MembershipAdministration { get; } = new(PermissionScope.Tenant, IdentityFoundationManifest.MembershipAdmin); public static PermissionDefinition RoleAdministration { get; } = new(PermissionScope.Tenant, IdentityFoundationManifest.RoleAdmin); public const string FederationReadOperation = "identity.federation.read"; + + // ADR-0106 § 4: the subject's own live-session data-request operations carry no key (OwnDataRequest, whose + // operation ids share this prefix); the administrator's reuse the identity.membership.admin alternatives. + public const string OwnDataExportCreateOperation = "identity.data_request.create_own_export"; + public const string OwnDataRequestListOperation = "identity.data_request.list_own"; + public const string OwnDataRequestReadOperation = "identity.data_request.read_own"; + public const string OwnDataRequestCancelOperation = "identity.data_request.cancel_own"; + public const string OwnDataExportRevokeOperation = "identity.data_request.revoke_own_export"; + public const string OwnDataExportTicketOperation = "identity.data_request.mint_export_ticket"; + public const string OwnDataExportChunkOperation = "identity.data_request.read_export_chunk"; + public const string OwnDataRequestReceiptOperation = "identity.data_request.read_own_receipt"; + public const string DataExportCreateOperation = "identity.data_request.create_export"; + public const string DataRequestListOperation = "identity.data_request.list"; + public const string DataRequestReadOperation = "identity.data_request.read"; + public const string DataRequestCancelOperation = "identity.data_request.cancel"; + public const string DataExportRevokeOperation = "identity.data_request.revoke_export"; + public const string DataRequestReceiptOperation = "identity.data_request.read_receipt"; public const string PublicSignInOperation = "identity.public_sign_in.read"; /// Virtual Portal Public definition for the anonymous sign-in read; never a stored Role grant. public static PermissionDefinition PublicSignIn { get; } = new(PermissionScope.Tenant, "identity.public_sign_in.read"); @@ -65,6 +83,20 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("identity.data_request.fulfill_organization_export", AuthorizationSourceKind.BackgroundJob), OperationPolicy.ForTrusted("identity.data_export.purge_tenant", AuthorizationSourceKind.BackgroundJob), OperationPolicy.ForTrusted("identity.data_export.purge_organization", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForOwnDataRequest(OwnDataExportCreateOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestListOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestReadOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestCancelOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportRevokeOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportTicketOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportChunkOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestReceiptOperation), + OperationPolicy.ForProtected(DataExportCreateOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataRequestListOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataRequestReadOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataRequestCancelOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataExportRevokeOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataRequestReceiptOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected("identity.invitation.list", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected("identity.invitation.read", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected("identity.invitation.list_invitable_roles", [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), 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 212e1fde..d6e67af9 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 @@ -16,6 +16,7 @@ using LearnStack.Modules.Identity.Infrastructure.Persistence; using LearnStack.Modules.Identity.Application.DataRequests; using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Results; @@ -96,6 +97,17 @@ private static void AddIdentityDataRequests(this IServiceCollection services) services.TryAddScoped>>(provider => provider.GetRequiredService()); services.TryAddScoped(); services.TryAddEnumerable(ServiceDescriptor.Scoped()); + // ADR-0106 § 7, ADR-0107 § 4: the live-session request API. The default eligibility checks structure only; the + // hold source is the composition root's NoHoldSource. The session binding answers nothing until the API + // composition replaces it with the validated-credential binding, so no other host mints or honours a ticket. + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); } /// Registers internal consumers only; qualification is an explicit startup act before admission activation. diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs new file mode 100644 index 00000000..5cac7d4d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs @@ -0,0 +1,106 @@ +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// on the ambient Identity context and transaction, confined to the announced group +/// (ADR-0107 § 4). A ticket is inserted with its two digests and its one later change is the consumed marker, which is +/// the application role's only update privilege on the table. +/// +public sealed class DataExportTicketStore(IdentityDbContext db, IUnitOfWork unit, ITenantContext tenant) : IDataExportTicketStore +{ + public async Task AddAsync(DataExportTicket aggregate, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(aggregate); + Admit(); + if (aggregate.TenantId != tenant.TenantId || aggregate.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A download ticket is minted only in its own announced group."); + } + + db.DataExportTickets.Add(aggregate); + await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + public async Task UpdateAsync(DataExportTicket aggregate, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(aggregate); + RequireOwner(); + if (aggregate.TenantId != tenant.TenantId || aggregate.OrganizationId != tenant.OrganizationId + || db.Entry(aggregate).State == EntityState.Detached + || !ReferenceEquals(db.Database.CurrentTransaction?.GetDbTransaction(), unit.Transaction)) + { + throw new InvalidOperationException("A download ticket is saved only from its own loaded group."); + } + + await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + public async Task FindLockedAsync(DataExportArtifactId artifactId, string digest, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(digest); + Admit(); + if (digest.Length != 64 || !digest.All(char.IsAsciiHexDigitLower)) + { + return null; + } + + // The digest is unique per tenant; the artifact and group narrow it further, so another artifact's or group's + // ticket is absent here rather than refused. + await using var command = DataRequestSql.Command(unit, tenant, """ + SELECT id FROM public.data_export_tickets + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND artifact_id=@artifact AND digest=@digest + FOR UPDATE + """); + command.Parameters.AddWithValue("artifact", artifactId.Value); + command.Parameters.AddWithValue("digest", NpgsqlDbType.Bytea, Convert.FromHexString(digest)); + var found = await DataRequestSql.ExecuteAsync(unit, token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false); + if (found is not Guid id) + { + return null; + } + + var ticketId = DataExportTicketId.From(id); + return await db.DataExportTickets.SingleAsync(candidate => candidate.Id == ticketId + && candidate.TenantId == tenant.TenantId && candidate.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + } + + private async Task SaveChangesAsync(CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + } + + /// The announced writable owner, with the clean Identity context re-enrolled on its transaction. + private void Admit() + { + RequireOwner(); + ContextualIdentityStorageControl.EnrollCurrentTenantOwner(db, unit); + } + + private void RequireOwner() + { + if (!unit.HasActiveTransaction || unit.IsRollbackOnly || unit.Mode != TransactionMode.ReadWrite + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Download ticket storage requires its announced writable owner."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs index 5658c1d1..d5b046cc 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs @@ -23,23 +23,15 @@ namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; /// public sealed class DataRequestJobPhaseReader(IUnitOfWork unit, ITenantContext tenant) : IDataRequestJobPhaseReader { - public async Task ReadAsync(DataSubjectRequest request, CancellationToken cancellationToken) + public async Task ReadAsync(DataSubjectRequestId requestId, DataRequestKind kind, CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(request); - if (!unit.HasActiveTransaction || unit.IsRollbackOnly - || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement - || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId - || request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId) - { - throw new InvalidOperationException("A data request job phase requires its existing announced owner."); - } - - if (request.Kind != DataRequestKind.Export) + RequireOwner(); + if (kind != DataRequestKind.Export) { return DataRequestJobPhase.Unavailable; } - var parameters = BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(request.Id.Value), + var parameters = BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(requestId.Value), typeof(DataExportJobParameters), BackgroundJobPayloadKind.Parameters); await using var command = new NpgsqlCommand(""" SELECT phase, quarantine_reason IS NOT NULL OR terminal_reason IS NOT NULL OR dead_lettered_at IS NOT NULL @@ -51,7 +43,8 @@ LIMIT 1 """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); - command.Parameters.AddWithValue("definition", DataExportJobKeys.ExportFor(request.Group).Value); + command.Parameters.AddWithValue("definition", + DataExportJobKeys.ExportFor(new DataRequestScopeGroup(tenant.TenantId, tenant.OrganizationId)).Value); command.Parameters.AddWithValue("parameters", parameters); using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); budget.CancelAfter(TimeSpan.FromSeconds(5)); @@ -74,6 +67,76 @@ LIMIT 1 } } + public async Task> ReadManyAsync( + IReadOnlyCollection exportRequestIds, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(exportRequestIds); + RequireOwner(); + if (exportRequestIds.Count > 101) + { + throw new InvalidOperationException("A data request job phase page reads at most 101 requests."); + } + + var phases = exportRequestIds.Distinct().ToDictionary(id => id, _ => DataRequestJobPhase.Unavailable); + var exports = phases.Keys + .ToDictionary(id => BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(id.Value), + typeof(DataExportJobParameters), BackgroundJobPayloadKind.Parameters), id => id, StringComparer.Ordinal); + if (exports.Count == 0) + { + return phases; + } + + // One statement for the page, newest job per request, by the same exact route as the single read. + await using var command = new NpgsqlCommand(""" + SELECT DISTINCT ON (parameters) parameters, phase, + quarantine_reason IS NOT NULL OR terminal_reason IS NOT NULL OR dead_lettered_at IS NOT NULL + FROM public.background_jobs + WHERE tenant_id = @tenant AND organization_id IS NOT DISTINCT FROM @organization + AND definition_key = @definition AND profile = 'transactional' AND parameters = ANY(@parameters) + ORDER BY parameters, created_at DESC, id DESC + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + command.Parameters.AddWithValue("definition", + DataExportJobKeys.ExportFor(new DataRequestScopeGroup(tenant.TenantId, tenant.OrganizationId)).Value); + command.Parameters.AddWithValue("parameters", exports.Keys.ToArray()); + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + await using var row = await command.ExecuteReaderAsync(budget.Token).ConfigureAwait(false); + while (await row.ReadAsync(budget.Token).ConfigureAwait(false)) + { + if (exports.TryGetValue(row.GetString(0), out var id)) + { + phases[id] = Classify(row.GetString(1), row.GetBoolean(2)); + } + } + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && budget.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request job phase unavailable."); + } + catch (NpgsqlException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request job phase unavailable."); + } + + return phases; + } + + private void RequireOwner() + { + if (!unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A data request job phase requires its existing announced owner."); + } + } + /// Quarantine, a terminal reason or a dead letter is dead; completed without one is done. public static DataRequestJobPhase Classify(string phase, bool failed) => (phase, failed) switch { diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestReader.cs new file mode 100644 index 00000000..f659f9d1 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestReader.cs @@ -0,0 +1,176 @@ +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// on the ambient Identity context and transaction: untracked, confined to the +/// announced tenant and exactly the announced organization or none. +/// +/// +/// The predicate organization_id IS NOT DISTINCT FROM the announced organization is what keeps the +/// tenant-wide group's requests out of an organization's pages and the reverse: the canonical row policy shows an +/// organization context the tenant-wide rows as well (ADR-0106 § 2). +/// +public sealed class DataRequestReader(IdentityDbContext db, IUnitOfWork unit, ITenantContext tenant) : IDataRequestReader +{ + public async Task> ListAsync(UserId? subject, Guid? before, int take, + CancellationToken cancellationToken) + { + Admit(); + if (take is < 1 or > 101) + { + throw new ArgumentOutOfRangeException(nameof(take), "A data request page reads between one and 101 rows."); + } + + // A UUIDv7 is time-ordered and unique, so newest first is id descending and the seek is id < anchor. + var source = before is { } anchor + ? db.DataSubjectRequests.FromSqlInterpolated($"SELECT * FROM public.data_subject_requests WHERE id < {anchor}") + : db.DataSubjectRequests; + var query = Group(source.AsNoTracking()); + query = subject is { } person + ? query.Where(request => request.SubjectUserId == person) + : query.Where(request => request.Kind != DataRequestKind.Closure); + return await Guard(() => query.OrderByDescending(request => request.Id).Take(take).ToListAsync(cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + public async Task FindAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) + { + Admit(); + return await Guard(() => Group(db.DataSubjectRequests.AsNoTracking()) + .SingleOrDefaultAsync(request => request.Id == requestId, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + public async Task> ReadArtifactsAsync( + IReadOnlyCollection requestIds, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(requestIds); + Admit(); + if (requestIds.Count == 0) + { + return new Dictionary(); + } + + if (requestIds.Count > 101) + { + throw new ArgumentOutOfRangeException(nameof(requestIds), "A data request page reads at most 101 artifacts."); + } + + var ids = requestIds.Distinct().ToArray(); + var artifacts = await Guard(() => db.DataExportArtifacts.AsNoTracking() + .Where(artifact => artifact.TenantId == tenant.TenantId && artifact.OrganizationId == tenant.OrganizationId + && ids.Contains(artifact.RequestId)) + .ToListAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + if (artifacts.Count == 0) + { + return new Dictionary(); + } + + // Expiry is a time check by the database clock, as the guards and the chunk read make it (ADR-0107 § 4). + var now = await DatabaseNowAsync(cancellationToken).ConfigureAwait(false); + return artifacts.ToDictionary(artifact => artifact.RequestId, + artifact => new DataRequestArtifactRow(artifact, artifact.Status == DataExportArtifactStatus.Available && now < artifact.ExpiresAt)); + } + + public async Task FindMembershipSubjectAsync(MembershipId membership, CancellationToken cancellationToken) + { + Admit(); + await using var command = DataRequestSql.Command(unit, tenant, """ + SELECT user_id FROM public.memberships + WHERE id=@membership AND tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization + """); + command.Parameters.AddWithValue("membership", membership.Value); + var found = await DataRequestSql.ExecuteAsync(unit, token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false); + return found is Guid user ? UserId.From(user) : null; + } + + public async Task FindArtifactLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) + { + Admit(); + await using var command = DataRequestSql.Command(unit, tenant, """ + SELECT id, status = 'available' AND clock_timestamp() < expires_at FROM public.data_export_artifacts + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND request_id=@request + FOR UPDATE + """); + command.Parameters.AddWithValue("request", requestId.Value); + var found = await DataRequestSql.ExecuteAsync(unit, async token => + { + await using var row = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + if (!await row.ReadAsync(token).ConfigureAwait(false)) + { + return ((Guid Id, bool Readable)?)null; + } + + var value = (row.GetGuid(0), row.GetBoolean(1)); + return await row.ReadAsync(token).ConfigureAwait(false) + ? throw new InvalidOperationException("A request holds more than one export artifact.") + : value; + }, cancellationToken).ConfigureAwait(false); + if (found is not { } artifact) + { + return null; + } + + var artifactId = DataExportArtifactId.From(artifact.Id); + var tracked = await db.DataExportArtifacts.SingleAsync(candidate => candidate.Id == artifactId + && candidate.TenantId == tenant.TenantId && candidate.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + return new DataRequestArtifactRow(tracked, artifact.Readable); + } + + private IQueryable Group(IQueryable requests) => + requests.Where(request => request.TenantId == tenant.TenantId && request.OrganizationId == tenant.OrganizationId); + + private async Task DatabaseNowAsync(CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand("SELECT clock_timestamp()", (NpgsqlConnection)unit.Connection, + (NpgsqlTransaction)unit.Transaction!) + { CommandTimeout = 5 }; + var value = await Guard(() => command.ExecuteScalarAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + return value switch + { + DateTime utc when utc.Kind == DateTimeKind.Utc => new DateTimeOffset(utc, TimeSpan.Zero), + DateTimeOffset instant => instant.ToUniversalTime(), + _ => throw new InfrastructureException("Data request storage unavailable."), + }; + } + + private async Task Guard(Func> read, CancellationToken cancellationToken) + { + try + { + return await read().ConfigureAwait(false); + } + catch (Exception failure) when (failure is NpgsqlException or DbUpdateException + || failure is OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + } + + /// + /// The announced owner, with the scoped Identity context re-enrolled on its transaction when the context was created on + /// an earlier transaction of the same request. + /// + private void Admit() + { + if (!unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.GetTenantContextAnnouncement(unit.Transaction) is not { } announcement + || announcement.TenantId != tenant.TenantId || announcement.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("Data request reads require their announced owner."); + } + + ContextualIdentityStorageControl.EnrollCurrentTenantOwner(db, unit); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestSql.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestSql.cs new file mode 100644 index 00000000..4c9c6822 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestSql.cs @@ -0,0 +1,43 @@ +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The fixed parameterized statements of the data-request adapters: on the ambient transaction, bound to the announced +/// tenant and organization, under a five-second budget, with a provider failure leaving the owner rollback-only. +/// +internal static class DataRequestSql +{ + internal static NpgsqlCommand Command(IUnitOfWork unit, ITenantContext tenant, string sql) + { + var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + return command; + } + + internal static async Task ExecuteAsync(IUnitOfWork unit, Func> statement, + CancellationToken cancellationToken) + { + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + return await statement(budget.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + catch (NpgsqlException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs index a91b71bd..17b81d46 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs @@ -3,11 +3,13 @@ using LearnStack.Modules.Identity.Domain; using LearnStack.Modules.Identity.Infrastructure.Persistence; using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Tenancy; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; using Npgsql; using NpgsqlTypes; @@ -25,6 +27,13 @@ public sealed class DataRequestStore(IdentityDbContext db, IUnitOfWork unit, Pro typeof(PurgeTenantDataExportCommand), typeof(PurgeOrganizationDataExportCommand), ]; + private const string ActiveIndex = "ux_data_subject_requests_active"; + + private NpgsqlCommand Command(string sql) => DataRequestSql.Command(unit, tenant, sql); + + private Task ExecuteAsync(Func> statement, CancellationToken cancellationToken) => + DataRequestSql.ExecuteAsync(unit, statement, cancellationToken); + public BackgroundJobId RequireCurrentJob() { var origin = producer.CaptureJobOrigin(unit); @@ -40,7 +49,7 @@ public BackgroundJobId RequireCurrentJob() public async Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) { - RequireOwner(); + Admit(); await using var command = new NpgsqlCommand(""" SELECT id FROM public.data_subject_requests WHERE id=@id AND tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization FOR UPDATE @@ -114,6 +123,120 @@ public async Task SaveAsync(DataSubjectRequest request, CancellationToken cancel } } + public async Task> ReadSubjectMembershipsAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + // Exactly the creation guard's predicate (ADR-0106 § 8): every status, Revoked tombstones included, of this group only. + await using var command = Command(""" + SELECT id FROM public.memberships + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND user_id=@subject + ORDER BY id LIMIT @limit + """); + command.Parameters.AddWithValue("subject", subject.Value); + command.Parameters.AddWithValue("limit", DataRequestLimits.MaximumSnapshotMemberships + 1); + return await ExecuteAsync(async token => + { + var found = new List(); + await using var row = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + while (await row.ReadAsync(token).ConfigureAwait(false)) + { + found.Add(MembershipId.From(row.GetGuid(0))); + } + + return (IReadOnlyList)found; + }, cancellationToken).ConfigureAwait(false); + } + + public async Task FindActiveLockedAsync(UserId subject, DataRequestKind kind, CancellationToken cancellationToken) + { + Admit(); + // The one-active partial unique index holds at most one such row (ADR-0106 § 7). + await using var command = Command(""" + SELECT id FROM public.data_subject_requests + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND subject_user_id=@subject AND kind=@kind + AND status IN ('requested','scheduled','fulfilling','awaiting_privileged_step') + FOR UPDATE + """); + command.Parameters.AddWithValue("subject", subject.Value); + command.Parameters.AddWithValue("kind", DataRequestCodes.Kinds.ToCode(kind)); + var found = await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false); + if (found is not Guid id) + { + return null; + } + + var requestId = DataSubjectRequestId.From(id); + return await db.DataSubjectRequests.SingleAsync(request => request.Id == requestId + && request.TenantId == tenant.TenantId && request.OrganizationId == tenant.OrganizationId, cancellationToken) + .ConfigureAwait(false); + } + + /// The aggregate port's insertion: a creation refused by the one-active index is a storage refusal here. + async Task IAggregateWriteStore.AddAsync(DataSubjectRequest aggregate, + CancellationToken cancellationToken) + { + if (!await TryAddAsync(aggregate, cancellationToken).ConfigureAwait(false)) + { + throw new InfrastructureException("Data request already active."); + } + } + + public async Task TryAddAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + Admit(); + if (request.TenantId != tenant.TenantId || request.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A data request is filed only in its own announced group."); + } + + db.DataSubjectRequests.Add(request); + try + { + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return true; + } + catch (DbUpdateException failure) when (failure.InnerException is PostgresException + { + SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: ActiveIndex, + }) + { + // ADR-0106 § 7: two concurrent creations cannot both pass. Nothing was stored and the transaction is aborted. + db.Entry(request).State = EntityState.Detached; + unit.MarkRollbackOnly(); + return false; + } + catch (DbUpdateException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + } + + private async Task SaveChangesAsync(CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException) + { + unit.MarkRollbackOnly(); + throw new InfrastructureException("Data request storage unavailable."); + } + } + + /// + /// The announced writable owner, with the Identity context re-enrolled on its transaction: the scoped context may + /// have been created on an earlier transaction of the same request (the authorization read), and a clean context is + /// re-enrolled only on the same connection's freshly announced tenant owner. + /// + private void Admit() + { + RequireOwner(); + ContextualIdentityStorageControl.EnrollCurrentTenantOwner(db, unit); + } + private void RequireOwner() { if (!unit.HasActiveTransaction || unit.IsRollbackOnly || unit.Mode != TransactionMode.ReadWrite diff --git a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs index 189472e1..adebd592 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs @@ -6,6 +6,7 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.Modules.Education.Application.Abstractions; using LearnStack.Modules.Education.Domain; +using LearnStack.Modules.Identity.Application.DataRequests; using LearnStack.Modules.Identity.Application.Invitations; using LearnStack.Modules.Identity.Domain; using LearnStack.Modules.Identity.Infrastructure.Invitations; @@ -191,6 +192,51 @@ public void Write_Port_Census_Distinguishes_Typed_Read_Keys_From_Wrapped_Domain_ TakesDomainObject(extra, identityDomains).Should().BeTrue("an inherited extra root/key write or same-shaped unrelated port cannot borrow the exact metadata exception"); WriteStoreConstructions(typeof(IInvitationEmailJobStore)).Should().ContainSingle() .Which.GetGenericArguments()[0].Should().Be(); + AssertDataRequestPorts(identityDomains); + } + + /// + /// The subject data-request ports (ADR-0106, ADR-0107): each write port derives the typed write store of the one + /// root it writes, the reader and phase reader take typed keys only through their enumerated read methods, the + /// scheduler takes plain values, and each executor reaches exactly one root. + /// + private static void AssertDataRequestPorts(HashSet identityDomains) + { + WriteStoreConstructions(typeof(IDataRequestStore)).Should().ContainSingle() + .Which.GetGenericArguments()[0].Should().Be(); + WriteStoreConstructions(typeof(IDataExportTicketStore)).Should().ContainSingle() + .Which.GetGenericArguments()[0].Should().Be(); + TakesDomainObject(typeof(IDataRequestFulfillmentScheduler), identityDomains) + .Should().BeFalse("the scheduler takes the request's identifier and SharedKernel vocabulary, never a root"); + foreach (var port in new[] { typeof(IDataRequestReader), typeof(IDataRequestJobPhaseReader) }) + { + TakesDomainObject(port, identityDomains).Should().BeFalse($"{port.Name} reads its typed keys only through enumerated read methods"); + foreach (var method in port.GetMethods().Where(method => ReadMethods.Contains(method)).ToList()) + { + ReadMethods.Remove(method).Should().BeTrue(); + try { TakesDomainObject(port, identityDomains).Should().BeTrue($"removing only {method.Name} must expose its typed key"); } + finally { ReadMethods.Add(method); } + } + } + + AggregatesWrittenBy(typeof(DataRequestService).GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataSubjectRequest)], "the request executor writes the request root only"); + AggregatesWrittenBy(typeof(DataExportDownloadService).GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataExportTicket)], "the download executor writes the ticket root only"); + AggregatesWrittenBy(typeof(DataRequestFailureReconciler).GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataSubjectRequest)]); + var handlers = typeof(DataRequestService).Assembly.GetTypes() + .Where(type => type.Namespace == typeof(DataRequestService).Namespace && IsMessageHandler(type) + && type != typeof(DataExportJobHandlers)) + .ToList(); + handlers.Should().HaveCount(14, "the fourteen live-session data-request operations each have one thin handler"); + foreach (var handler in handlers) + { + var parameters = handler.GetConstructors().Single().GetParameters().Select(parameter => parameter.ParameterType).ToList(); + parameters.Should().HaveCount(2).And.Contain(typeof(LiveDataRequestAdmission), handler.Name); + parameters.Should().ContainSingle(type => type == typeof(DataRequestService) || type == typeof(DataExportDownloadService), + $"{handler.Name} delegates only to one countable single-root executor"); + } } /// Exercise the same handler predicate and constructor scan as production. @@ -331,6 +377,12 @@ private static bool IsTypedId(Type type) => type.GetInterfaces().Any(contract => typeof(IInvitationAcceptanceReadStore).GetMethod(nameof(IInvitationAcceptanceReadStore.ReadResultAsync))!, typeof(IInvitationAcceptanceReadStore).GetMethod(nameof(IInvitationAcceptanceReadStore.LockInvitationAsync))!, typeof(IInvitationAcceptanceReadStore).GetMethod(nameof(IInvitationAcceptanceReadStore.ReadFinalAsync))!, + typeof(IDataRequestReader).GetMethod(nameof(IDataRequestReader.FindAsync))!, + typeof(IDataRequestReader).GetMethod(nameof(IDataRequestReader.ReadArtifactsAsync))!, + typeof(IDataRequestReader).GetMethod(nameof(IDataRequestReader.FindArtifactLockedAsync))!, + typeof(IDataRequestReader).GetMethod(nameof(IDataRequestReader.FindMembershipSubjectAsync))!, + typeof(IDataRequestJobPhaseReader).GetMethod(nameof(IDataRequestJobPhaseReader.ReadAsync))!, + typeof(IDataRequestJobPhaseReader).GetMethod(nameof(IDataRequestJobPhaseReader.ReadManyAsync))!, ]; private interface IIdOnlyWriteProbe { Task DeleteAsync(CourseId id); } diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.DescriptorInterpreter.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.DescriptorInterpreter.cs index 9ce7f96e..f771d1d6 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.DescriptorInterpreter.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.DescriptorInterpreter.cs @@ -20,7 +20,7 @@ private static IEnumerable DescriptorRelationOffenders(TypeDefinition de var request = endpoint.Request.Assembly.GetName().Name + ":" + endpoint.Request.FullName; var value = new RequestValue(request); if (EvaluateDescriptor(descriptor, "For", shape.Operation, map) != new Evaluation(true, - new DescriptorValue(shape.Operation, request, shape.Kind, shape.Operation is 7 or 11 or 15))) + new DescriptorValue(shape.Operation, request, shape.Kind, Creates(shape.Operation)))) yield return "Unexpected protected descriptor: exact enum-to-request relation " + shape.Name; if (EvaluateDescriptor(descriptor, "OperationFor", value, map) != new Evaluation(true, shape.Operation)) yield return "Unexpected protected descriptor: exact request-to-enum relation " + shape.Name; diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs index faad4e8c..127393b4 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs @@ -34,8 +34,17 @@ private sealed record ProtectedShape(int Operation, string Name, int Kind, strin new(21, "SetOwnCustomFields", 0, "Membership", "ExpectedVersion"), new(22, "GrantOwnFieldConsent", 7, "MembershipFieldConsent", null), new(23, "WithdrawOwnFieldConsent", 7, "MembershipFieldConsent", null), + new(24, "CreateOwnDataExport", 8, "DataSubjectRequest", null), + new(25, "CreateDataExportForSubject", 8, "DataSubjectRequest", null), + new(26, "CancelOwnDataRequest", 8, "DataSubjectRequest", "ExpectedVersion"), + new(27, "CancelDataRequest", 8, "DataSubjectRequest", "ExpectedVersion"), + new(28, "RevokeOwnDataExport", 8, "DataSubjectRequest", "ExpectedArtifactVersion"), + new(29, "RevokeDataExport", 8, "DataSubjectRequest", "ExpectedArtifactVersion"), ]; + /// The keyed creations: the three 201 creations and ADR-0106 § 10's two 202 data-request creations. + private static bool Creates(int operation) => operation is 7 or 11 or 15 or 24 or 25; + private static readonly Lazy ProtectedSourceBaseline = new(() => ProtectedSourceOffenders( File.ReadAllText(Path.Combine(RepositoryPaths.BackendSrc(), "LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs")), File.ReadAllText(Path.Combine(RepositoryPaths.BackendSrc(), "LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs"))).ToArray()); @@ -63,7 +72,7 @@ private static IEnumerable DescriptorOffenders(Dictionary entry.Request.FullName == request.FullName && entry.ProtectedOperation is not null); var shape = ProtectedShapes.SingleOrDefault(item => item.Operation == endpoint?.ProtectedOperation); if (shape is null || Integer(Argument(factory, creation, 2)) != shape.Kind - || Integer(Argument(factory, creation, 3)) != (shape.Operation is 7 or 11 or 15 ? 1 : 0)) + || Integer(Argument(factory, creation, 3)) != (Creates(shape.Operation) ? 1 : 0)) yield return "Unexpected protected descriptor: target kind/creation mismatch for " + request.FullName; } var expected = Endpoints.Where(entry => entry.ProtectedOperation is not null) @@ -108,7 +117,7 @@ private static IEnumerable ProtectedSourceOffenders(string descriptorSou var request = Endpoints.Single(entry => entry.ProtectedOperation == shape.Operation).Request.Name; return name switch { - "For" => "ProtectedAdministrationOperation." + shape.Name + "=>new(operation,typeof(" + request + "),IdempotencyReplayTargetKind." + shape.Target + (shape.Operation is 7 or 11 or 15 ? ",true" : "") + ")", + "For" => "ProtectedAdministrationOperation." + shape.Name + "=>new(operation,typeof(" + request + "),IdempotencyReplayTargetKind." + shape.Target + (Creates(shape.Operation) ? ",true" : "") + ")", "OperationFor" => request + "=>ProtectedAdministrationOperation." + shape.Name, _ => request + (shape.Version is null ? "=>null" : "command=>command." + shape.Version) }; @@ -116,7 +125,9 @@ private static IEnumerable ProtectedSourceOffenders(string descriptorSou if (name == "ExpectedVersion") expected = expected.Where(arm => arm is not ("CreateManagedOrganizationCommand=>null" or "CreateInvitationCommand=>null")) .Where(arm => arm is not ("RegisterCustomFieldDefinitionCommand=>null" or "GrantOwnMembershipFieldConsentCommand=>null" or "WithdrawOwnMembershipFieldConsentCommand=>null")) .Append("CreateManagedOrganizationCommandorCreateInvitationCommand=>null") - .Append("RegisterCustomFieldDefinitionCommandorGrantOwnMembershipFieldConsentCommandorWithdrawOwnMembershipFieldConsentCommand=>null").ToArray(); + .Append("RegisterCustomFieldDefinitionCommandorGrantOwnMembershipFieldConsentCommandorWithdrawOwnMembershipFieldConsentCommand=>null") + .Where(arm => arm is not ("CreateOwnDataExportCommand=>null" or "CreateDataExportForSubjectCommand=>null")) + .Append("CreateOwnDataExportCommandorCreateDataExportForSubjectCommand=>null").ToArray(); var fallback = name switch { "For" => "_=>thrownewArgumentOutOfRangeException(nameof(operation))", @@ -148,6 +159,9 @@ private static IEnumerable ProtectedSourceOffenders(string descriptorSou 21 => "Membership(awaitsender.Send(command,cancellationToken),null)", 22 => "Consent(awaitsender.Send(command,cancellationToken),true)", 23 => "Consent(awaitsender.Send(command,cancellationToken),false)", + 24 or 25 => "DataRequest(awaitsender.Send(command,cancellationToken),null)", + 26 or 27 => "DataRequest(awaitsender.Send(command,cancellationToken),command.RequestId)", + 28 or 29 => "Artifact(awaitsender.Send(command,cancellationToken),command.RequestId)", _ => throw new InvalidOperationException("Unknown expected protected operation") }; return request + "command=>" + result; diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs index b458c984..3a15d983 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs @@ -251,6 +251,43 @@ private sealed record Endpoint(string Controller, string Action, string Verb, st new("LearnStack.Api.Tenancy.InvitationPolicyController", "Set", "PUT", "tenancy/settings/invitation-policy", null, "SetTenantInvitationLifetime", typeof(LearnStack.Modules.Tenancy.Application.Contracts.Settings.SetTenantInvitationLifetimeCommand), "LearnStackOperation:tenancy.setting.write_invitation_lifetime", typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 14, new(OperationClass.Must, OperationType.Update, "tenancy.setting.write", typeof(LearnStack.Modules.Tenancy.Domain.TenantSetting))), + // ADR-0106, ADR-0107 § 4: the subject's key-less own data requests and the administrator's status-only view. + new("LearnStack.Api.Identity.OwnDataRequestsController", "Create", "POST", "identity/me/data-requests", "exports", + "CreateOwnDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateOwnDataExportCommand), "LearnStackOperation:identity.data_request.create_own_export", + typeof(LearnStack.Api.Identity.DataRequestAcceptedResponse), 202, 24, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_export", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.OwnDataRequestsController", "List", "GET", "identity/me/data-requests", null, + "ListOwnDataRequests", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListOwnDataRequestsQuery), "LearnStackOperation:identity.data_request.list_own", + typeof(LearnStack.Api.Identity.OwnDataRequestPage), 200, null, new()), + new("LearnStack.Api.Identity.OwnDataRequestsController", "Get", "GET", "identity/me/data-requests", "{id}", + "GetOwnDataRequest", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.GetOwnDataRequestQuery), "LearnStackOperation:identity.data_request.read_own", + typeof(LearnStack.Api.Identity.OwnDataRequestResponse), 200, null, new()), + new("LearnStack.Api.Identity.OwnDataRequestsController", "Cancel", "POST", "identity/me/data-requests", "{id}/cancellations", + "CancelOwnDataRequest", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CancelOwnDataRequestCommand), "LearnStackOperation:identity.data_request.cancel_own", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 26, new(OperationClass.Must, OperationType.Update, "identity.data_request.cancel", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.OwnDataRequestsController", "Revoke", "POST", "identity/me/data-requests", "{id}/artifact/revocations", + "RevokeOwnDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.RevokeOwnDataExportCommand), "LearnStackOperation:identity.data_request.revoke_own_export", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 28, new(OperationClass.Must, OperationType.Delete, "identity.data_export.revoke", typeof(LearnStack.Modules.Identity.Domain.DataExportArtifact))), + new("LearnStack.Api.Identity.OwnDataExportTicketsController", "MintTicket", "POST", "identity/me/data-requests", "{id}/artifact/tickets", + "MintOwnDataExportTicket", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.MintOwnDataExportTicketCommand), "LearnStackOperation:identity.data_request.mint_export_ticket", + typeof(LearnStack.Api.Identity.DataExportTicketResponse), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_export.mint_ticket", typeof(LearnStack.Modules.Identity.Domain.DataExportTicket))), + new("LearnStack.Api.Identity.OwnDataExportChunksController", "ReadChunk", "POST", "identity/me/data-requests", "{id}/artifact/chunks", + "ReadOwnDataExportChunk", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ReadOwnDataExportChunkCommand), "LearnStackOperation:identity.data_request.read_export_chunk", + typeof(LearnStack.Api.Identity.DataExportChunkResponse), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_export.read_chunk", typeof(LearnStack.Modules.Identity.Domain.DataExportTicket))), + new("LearnStack.Api.Identity.DataRequestsController", "Create", "POST", "identity/data-requests", "exports", + "CreateDataExportForSubject", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateDataExportForSubjectCommand), "LearnStackOperation:identity.data_request.create_export", + typeof(LearnStack.Api.Identity.DataRequestAcceptedResponse), 202, 25, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_export", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestsController", "List", "GET", "identity/data-requests", null, + "ListDataRequests", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListDataRequestsQuery), "LearnStackOperation:identity.data_request.list", + typeof(LearnStack.Api.Identity.DataRequestPage), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_request.list", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestsController", "Get", "GET", "identity/data-requests", "{id}", + "GetDataRequest", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.GetDataRequestQuery), "LearnStackOperation:identity.data_request.read", + typeof(LearnStack.Api.Identity.DataRequestResponse), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_request.read", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestsController", "Cancel", "POST", "identity/data-requests", "{id}/cancellations", + "CancelDataRequest", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CancelDataRequestCommand), "LearnStackOperation:identity.data_request.cancel", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 27, new(OperationClass.Must, OperationType.Update, "identity.data_request.cancel", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestsController", "Revoke", "POST", "identity/data-requests", "{id}/artifact/revocations", + "RevokeDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.RevokeDataExportCommand), "LearnStackOperation:identity.data_request.revoke_export", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 29, new(OperationClass.Must, OperationType.Delete, "identity.data_export.revoke", typeof(LearnStack.Modules.Identity.Domain.DataExportArtifact))), // ADR-0099: the protected federation operations hand off to the one runner, without Idempotency-Key. new("LearnStack.Api.Identity.FederationController", "Get", "GET", "identity/federation", null, "GetFederationConnection", typeof(LearnStack.Modules.Identity.Application.Contracts.Federation.GetFederationConnectionQuery), "LearnStackOperation:identity.federation.read", @@ -305,9 +342,9 @@ public void Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly() => WithProdu errors.Should().BeEmpty( "Fix: retain the exact ADR-0064/0076 reads and ADR-0078/0079 finite entry/administration union; all findings: {0}", string.Join("\n", errors)); // The totals Standard 21 publishes for this rule; Violations binds the production surface to this literal census. - Endpoints.Should().HaveCount(72, "the census closes the surface at 72 MVC actions"); - Endpoints.Select(endpoint => endpoint.Request).Distinct().Should().HaveCount(67, - "Standard 21 publishes 67 distinct IRequest roots for the 72 actions"); + Endpoints.Should().HaveCount(84, "the census closes the surface at 84 MVC actions"); + Endpoints.Select(endpoint => endpoint.Request).Distinct().Should().HaveCount(79, + "Standard 21 publishes 79 distinct IRequest roots for the 84 actions"); }); /// ADR-0064's controls mutate the same production route census. @@ -459,7 +496,7 @@ public void Authenticated_http_census_follows_production_helpers_and_nested_disp var map = Types(modules).ToDictionary(Key, StringComparer.Ordinal); var account = map.Values.Single(type => type.FullName == Account); var handlers = HandlerRoots(map).ToArray(); - handlers.Should().HaveCount(46, "all finite HTTP requests have real production handlers; the seven invitation operations and three policy operations share two additional handler classes, and the federation commands share one handler class beside its two query handlers"); + handlers.Should().HaveCount(58, "all finite HTTP requests have real production handlers; the seven invitation operations and three policy operations share two additional handler classes, the federation commands share one handler class beside its two query handlers, and each of the twelve data-request requests has its own thin handler"); Violations(modules, facts).Should().BeEmpty(); AssertPolicyMetadataControls(modules, facts); AssertControllerMetadataControls(modules, facts); diff --git a/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs index 6402323c..8dfb246f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs @@ -1,3 +1,4 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using FluentAssertions; using LearnStack.Api.Idempotency; using LearnStack.Application.Authorization; @@ -37,6 +38,7 @@ public sealed partial class IdempotencyConventionTests typeof(ReadRoleReceiptQuery), typeof(ReadOrganizationReceiptQuery), typeof(ReadDefaultOrganizationReceiptQuery), typeof(ReadInvitationReceiptQuery), typeof(ReadInvitationPolicyReceiptQuery), typeof(ReadCustomFieldDefinitionReceiptQuery), typeof(ReadOwnGrantedFieldConsentReceiptQuery), typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), + typeof(ReadOwnDataRequestReceiptQuery), typeof(ReadDataRequestReceiptQuery), ]; [Fact] @@ -49,6 +51,7 @@ public void Protected_Idempotent_Replay_Reauthorizes_Original_Target() { catalog.TryGet(receipt, out var policy).Should().BeTrue("Fix: classify every receipt read explicitly"); policy.Kind.Should().Be(receipt == typeof(ReadOwnWithdrawnFieldConsentReceiptQuery) ? OperationPolicyKind.OwnConsentEntry + : receipt == typeof(ReadOwnDataRequestReceiptQuery) ? OperationPolicyKind.OwnDataRequest : receipt == typeof(ReadOwnMembershipProfileReceiptQuery) || receipt == typeof(ReadInvitationPolicyReceiptQuery) || receipt == typeof(ReadOwnGrantedFieldConsentReceiptQuery) ? OperationPolicyKind.OwnMembershipRead : OperationPolicyKind.Protected); policy.RequiresOrglessWrite.Should().BeFalse("disclosure is not the original mutation's eligibility"); @@ -225,6 +228,12 @@ private static string[] DispatcherOffenders(ModuleDefinition[] modules) [ProtectedAdministrationOperation.SetOwnCustomFields] = typeof(ReadOwnMembershipProfileReceiptQuery), [ProtectedAdministrationOperation.GrantOwnFieldConsent] = typeof(ReadOwnGrantedFieldConsentReceiptQuery), [ProtectedAdministrationOperation.WithdrawOwnFieldConsent] = typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), + [ProtectedAdministrationOperation.CreateOwnDataExport] = typeof(ReadOwnDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CancelOwnDataRequest] = typeof(ReadOwnDataRequestReceiptQuery), + [ProtectedAdministrationOperation.RevokeOwnDataExport] = typeof(ReadOwnDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateDataExportForSubject] = typeof(ReadDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CancelDataRequest] = typeof(ReadDataRequestReceiptQuery), + [ProtectedAdministrationOperation.RevokeDataExport] = typeof(ReadDataRequestReceiptQuery), }; private static string[] AdmissionOffenders(ModuleDefinition[] modules) diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 97dba08a..68b00737 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -33,6 +33,7 @@ public sealed partial class IdentityAuditConventionTests private const string TenancyStorageScope = "LearnStack.Modules.Tenancy.Infrastructure.Persistence.TenancyAdministrationStorageScope"; private const string InvitationAuthorization = "LearnStack.Modules.Identity.Application.Invitations.InvitationAdministrationAuthorization"; private const string FederationAuthorization = "LearnStack.Modules.Identity.Application.Federation.FederationAuthorization"; + private const string DataRequestAuthorization = "LearnStack.Modules.Identity.Application.DataRequests.DataRequestAuthorization"; private const string InvitationPolicyAuthorization = "LearnStack.Modules.Tenancy.Application.Settings.InvitationPolicyHandlers"; private const string InvitationEntrySource = "LearnStack.Api.Authentication.InvitationEntrySource"; private const string InvitationEntryAuthorization = "LearnStack.Modules.Identity.Application.Invitations.InvitationEntryAuthorization"; @@ -74,6 +75,8 @@ private static readonly (string Owner, string Method, int Count)[] CurrentInvoca (InvitationAuthorization, "Matches", 1), (FederationAuthorization, "AdmitAsync", 1), (FederationAuthorization, "Matches", 1), + (DataRequestAuthorization, "AdmitAsync", 1), + (DataRequestAuthorization, "Matches", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (ReadAuthorization, "Current", 1), (ReadAuthorization, "Matches", 1), @@ -131,6 +134,7 @@ private static readonly (string Owner, string Method, int Count)[] CurrentDecisi (InvitationEntryWriteStore, "UpdateAsync", 1), (InvitationAuthorization, "Matches", 1), (FederationAuthorization, "Matches", 1), + (DataRequestAuthorization, "Matches", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (ReadAuthorization, "Matches", 1), (NavigationReader, "Matches", 1), @@ -390,12 +394,14 @@ instruction.Operand is MethodReference target (PolicyOwner, "get_CurrentDataRequestWitness", 1)]); EvidenceCallers(census, errors, callerIndex, "LearnStack.SharedKernel.Audit.IAuthorizationRefusalReporter", "ReportRecheck", [(RoleAuthorization, "ReportRecheck", 1), (MemberAuthorization, "ReportRecheck", 1), (TenancyAuthorization, "RecheckAsync", 1), (ReceiptAuthorization, "RecheckAsync", 1), (ReadAuthorization, "RecheckAsync", 1), - (InvitationAuthorization, "RecheckAsync", 1), (FederationAuthorization, "RecheckAsync", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (CustomFieldAdmission, "RecheckAsync", 1), + (InvitationAuthorization, "RecheckAsync", 1), (FederationAuthorization, "RecheckAsync", 1), (DataRequestAuthorization, "RecheckAsync", 1), + (InvitationPolicyAuthorization, "OwnAsync", 1), (CustomFieldAdmission, "RecheckAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.OwnFieldConsentAuthorization", "AdmitGrantAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.GetOwnMembershipFieldConsentQueryHandler", "AuthorizedAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.ReadOwnGrantedFieldConsentReceiptQueryHandler", "RecheckAsync", 1)]); EvidenceCallers(census, errors, callerIndex, "LearnStack.SharedKernel.Audit.IAuthorizationRefusalReporter", "ReportResourceRefusal", [(RoleAuthorization, "ReportRefusal", 1), (MemberAuthorization, "ReportRefusal", 1), (TenancyAuthorization, "RecheckAsync", 1), (ReceiptAuthorization, "RecheckAsync", 1), (ReadAuthorization, "RecheckAsync", 1), - (InvitationAuthorization, "RecheckAsync", 1), (FederationAuthorization, "RecheckAsync", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (CustomFieldAdmission, "RecheckAsync", 1), + (InvitationAuthorization, "RecheckAsync", 1), (FederationAuthorization, "RecheckAsync", 1), (DataRequestAuthorization, "RecheckAsync", 1), + (InvitationPolicyAuthorization, "OwnAsync", 1), (CustomFieldAdmission, "RecheckAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.OwnFieldConsentAuthorization", "AdmitGrantAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.GetOwnMembershipFieldConsentQueryHandler", "AuthorizedAsync", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.ReadOwnGrantedFieldConsentReceiptQueryHandler", "RecheckAsync", 1)]); foreach (var (type, method, target, name) in new[] diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs index 431a8519..fbdfc527 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -124,6 +124,10 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() // guard requires of every request write; neither admits a Membership. "LearnStack.Modules.Identity.Application.DataRequests.DataExportJobHandlers.ExportAsync", "LearnStack.Modules.Identity.Application.DataRequests.DataRequestFailureReconciler.ReconcileAsync", + // ADR-0106 § 7: creation fences the subject's User and the shared tenant before it judges the one-active rule; + // cancellation holds the shared tenant fence the request guard requires. + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CreateExportAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CancelAsync", ]; // A retained-plan check is not another acquisition: the guards, bounded // reader and two separately confined source/witness pairs must recheck it. @@ -153,6 +157,11 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.SharedKernel.Permissions.SeedPrerequisiteReadWitness.RequireCurrent", "LearnStack.SharedKernel.Permissions.SeedCompletionReadWitness.RequireCurrent", "LearnStack.Modules.Identity.Application.Federation.FederationCommandHandlers.ActAsync", + // The data-request writers recheck their own plan after the authority recheck; the reconciler proves a plan + // the creation path hands it instead of acquiring a second one. + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CreateExportAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CancelAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestFailureReconciler.ReconcileAsync", ]; // Exact set controls detect a missing named site and an unrelated borrower. static bool SameSites(IEnumerable actual, IEnumerable expected) => diff --git a/backend/tests/LearnStack.Tests.Architecture/OperationPermissionConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPermissionConventionTests.cs index 059c5845..7ee413e6 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperationPermissionConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperationPermissionConventionTests.cs @@ -8,6 +8,7 @@ using LearnStack.Modules.Education.Application.Authorization; using LearnStack.Modules.Identity.Application; using LearnStack.Modules.Identity.Application.Contracts.Memberships; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Federation; @@ -98,6 +99,12 @@ public void Permission_Scope_Matches_Resource_Scope() (typeof(GetCustomFieldDefinitionQuery), false, [new([BoundedCustomFieldPermissions.Definition])]), (typeof(ListCustomFieldDefinitionsQuery), false, [new([BoundedCustomFieldPermissions.Definition])]), (typeof(ListCustomFieldDefinitionRevisionsQuery), false, [new([BoundedCustomFieldPermissions.Definition])]), + // ADR-0106 § 4: the administrator data-request operations reuse the invitation pair exactly. + .. new[] + { + typeof(CreateDataExportForSubjectCommand), typeof(ListDataRequestsQuery), typeof(GetDataRequestQuery), + typeof(CancelDataRequestCommand), typeof(RevokeDataExportCommand), typeof(ReadDataRequestReceiptQuery), + }.Select(request => (request, false, new OperationPolicyClause[] { new([membershipAdmin]), new([organizationAdmin]) })), (typeof(ListInvitationsQuery), false, [new([membershipAdmin]), new([organizationAdmin])]), (typeof(GetInvitationQuery), false, [new([membershipAdmin]), new([organizationAdmin])]), (typeof(ListInvitableRolesQuery), false, [new([membershipAdmin]), new([organizationAdmin])]), diff --git a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs index fb4d1147..45fb05b1 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs @@ -27,10 +27,13 @@ public sealed partial class OperationPolicyOwnershipTests private const string InvitationEvaluator = "LearnStack.Modules.Identity.Application.Invitations.InvitationAdministrationAuthorization"; private const string InvitationPolicyEvaluator = "LearnStack.Modules.Tenancy.Application.Settings.InvitationPolicyHandlers"; private const string FederationEvaluator = "LearnStack.Modules.Identity.Application.Federation.FederationAuthorization"; + private const string DataRequestEvaluator = "LearnStack.Modules.Identity.Application.DataRequests.DataRequestAuthorization"; private static readonly (string Type, string Method, string Target, string Name)[] InvitationChecks = [ (InvitationEvaluator, "RecheckAsync", Permissions + "IProtectedOperationAuthorizer", "AuthorizeAsync"), (InvitationPolicyEvaluator, "OwnAsync", Permissions + "IProtectedOperationAuthorizer", "AuthorizeAsync"), + // ADR-0106 § 4: the data-request writers recheck the live invocation under their fences the same way. + (DataRequestEvaluator, "RecheckAsync", Permissions + "IProtectedOperationAuthorizer", "AuthorizeAsync"), ]; private static readonly (string Type, string Method, string Target, string Name)[] MemberChecks = [ @@ -308,7 +311,7 @@ private static List Offenders(Census census) (InvitationEvaluator, "RecheckAsync", 1), (InvitationPolicyEvaluator, "OwnAsync", 1), (DefinitionEvaluator, "RecheckAsync", 1), (OwnConsentEvaluator, "AdmitGrantAsync", 1), (ConsentReceiptEvaluator, "RecheckAsync", 1), (ConsentReadEvaluator, "AuthorizedAsync", 1), - (FederationEvaluator, "RecheckAsync", 1)]); + (FederationEvaluator, "RecheckAsync", 1), (DataRequestEvaluator, "RecheckAsync", 1)]); Exact(Permissions + "IAuthorizationCandidateSource", "ForValidatedScope", [(Coordinator, "ExecuteAsync", 2)]); Exact(Coordinator, "ExecuteRequestAsync", [(AuthorizationBehavior, "Handle", 1)]); Exact(HttpSource, "ForValidatedScope", [(HttpSource, Permissions + "IAuthorizationCandidateSource.ForValidatedScope", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs index d9ff2086..021a92da 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs @@ -216,6 +216,15 @@ public void Observation_registration_control_detects_missing_duplicate_or_replac ObservationRegistrationOffenders(services).Should().NotBeEmpty("duplicate SMTP startup qualification is not another admitted worker"); services.Remove(smtpStartup); ObservationRegistrationOffenders(services).Should().BeEmpty("restoring SMTP qualification restores the clean worker set"); + var exportStartup = services.Single(descriptor => descriptor.ServiceType == typeof(IHostedService) + && HostedAliasIdentity(descriptor) == "LearnStack.Api.Composition.DataExportStartupService"); + services.Remove(exportStartup); + ObservationRegistrationOffenders(services).Should().NotBeEmpty("the mandatory export key-ring qualification startup cannot disappear"); + services.Add(exportStartup); + services.Add(exportStartup); + ObservationRegistrationOffenders(services).Should().NotBeEmpty("duplicate export key-ring qualification is not another admitted worker"); + services.Remove(exportStartup); + ObservationRegistrationOffenders(services).Should().BeEmpty("restoring the export key-ring qualification restores the clean worker set"); services.Remove(worker); ObservationRegistrationOffenders(services).Should().NotBeEmpty("Fix: missing mandatory execution must be detected"); services.Add(worker); @@ -505,6 +514,7 @@ private static SortedSet ObservationRegistrationOffenders(IServiceCollec [typeof(OutboxProcessor).FullName!, typeof(DeliveryProcessor).FullName!, JobHostedService, "LearnStack.Api.Composition.InvitationEmailStartupService", + "LearnStack.Api.Composition.DataExportStartupService", "Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckPublisherHostedService"]); if (workers.Any(descriptor => descriptor.Lifetime != ServiceLifetime.Singleton)) offenders.Add("Mandatory singleton worker registration"); foreach (var type in new[] { typeof(OutboxProcessor), typeof(DeliveryProcessor), typeof(LearnStack.Api.Jobs.BackgroundJobHostedService) }) diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.Enrollment.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.Enrollment.cs index eb659f6f..a3b18693 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.Enrollment.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.Enrollment.cs @@ -277,7 +277,11 @@ private static List EfEnrollmentOffenders(EnrollmentCensus census) "LearnStack.Modules.Identity.Infrastructure.Persistence.FixedSeedIdentityCompletionReader::ReadAsync", "LearnStack.Modules.Identity.Infrastructure.Persistence.SeedIdentityStageReader::HasNoRoleHistoryAsync", "LearnStack.Modules.Identity.Infrastructure.Persistence.FederationConnectionStore::ReadLiveAsync", - "LearnStack.Modules.Identity.Infrastructure.Persistence.FederationConnectionStore::Writable" }.Order(StringComparer.Ordinal), StringComparer.Ordinal) + "LearnStack.Modules.Identity.Infrastructure.Persistence.FederationConnectionStore::Writable", + // ADR-0106 § 4: the data-request adapters run on the request's own tenant owner after authorization. + "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataRequestStore::Admit", + "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataRequestReader::Admit", + "LearnStack.Modules.Identity.Infrastructure.DataRequests.DataExportTicketStore::Admit" }.Order(StringComparer.Ordinal), StringComparer.Ordinal) || reenrollments.Any(site => site.Instruction.OpCode != OpCodes.Call)) errors.Add("Only the exact contextual graph, seed metadata/stage, member/Role, native admission and federation registry readers may reenroll the same tenant owner"); return errors; diff --git a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs new file mode 100644 index 00000000..74249e03 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs @@ -0,0 +1,119 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Contract; + +/// +/// ADR-0106 § 10 and ADR-0107 § 4 wire census: the keyed 202 creations, the conditional keyed mutations, and the ticket +/// operations that are neither keyed nor conditional and carry the ticket only in a body. +/// +public sealed partial class OpenApiContractTests +{ + private enum DataRequestShape { Read, Create, Mutation, Ticket } + + private sealed record DataRequestOperation(string Path, string Method, string Id, DataRequestShape Shape, string Response, string? Body); + + private static readonly DataRequestOperation[] DataRequestOperations = + [ + new("/api/v1/identity/me/data-requests/exports", "post", "CreateOwnDataExport", DataRequestShape.Create, "DataRequestAcceptedResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/me/data-requests", "get", "ListOwnDataRequests", DataRequestShape.Read, "OwnDataRequestPage", null), + new("/api/v1/identity/me/data-requests/{id}", "get", "GetOwnDataRequest", DataRequestShape.Read, "OwnDataRequestResponse", null), + new("/api/v1/identity/me/data-requests/{id}/cancellations", "post", "CancelOwnDataRequest", DataRequestShape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput"), + new("/api/v1/identity/me/data-requests/{id}/artifact/revocations", "post", "RevokeOwnDataExport", DataRequestShape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput"), + new("/api/v1/identity/me/data-requests/{id}/artifact/tickets", "post", "MintOwnDataExportTicket", DataRequestShape.Ticket, "DataExportTicketResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/me/data-requests/{id}/artifact/chunks", "post", "ReadOwnDataExportChunk", DataRequestShape.Ticket, "DataExportChunkResponse", "DataExportChunkInput"), + new("/api/v1/identity/data-requests/exports", "post", "CreateDataExportForSubject", DataRequestShape.Create, "DataRequestAcceptedResponse", "DataExportForSubjectInput"), + new("/api/v1/identity/data-requests", "get", "ListDataRequests", DataRequestShape.Read, "DataRequestPage", null), + new("/api/v1/identity/data-requests/{id}", "get", "GetDataRequest", DataRequestShape.Read, "DataRequestResponse", null), + new("/api/v1/identity/data-requests/{id}/cancellations", "post", "CancelDataRequest", DataRequestShape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput"), + new("/api/v1/identity/data-requests/{id}/artifact/revocations", "post", "RevokeDataExport", DataRequestShape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput"), + ]; + + private static readonly string[] DataRequestSchemaNames = + [ + "DataRequestAcceptedResponse", "DataRequestRetainedResponse", "DataExportTruncationResponse", "DataExportArtifactResponse", + "OwnDataRequestResponse", "OwnDataRequestPage", "DataRequestResponse", "DataRequestPage", "DataExportForSubjectInput", + "DataExportTicketResponse", "DataExportChunkInput", "DataExportChunkResponse", + ]; + + private static List DataRequestContractErrors(JsonNode document) + { + var errors = new List(); + foreach (var group in DataRequestOperations.GroupBy(operation => operation.Path, StringComparer.Ordinal)) + if (document["paths"]?[group.Key] is not JsonObject item + || !item.Select(method => method.Key).ToHashSet(StringComparer.Ordinal).SetEquals(group.Select(operation => operation.Method))) + errors.Add("data-request-operations"); + foreach (var contract in DataRequestOperations) + { + if (document["paths"]?[contract.Path]?[contract.Method] is not JsonObject operation) { errors.Add("data-request-operations"); continue; } + if (operation["operationId"]?.GetValue() != contract.Id) errors.Add("data-request-operations"); + if (operation["security"] is not JsonArray { Count: 1 } security || security[0] is not JsonObject { Count: 1 } requirement + || requirement["TenantBearer"] is not JsonArray { Count: 0 }) errors.Add("data-request-security"); + var parameters = (operation["parameters"]?.AsArray() ?? []).Select(parameter => parameter!["name"]!.GetValue()).ToArray(); + var expected = new List(); + if (contract.Path.Contains("{id}", StringComparison.Ordinal)) expected.Add("id"); + if (contract.Shape == DataRequestShape.Read && !contract.Path.EndsWith("{id}", StringComparison.Ordinal)) expected.AddRange(["cursor", "limit"]); + if (contract.Shape is DataRequestShape.Create or DataRequestShape.Mutation) expected.Add("Idempotency-Key"); + if (contract.Shape == DataRequestShape.Mutation) expected.Add("If-Match"); + if (!parameters.Order(StringComparer.Ordinal).SequenceEqual(expected.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + errors.Add("data-request-parameters:" + contract.Id); + if (parameters.Any(name => name.Contains("ticket", StringComparison.OrdinalIgnoreCase))) errors.Add("data-request-ticket-in-url"); + if ((contract.Body is null) != (operation["requestBody"] is null) + || contract.Body is not null && operation["requestBody"]?["content"]?["application/json"]?["schema"]?["$ref"]?.GetValue() + != "#/components/schemas/" + contract.Body) errors.Add("data-request-body:" + contract.Id); + var status = contract.Shape == DataRequestShape.Create ? "202" : "200"; + var responses = operation["responses"]!.AsObject(); + if (responses[status]?["content"]?["application/json"]?["schema"]?["$ref"]?.GetValue() != "#/components/schemas/" + contract.Response + || responses.Any(response => response.Key is "200" or "201" or "202" && response.Key != status)) + errors.Add("data-request-success:" + contract.Id); + foreach (var (_, response) in responses) + if (response?["headers"]?["Cache-Control"]?["schema"]?["enum"]?[0]?.GetValue() != "no-store") errors.Add("data-request-no-store:" + contract.Id); + var etag = responses[status]?["headers"]?["ETag"]; + if ((contract.Shape is DataRequestShape.Create or DataRequestShape.Mutation + || contract.Shape == DataRequestShape.Read && contract.Path.EndsWith("{id}", StringComparison.Ordinal)) != (etag is not null)) + errors.Add("data-request-etag:" + contract.Id); + if ((contract.Shape == DataRequestShape.Create) != (responses[status]?["headers"]?["Location"] is not null)) + errors.Add("data-request-location:" + contract.Id); + } + foreach (var name in DataRequestSchemaNames) + if (document["components"]?["schemas"]?[name] is not JsonObject schema || schema["additionalProperties"]?.GetValue() != false) + errors.Add("data-request-schema:" + name); + // The subject's receipt names no internal identifier; only the administrator's view names the frozen Memberships. + if (document["components"]?["schemas"]?["OwnDataRequestResponse"]?["properties"]?["membershipIds"] is not null + || document["components"]?["schemas"]?["DataRequestResponse"]?["properties"]?["membershipIds"] is null) + errors.Add("data-request-membership-disclosure"); + // No receipt or artifact view carries a key label or content. + foreach (var name in DataRequestSchemaNames) + if (document["components"]?["schemas"]?[name]?["properties"] is JsonObject properties + && properties.Any(property => property.Key is "keyVersion" or "ciphertext" or "nonce" or "digest" or "subjectUserId")) + errors.Add("data-request-disclosure:" + name); + return errors; + } + + [Fact] + public async Task Data_request_census_refuses_a_keyed_ticket_a_ticket_in_the_url_and_a_missing_precondition() + { + var clean = await Served(); + DataRequestContractErrors(clean).Should().BeEmpty(); + + var keyed = clean.DeepClone(); + keyed["paths"]!["/api/v1/identity/me/data-requests/{id}/artifact/tickets"]!["post"]!["parameters"]!.AsArray() + .Add(new JsonObject { ["name"] = "Idempotency-Key", ["in"] = "header" }); + DataRequestContractErrors(keyed).Should().Contain("data-request-parameters:MintOwnDataExportTicket"); + + var query = clean.DeepClone(); + query["paths"]!["/api/v1/identity/me/data-requests/{id}/artifact/chunks"]!["post"]!["parameters"]!.AsArray() + .Add(new JsonObject { ["name"] = "ticket", ["in"] = "query" }); + DataRequestContractErrors(query).Should().Contain("data-request-ticket-in-url"); + + var unconditional = clean.DeepClone(); + var cancel = unconditional["paths"]!["/api/v1/identity/me/data-requests/{id}/cancellations"]!["post"]!["parameters"]!.AsArray(); + cancel.Remove(cancel.Single(parameter => parameter!["name"]!.GetValue() == "If-Match")); + DataRequestContractErrors(unconditional).Should().Contain("data-request-parameters:CancelOwnDataRequest"); + + var disclosed = clean.DeepClone(); + disclosed["components"]!["schemas"]!["OwnDataRequestResponse"]!["properties"]!["membershipIds"] = new JsonObject { ["type"] = "array" }; + DataRequestContractErrors(disclosed).Should().Contain("data-request-membership-disclosure"); + } +} diff --git a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs index dad13899..3ae84c9a 100644 --- a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs @@ -182,12 +182,13 @@ private static List ContractErrors(JsonNode document) var errors = new List(); var paths = document["paths"]!.AsObject(); if (!paths.Select(path => path.Key).ToHashSet(StringComparer.Ordinal) - .SetEquals(Operations.Keys.Concat(NativeOperations.Keys).Concat(InvitationEntryOperations.Keys).Concat(AdministrationOperations.Select(operation => operation.Path)).Concat(CustomFieldOperations.Select(operation => operation.Path)).Concat(FederationOperations.Select(operation => operation.Path)))) errors.Add("operations"); + .SetEquals(Operations.Keys.Concat(NativeOperations.Keys).Concat(InvitationEntryOperations.Keys).Concat(AdministrationOperations.Select(operation => operation.Path)).Concat(CustomFieldOperations.Select(operation => operation.Path)).Concat(FederationOperations.Select(operation => operation.Path)).Concat(DataRequestOperations.Select(operation => operation.Path)))) errors.Add("operations"); errors.AddRange(NativeContractErrors(document)); errors.AddRange(InvitationEntryContractErrors(document)); errors.AddRange(AdministrationContractErrors(document)); errors.AddRange(CustomFieldContractErrors(document)); errors.AddRange(FederationContractErrors(document)); + errors.AddRange(DataRequestContractErrors(document)); var count = 0; foreach (var (path, ids) in Operations) { @@ -370,7 +371,8 @@ private static List SchemaErrors(JsonNode document) if (!schemas.Select(schema => schema.Key).ToHashSet(StringComparer.Ordinal) .SetEquals(expectedNames.Concat(AccountSchemaNames).Concat(DirectorySchemaNames) .Concat(["IdentitySelfActive", "IdentitySelfMissing", "IdentitySelfState", "NativeSessionScopeAdmission", "SelfContextItem", "SelfContextPage"]) - .Concat(AdministrationSchemas.Keys).Concat(InvitationEntrySchemas.Keys).Concat(CustomFieldSchemaNames).Concat(FederationSchemaNames).Append("AdministrationGrantResponse"))) errors.Add("schema-census"); + .Concat(AdministrationSchemas.Keys).Concat(InvitationEntrySchemas.Keys).Concat(CustomFieldSchemaNames).Concat(FederationSchemaNames) + .Concat(DataRequestSchemaNames).Append("AdministrationGrantResponse"))) errors.Add("schema-census"); errors.AddRange(AdministrationSchemaErrors(document)); errors.AddRange(CustomFieldSchemaErrors(document)); foreach (var (name, descriptor) in Dtos) diff --git a/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs b/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs index f5e751a9..ca03454b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs @@ -19,6 +19,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Federation; using LearnStack.Modules.Tenancy.Application.Authorization; using LearnStack.Modules.Tenancy.Application.Contracts.Account; @@ -120,6 +121,18 @@ private sealed record ExpectedAction(Type Controller, string Action, string Name new(typeof(ConsentSubjectController), "Withdraw", "WithdrawOwnMembershipFieldConsent", "POST", "tenancy/membership-field-consents/withdrawals", typeof(WithdrawOwnMembershipFieldConsentCommand), "tenancy.membership_field_consent.withdraw", Protected: ProtectedAdministrationOperation.WithdrawOwnFieldConsent), new(typeof(OwnFieldConsentController), "Current", "GetOwnMembershipFieldConsent", "GET", "tenancy/membership-field-consents/own", typeof(GetOwnMembershipFieldConsentQuery), "tenancy.membership_field_consent.get_own"), new(typeof(OwnFieldConsentController), "Grant", "GrantOwnMembershipFieldConsent", "POST", "tenancy/membership-field-consents/grants", typeof(GrantOwnMembershipFieldConsentCommand), "tenancy.membership_field_consent.grant", Protected: ProtectedAdministrationOperation.GrantOwnFieldConsent), + new(typeof(OwnDataRequestsController), "Create", "CreateOwnDataExport", "POST", "identity/me/data-requests/exports", typeof(CreateOwnDataExportCommand), "identity.data_request.create_own_export", Protected: ProtectedAdministrationOperation.CreateOwnDataExport), + new(typeof(OwnDataRequestsController), "List", "ListOwnDataRequests", "GET", "identity/me/data-requests", typeof(ListOwnDataRequestsQuery), "identity.data_request.list_own"), + new(typeof(OwnDataRequestsController), "Get", "GetOwnDataRequest", "GET", "identity/me/data-requests/{id}", typeof(GetOwnDataRequestQuery), "identity.data_request.read_own"), + new(typeof(OwnDataRequestsController), "Cancel", "CancelOwnDataRequest", "POST", "identity/me/data-requests/{id}/cancellations", typeof(CancelOwnDataRequestCommand), "identity.data_request.cancel_own", Protected: ProtectedAdministrationOperation.CancelOwnDataRequest), + new(typeof(OwnDataRequestsController), "Revoke", "RevokeOwnDataExport", "POST", "identity/me/data-requests/{id}/artifact/revocations", typeof(RevokeOwnDataExportCommand), "identity.data_request.revoke_own_export", Protected: ProtectedAdministrationOperation.RevokeOwnDataExport), + new(typeof(OwnDataExportTicketsController), "MintTicket", "MintOwnDataExportTicket", "POST", "identity/me/data-requests/{id}/artifact/tickets", typeof(MintOwnDataExportTicketCommand), "identity.data_request.mint_export_ticket"), + new(typeof(OwnDataExportChunksController), "ReadChunk", "ReadOwnDataExportChunk", "POST", "identity/me/data-requests/{id}/artifact/chunks", typeof(ReadOwnDataExportChunkCommand), "identity.data_request.read_export_chunk"), + new(typeof(DataRequestsController), "Create", "CreateDataExportForSubject", "POST", "identity/data-requests/exports", typeof(CreateDataExportForSubjectCommand), "identity.data_request.create_export", Protected: ProtectedAdministrationOperation.CreateDataExportForSubject), + new(typeof(DataRequestsController), "List", "ListDataRequests", "GET", "identity/data-requests", typeof(ListDataRequestsQuery), "identity.data_request.list"), + new(typeof(DataRequestsController), "Get", "GetDataRequest", "GET", "identity/data-requests/{id}", typeof(GetDataRequestQuery), "identity.data_request.read"), + new(typeof(DataRequestsController), "Cancel", "CancelDataRequest", "POST", "identity/data-requests/{id}/cancellations", typeof(CancelDataRequestCommand), "identity.data_request.cancel", Protected: ProtectedAdministrationOperation.CancelDataRequest), + new(typeof(DataRequestsController), "Revoke", "RevokeDataExport", "POST", "identity/data-requests/{id}/artifact/revocations", typeof(RevokeDataExportCommand), "identity.data_request.revoke_export", Protected: ProtectedAdministrationOperation.RevokeDataExport), ]; [Fact] @@ -161,10 +174,10 @@ public async Task Every_actual_built_controller_and_infrastructure_endpoint_has_ var endpoints = Endpoints(app); var catalog = Catalog(); var classifier = new OperationHttpClassifier(catalog); - Assert.Equal(72, ExpectedActions.Length); - Assert.Equal(23, ExpectedActions.Count(expected => expected.Protected is not null)); + Assert.Equal(84, ExpectedActions.Length); + Assert.Equal(29, ExpectedActions.Count(expected => expected.Protected is not null)); var actualActions = endpoints.Where(endpoint => endpoint.Metadata.GetMetadata() is not null).ToArray(); - Assert.Equal(72, actualActions.Length); + Assert.Equal(84, actualActions.Length); Assert.Equal(ExpectedActions.Select(expected => expected.Name).Order(StringComparer.Ordinal), actualActions .Select(endpoint => endpoint.Metadata.GetRequiredMetadata().EndpointName).Order(StringComparer.Ordinal)); foreach (var endpoint in endpoints) @@ -301,7 +314,7 @@ public async Task Actual_protected_MVC_metadata_twins_require_the_same_declared_ var endpoints = Endpoints(app); var classifier = new OperationHttpClassifier(Catalog()); var protectedActions = ExpectedActions.Where(expected => expected.Protected is not null).ToArray(); - Assert.Equal(23, protectedActions.Length); + Assert.Equal(29, protectedActions.Length); foreach (var expected in protectedActions) { var original = Assert.Single(endpoints, endpoint => endpoint.Metadata.GetMetadata()?.EndpointName == expected.Name); @@ -330,7 +343,7 @@ public async Task Actual_protected_MVC_metadata_twins_require_the_same_declared_ Assert.Equal(HttpOperationClassification.Application, classifier.Classify(original, out _)); } var unkeyedActions = ExpectedActions.Where(expected => expected.Protected is null).ToArray(); - Assert.Equal(49, unkeyedActions.Length); + Assert.Equal(55, unkeyedActions.Length); foreach (var expected in unkeyedActions) { var original = Assert.Single(endpoints, endpoint => endpoint.Metadata.GetMetadata()?.EndpointName == expected.Name); diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs index 8f4cd553..93ed7413 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs @@ -51,7 +51,8 @@ private static void AssertActionFilters(ControllerActionDescriptor action) expected.Add(Framework(produces.FullName!, 30, 0, 0) with { Status = approved.Protected is ProtectedAdministrationOperation.CreateOrganization or ProtectedAdministrationOperation.CreateInvitation - or ProtectedAdministrationOperation.RegisterCustomFieldDefinition ? 201 : 200, + or ProtectedAdministrationOperation.RegisterCustomFieldDefinition ? 201 + : approved.Protected is ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CreateDataExportForSubject ? 202 : 200, ResponseType = response }); actual.Should().Equal(expected, "Fix: preserve the exact effective action filters, factories, ordering and declared response metadata"); diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs index 5631e04a..753c6276 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs @@ -18,6 +18,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Roles; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Tenancy.Application.Contracts.Account; using LearnStack.Modules.Tenancy.Application.Contracts.PublicReads; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; @@ -115,6 +116,19 @@ private sealed record SurfaceAction(string Path, string Verb, Type Controller, s new("tenancy/membership-field-consents/withdrawals", "POST", typeof(ConsentSubjectController), "Withdraw", typeof(WithdrawOwnMembershipFieldConsentCommand), typeof(ConsentWithdrawalResponse), "tenancy.membership_field_consent.withdraw", ProtectedAdministrationOperation.WithdrawOwnFieldConsent), new("tenancy/membership-field-consents/own", "GET", typeof(OwnFieldConsentController), "Current", typeof(GetOwnMembershipFieldConsentQuery), typeof(OwnFieldConsentCurrentResponse), "tenancy.membership_field_consent.get_own"), new("tenancy/membership-field-consents/grants", "POST", typeof(OwnFieldConsentController), "Grant", typeof(GrantOwnMembershipFieldConsentCommand), typeof(FieldConsentReceiptResponse), "tenancy.membership_field_consent.grant", ProtectedAdministrationOperation.GrantOwnFieldConsent), + // ADR-0106, ADR-0107 § 4: the subject's own data requests and the administrator's status-only view. + new("identity/me/data-requests/exports", "POST", typeof(OwnDataRequestsController), "Create", typeof(CreateOwnDataExportCommand), typeof(DataRequestAcceptedResponse), "identity.data_request.create_own_export", ProtectedAdministrationOperation.CreateOwnDataExport), + new("identity/me/data-requests", "GET", typeof(OwnDataRequestsController), "List", typeof(ListOwnDataRequestsQuery), typeof(OwnDataRequestPage), "identity.data_request.list_own"), + new("identity/me/data-requests/{id}", "GET", typeof(OwnDataRequestsController), "Get", typeof(GetOwnDataRequestQuery), typeof(OwnDataRequestResponse), "identity.data_request.read_own"), + new("identity/me/data-requests/{id}/cancellations", "POST", typeof(OwnDataRequestsController), "Cancel", typeof(CancelOwnDataRequestCommand), typeof(AdministrationVersionReceipt), "identity.data_request.cancel_own", ProtectedAdministrationOperation.CancelOwnDataRequest), + new("identity/me/data-requests/{id}/artifact/revocations", "POST", typeof(OwnDataRequestsController), "Revoke", typeof(RevokeOwnDataExportCommand), typeof(AdministrationVersionReceipt), "identity.data_request.revoke_own_export", ProtectedAdministrationOperation.RevokeOwnDataExport), + new("identity/me/data-requests/{id}/artifact/tickets", "POST", typeof(OwnDataExportTicketsController), "MintTicket", typeof(MintOwnDataExportTicketCommand), typeof(DataExportTicketResponse), "identity.data_request.mint_export_ticket"), + new("identity/me/data-requests/{id}/artifact/chunks", "POST", typeof(OwnDataExportChunksController), "ReadChunk", typeof(ReadOwnDataExportChunkCommand), typeof(DataExportChunkResponse), "identity.data_request.read_export_chunk"), + new("identity/data-requests/exports", "POST", typeof(DataRequestsController), "Create", typeof(CreateDataExportForSubjectCommand), typeof(DataRequestAcceptedResponse), "identity.data_request.create_export", ProtectedAdministrationOperation.CreateDataExportForSubject), + new("identity/data-requests", "GET", typeof(DataRequestsController), "List", typeof(ListDataRequestsQuery), typeof(DataRequestPage), "identity.data_request.list"), + new("identity/data-requests/{id}", "GET", typeof(DataRequestsController), "Get", typeof(GetDataRequestQuery), typeof(DataRequestResponse), "identity.data_request.read"), + new("identity/data-requests/{id}/cancellations", "POST", typeof(DataRequestsController), "Cancel", typeof(CancelDataRequestCommand), typeof(AdministrationVersionReceipt), "identity.data_request.cancel", ProtectedAdministrationOperation.CancelDataRequest), + new("identity/data-requests/{id}/artifact/revocations", "POST", typeof(DataRequestsController), "Revoke", typeof(RevokeDataExportCommand), typeof(AdministrationVersionReceipt), "identity.data_request.revoke_export", ProtectedAdministrationOperation.RevokeDataExport), new("public/sign-in", "GET", typeof(PublicSignInController), "Get", typeof(GetPublicSignInQuery), typeof(PublicSignIn)), new("public/sign-in", "HEAD", typeof(PublicSignInController), "Head", typeof(GetPublicSignInQuery), typeof(void)), // ADR-0099: the federation controller holds only FederationOperationRunner; the census observes the runner's sends. @@ -131,7 +145,8 @@ private sealed record SurfaceAction(string Path, string Verb, Type Controller, s new("identity/federation/resumption", "POST", typeof(FederationController), "Resume", typeof(ResumeFederationOperationCommand), typeof(FederationOperationResponse), "identity.federation.resume"), ]; private static readonly Type[] ContextControllers = - [typeof(MembershipsController), typeof(OwnMembershipController), typeof(RolesController), typeof(OrganizationsController), typeof(DefaultOrganizationController), typeof(InvitationsController), typeof(InvitationPolicyController), typeof(MembershipCustomFieldsController), typeof(ConsentSubjectController), typeof(OwnFieldConsentController)]; + [typeof(MembershipsController), typeof(OwnMembershipController), typeof(RolesController), typeof(OrganizationsController), typeof(DefaultOrganizationController), typeof(InvitationsController), typeof(InvitationPolicyController), typeof(MembershipCustomFieldsController), typeof(ConsentSubjectController), typeof(OwnFieldConsentController), + typeof(OwnDataRequestsController), typeof(DataRequestsController)]; private const string CensusTarget = "018f4d40-0000-7000-8000-000000000011"; private static SurfaceAction Approved(ControllerActionDescriptor action) => ApprovedActions.Single(expected => @@ -315,7 +330,7 @@ private static void AssertEndpointAuthorization(ControllerActionDescriptor actio private static void AssertActionInventory(IEnumerable actions) { var actual = actions.ToArray(); - actual.Should().HaveCount(72); + actual.Should().HaveCount(84); actual.Select(action => action.ControllerTypeInfo.FullName + "." + action.MethodInfo.Name).Order(StringComparer.Ordinal) .Should().Equal(ApprovedActions.Select(expected => expected.Controller.FullName + "." + expected.Action).Order(StringComparer.Ordinal), "every convention must reach exactly the approved controller/action multiset"); @@ -451,7 +466,10 @@ private static async Task DispatchedRequest(ControllerActionDescriptor act context.Request.QueryString = new QueryString("?membershipId=" + CensusTarget + "&definitionId=" + CensusTarget + "&definitionVersion=1"); var body = expected.Protected is { } operation ? CensusBody(operation) : controllerType == typeof(NativeSessionAdmissionController) ? "{}" - : controllerType == typeof(FederationController) ? FederationCensusBody(expected.Action) : string.Empty; + : controllerType == typeof(FederationController) ? FederationCensusBody(expected.Action) + : controllerType == typeof(OwnDataExportTicketsController) ? "{}" + : controllerType == typeof(OwnDataExportChunksController) + ? "{\"ticket\":\"" + new string('A', 43) + "\",\"index\":0}" : string.Empty; using var input = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body)); context.Request.Body = input; context.Request.ContentLength = input.Length; @@ -463,7 +481,8 @@ private static async Task DispatchedRequest(ControllerActionDescriptor act context.Request.Headers["Idempotency-Key"] = "census-command-key"; if (expected.Protected is not (ProtectedAdministrationOperation.CreateOrganization or ProtectedAdministrationOperation.CreateInvitation or ProtectedAdministrationOperation.RegisterCustomFieldDefinition or ProtectedAdministrationOperation.GrantOwnFieldConsent - or ProtectedAdministrationOperation.WithdrawOwnFieldConsent)) context.Request.Headers.IfMatch = "\"7\""; + or ProtectedAdministrationOperation.WithdrawOwnFieldConsent or ProtectedAdministrationOperation.CreateOwnDataExport + or ProtectedAdministrationOperation.CreateDataExportForSubject)) context.Request.Headers.IfMatch = "\"7\""; } // Federation mutations carry no Idempotency-Key; the connection revision converges them. Configure without // If-Match is the first configuration, the strictest closed input. @@ -569,6 +588,10 @@ public Task GetLimitAsync(LearnStack.SharedKernel.Entitlements.LimitKey ke ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministrationOperation.SetOwnCustomFields => "{\"set\":[],\"remove\":[]}", ProtectedAdministrationOperation.GrantOwnFieldConsent => "{\"definitionId\":\"" + CensusTarget + "\",\"definitionVersion\":1,\"noticeLocale\":\"en\",\"expectedNoticeHash\":\"" + new string('a', 64) + "\",\"expectedSequence\":0,\"expectedEvidenceId\":null,\"confirmed\":true}", ProtectedAdministrationOperation.WithdrawOwnFieldConsent => "{}", + ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CancelOwnDataRequest + or ProtectedAdministrationOperation.RevokeOwnDataExport or ProtectedAdministrationOperation.CancelDataRequest + or ProtectedAdministrationOperation.RevokeDataExport => "{}", + ProtectedAdministrationOperation.CreateDataExportForSubject => "{\"membershipId\":\"" + CensusTarget + "\"}", _ => throw new InvalidOperationException("Unclassified protected census input"), }; @@ -584,8 +607,8 @@ private sealed class CensusTenantContext : ITenantContext private static void AssertUnion(IEnumerable actual) { - ApprovedActions.Should().HaveCount(72); - ApprovedActions.Count(expected => expected.Protected is not null).Should().Be(23); + ApprovedActions.Should().HaveCount(84); + ApprovedActions.Count(expected => expected.Protected is not null).Should().Be(29); ApprovedActions.Count(expected => expected.Controller == typeof(FederationController)).Should().Be(11); ApprovedActions.Count(expected => expected.Policy is null).Should().Be(10, "eight public site and course reads plus the sign-in GET and HEAD"); ApprovedActions.Where(expected => expected.Reads is not null).Select(expected => expected.Action) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs index 7dc8716c..f3520a40 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs @@ -256,7 +256,7 @@ public async Task A_dead_export_job_reads_as_failed_and_the_reconciler_stores_it { var (reconciler, reader, store) = Reconciler(scope); var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; - (await reader.ReadAsync(loaded, CancellationToken.None)).Should().Be(DataRequestJobPhase.Pending); + (await reader.ReadAsync(loaded.Id, loaded.Kind, CancellationToken.None)).Should().Be(DataRequestJobPhase.Pending); DataRequestFailureReconciler.EffectiveStatus(loaded, DataRequestJobPhase.Pending).Should().Be(DataRequestStatus.Requested); (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().BeFalse("a live job may still finish"); await scope.Frame.FailAsync(); @@ -270,7 +270,7 @@ await SchemaQueries.ExecuteAsync(dispatcher, null, { var (reconciler, reader, store) = Reconciler(scope); var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; - var phase = await reader.ReadAsync(loaded, CancellationToken.None); + var phase = await reader.ReadAsync(loaded.Id, loaded.Kind, CancellationToken.None); phase.Should().Be(DataRequestJobPhase.Dead); DataRequestFailureReconciler.EffectiveStatus(loaded, phase).Should().Be(DataRequestStatus.Failed, "the receipt shows failed without writing"); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs new file mode 100644 index 00000000..aaabdae3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs @@ -0,0 +1,219 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.Tools.Seeder; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataRequestHttpTests +{ + [Fact] + public async Task A_tenant_administrator_files_an_export_for_a_member_sees_status_and_counts_only_and_never_a_ticket() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var admin = proof.Token(EnglishAdmin, English); + var learner = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var body = JsonSerializer.Serialize(new { membershipId = LearnerMembership }); + + // Never for oneself through this path. + using (var self = await SendAsync(client, admin, AdminPath + "/exports", "POST", + JsonSerializer.Serialize(new { membershipId = SeedData.IdentityMemberships[0].MembershipId }), key: Key())) + await ProblemAsync(self, HttpStatusCode.Conflict, "business_rule_violation"); + // A Membership of another tenant is absent. + using (var foreign = await SendAsync(client, admin, AdminPath + "/exports", "POST", + JsonSerializer.Serialize(new { membershipId = SeedData.IdentityMemberships[2].MembershipId }), key: Key())) + await ProblemAsync(foreign, HttpStatusCode.NotFound, "not_found"); + + var (id, _) = await FileExportAsync(client, admin, path: AdminPath + "/exports", body: body); + var detail = await ReceiptAsync(client, admin, id, AdminPath); + detail.GetProperty("origin").GetString().Should().Be("administrator"); + detail.GetProperty("requestedByYou").GetBoolean().Should().BeTrue(); + detail.GetProperty("membershipIds").EnumerateArray().Select(item => item.GetString()).Should().Equal(LearnerMembership.ToString("D")); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.read", id.ToString("D"))).Should().Be(1, + "an administrator's read of another person's request is a MUST read-sensitive row"); + using (var page = await SendAsync(client, admin, AdminPath)) + (await JsonAsync(page)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(id.ToString("D")); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.list")).Should().Be(1); + + // The subject sees the request on their own page and may cancel it; the one-active rule spans requesters. + var own = await ReceiptAsync(client, learner, id); + own.GetProperty("origin").GetString().Should().Be("administrator"); + using (var conflict = await SendAsync(client, learner, OwnPath + "/exports", "POST", "{}", key: Key())) + await ProblemAsync(conflict, HttpStatusCode.Conflict, "business_rule_violation"); + + await RunExportAsync(proof, tenant, null, id); + var completed = await ReceiptAsync(client, admin, id, AdminPath); + completed.GetProperty("status").GetString().Should().Be("completed"); + completed.GetProperty("artifact").GetProperty("chunkCount").GetInt32().Should().BeGreaterThan(0); + + // The administrator never gets content: the self path reaches no request about another person. + using (var ticket = await SendAsync(client, admin, OwnPath + "/" + id.ToString("D") + "/artifact/tickets", "POST", "{}")) + await ProblemAsync(ticket, HttpStatusCode.NotFound, "not_found"); + // The subject retrieves it. + var (_, bundle) = await DownloadAsync(client, learner, id); + bundle.Should().NotBeEmpty(); + + // The requesting administrator may revoke what their export produced. + var artifact = completed.GetProperty("artifact"); + using (var revoked = await SendAsync(client, admin, AdminPath + "/" + id.ToString("D") + "/artifact/revocations", "POST", "{}", + version: Version(artifact), key: Key())) + await JsonAsync(revoked); + (await ReceiptAsync(client, learner, id)).GetProperty("artifact").GetProperty("status").GetString().Should().Be("revoked"); + } + + [Fact] + public async Task An_organization_administrator_reaches_only_their_organization_and_a_Revoked_Membership_is_still_a_subject() + { + await using var proof = await CreatePreparedAsync(); + var branch = English.DefaultOrganization.OrganizationId; + var other = English.SecondOrganization.OrganizationId; + // A person who administers the English branch through an Organization-scoped role. + await proof.Database.AddMembershipAsync(English, YogaAdmin, branch, BuiltInRoleKey.OrgAdmin); + var branchMember = await proof.Database.AddMembershipAsync(English, EnglishLearner, branch); + var otherMember = await proof.Database.AddMembershipAsync(English, EnglishLearner, other); + using var client = proof.Client(); + var tenant = English.TenantId.Value; + var branchAdmin = proof.Token(YogaAdmin, English, organization: true, claimedOrganization: branch); + var tenantAdminInBranch = proof.Token(EnglishAdmin, English, organization: true, claimedOrganization: branch); + var tenantAdmin = proof.Token(EnglishAdmin, English); + + // The tenant-wide group's request is invisible to the branch, and the reverse. + var (tenantWide, _) = await FileExportAsync(client, tenantAdmin, path: AdminPath + "/exports", + body: JsonSerializer.Serialize(new { membershipId = LearnerMembership })); + using (var list = await SendAsync(client, branchAdmin, AdminPath)) + (await JsonAsync(list)).GetProperty("items").GetArrayLength().Should().Be(0); + using (var read = await SendAsync(client, branchAdmin, AdminPath + "/" + tenantWide.ToString("D"))) + await ProblemAsync(read, HttpStatusCode.NotFound, "not_found"); + using (var read = await SendAsync(client, tenantAdminInBranch, AdminPath + "/" + tenantWide.ToString("D"))) + await ProblemAsync(read, HttpStatusCode.NotFound, "not_found"); + // A Membership of the tenant-wide group or of another organization is absent to the branch. + foreach (var membership in new[] { LearnerMembership, otherMember }) + { + using var absent = await SendAsync(client, branchAdmin, AdminPath + "/exports", "POST", + JsonSerializer.Serialize(new { membershipId = membership }), key: Key()); + await ProblemAsync(absent, HttpStatusCode.NotFound, "not_found"); + } + + // The branch administrator files in their own group; a tenant administrator in the branch context files there too. + var (branchRequest, _) = await FileExportAsync(client, branchAdmin, path: AdminPath + "/exports", + body: JsonSerializer.Serialize(new { membershipId = branchMember })); + using (var list = await SendAsync(client, branchAdmin, AdminPath)) + (await JsonAsync(list)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(branchRequest.ToString("D")); + using (var list = await SendAsync(client, tenantAdmin, AdminPath)) + (await JsonAsync(list)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(new[] { tenantWide.ToString("D") }, "a tenant-wide context lists only the tenant-wide group"); + // Another administrator did not file it: they read it but cannot cancel it. + var branchReceipt = await ReceiptAsync(client, tenantAdminInBranch, branchRequest, AdminPath); + branchReceipt.GetProperty("requestedByYou").GetBoolean().Should().BeFalse(); + using (var cancel = await SendAsync(client, tenantAdminInBranch, AdminPath + "/" + branchRequest.ToString("D") + "/cancellations", "POST", "{}", + version: Version(branchReceipt), key: Key())) + await ProblemAsync(cancel, HttpStatusCode.NotFound, "not_found"); + + // ADR-0106 § 3: a Membership of any status counts, Revoked included. + await proof.SetMembershipStatusAsync(English, EnglishAdmin, otherMember, "Revoked", other); + var tenantAdminInOther = proof.Token(EnglishAdmin, English, organization: true, claimedOrganization: other); + var (revokedSubject, _) = await FileExportAsync(client, tenantAdminInOther, path: AdminPath + "/exports", + body: JsonSerializer.Serialize(new { membershipId = otherMember })); + await RunExportAsync(proof, tenant, other.Value, revokedSubject); + (await ReceiptAsync(client, tenantAdminInOther, revokedSubject, AdminPath)).GetProperty("status").GetString().Should().Be("completed"); + + // A learner without administration authority reaches no administrator operation. + using (var refused = await SendAsync(client, proof.Token(EnglishLearner, English), AdminPath)) + refused.StatusCode.Should().BeOneOf(HttpStatusCode.Forbidden, HttpStatusCode.NotFound); + } + + [Fact] + public async Task Requests_are_isolated_by_group_by_person_and_by_tenant() + { + await using var proof = await CreatePreparedAsync(); + var branch = English.DefaultOrganization.OrganizationId; + await proof.Database.AddMembershipAsync(English, EnglishLearner, branch); + using var client = proof.Client(); + var tenantWide = proof.Token(EnglishLearner, English); + var inBranch = proof.Token(EnglishLearner, English, organization: true, claimedOrganization: branch); + + var (wide, _) = await FileExportAsync(client, tenantWide); + var (local, _) = await FileExportAsync(client, inBranch); + using (var page = await SendAsync(client, inBranch, OwnPath)) + (await JsonAsync(page)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(new[] { local.ToString("D") }, "an organization context never lists the tenant-wide group's requests"); + using (var page = await SendAsync(client, tenantWide, OwnPath)) + (await JsonAsync(page)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(new[] { wide.ToString("D") }, "and the tenant-wide context never lists an organization's"); + using (var crossed = await SendAsync(client, inBranch, OwnPath + "/" + wide.ToString("D"))) + await ProblemAsync(crossed, HttpStatusCode.NotFound, "not_found"); + + // Another person of the same tenant reaches neither request. + var admin = proof.Token(EnglishAdmin, English); + using (var third = await SendAsync(client, admin, OwnPath + "/" + wide.ToString("D"))) + await ProblemAsync(third, HttpStatusCode.NotFound, "not_found"); + using (var page = await SendAsync(client, admin, OwnPath)) + (await JsonAsync(page)).GetProperty("items").GetArrayLength().Should().Be(0); + using (var cancel = await SendAsync(client, admin, OwnPath + "/" + wide.ToString("D") + "/cancellations", "POST", "{}", + version: "0", key: Key())) + await ProblemAsync(cancel, HttpStatusCode.NotFound, "not_found"); + + // Another tenant reaches nothing: its administrator, on its own host, finds no such request. + using (var foreign = await SendAsync(client, proof.Token(YogaAdmin, SeedData.Yoga), AdminPath + "/" + wide.ToString("D"), + host: SeedData.Yoga.Host)) + await ProblemAsync(foreign, HttpStatusCode.NotFound, "not_found"); + + // A cursor is bound to its operation, actor and group. + using (var paged = await SendAsync(client, tenantWide, OwnPath + "?limit=1")) + { + var info = (await JsonAsync(paged)).GetProperty("pageInfo"); + info.GetProperty("hasNext").GetBoolean().Should().BeFalse(); + } + using (var forged = await SendAsync(client, tenantWide, OwnPath + "?cursor=eyJ2IjoxfQ")) + await ProblemAsync(forged, HttpStatusCode.BadRequest, "validation_failed"); + } + + [Fact] + public async Task Concurrent_creations_for_one_subject_and_group_file_exactly_one_request() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var learner = proof.Token(EnglishLearner, English); + var admin = proof.Token(EnglishAdmin, English); + var body = JsonSerializer.Serialize(new { membershipId = LearnerMembership }); + var attempts = Enumerable.Range(0, 6).Select(index => index % 2 == 0 + ? SendAsync(client, learner, OwnPath + "/exports", "POST", "{}", key: Key()) + : SendAsync(client, admin, AdminPath + "/exports", "POST", body, key: Key())).ToArray(); + var responses = await Task.WhenAll(attempts); + try + { + responses.Count(response => response.StatusCode == HttpStatusCode.Accepted).Should().Be(1); + // The subject's exclusive User fence serializes every creation; a loser is told the slot is taken, or, when it + // waited past the fence's lock timeout, that the dependency is unavailable. Never a second request. + var losers = responses.Where(response => response.StatusCode != HttpStatusCode.Accepted).ToArray(); + foreach (var refused in losers) + { + if (refused.StatusCode == HttpStatusCode.ServiceUnavailable) + { + await ProblemAsync(refused, HttpStatusCode.ServiceUnavailable, "dependency_unavailable"); + continue; + } + + var problem = await ProblemAsync(refused, HttpStatusCode.Conflict, "business_rule_violation"); + problem.GetProperty("errors").GetProperty("$")[0].GetProperty("key").GetString().Should().Be("lockey_request_already_active"); + } + + losers.Should().Contain(response => response.StatusCode == HttpStatusCode.Conflict); + } + finally + { + foreach (var response in responses) response.Dispose(); + } + + (await CountAsync(proof, English.TenantId.Value, null, + "SELECT count(*) FROM public.data_subject_requests WHERE status='requested' AND organization_id IS NULL")).Should().Be(1); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Export.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Export.cs new file mode 100644 index 00000000..d90c3a1f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Export.cs @@ -0,0 +1,123 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.Extensions.DependencyInjection; +using Serilog.Core; +using Serilog.Events; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataRequestHttpTests +{ + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task A_subject_exports_their_own_data_through_the_api_the_job_runtime_and_a_ticketed_download(string scope) + { + await using var proof = await CreatePreparedAsync(); + var organization = scope == "organization" ? English.DefaultOrganization.OrganizationId : (OrganizationId?)null; + if (organization is { } branch) + { + await proof.Database.AddMembershipAsync(English, EnglishLearner, branch); + } + + var logs = new LogCapture(); + using var client = proof.Client(services => services.AddSingleton(logs)); + var token = organization is null ? proof.Token(EnglishLearner, English) + : proof.Token(EnglishLearner, English, organization: true, claimedOrganization: organization); + var tenant = English.TenantId.Value; + var key = Key(); + + var (id, version) = await FileExportAsync(client, token, key); + version.Should().Be("0"); + (await AuditCountAsync(proof, tenant, organization?.Value, "identity.data_request.create_export", id.ToString("D"))).Should().Be(1); + + // An exact-key replay discloses the original request again after a fresh receipt read; it never files a second. + using (var replay = await SendAsync(client, token, OwnPath + "/exports", "POST", "{}", key: key)) + { + var replayed = await JsonAsync(replay, HttpStatusCode.Accepted); + replayed.GetProperty("id").GetString().Should().Be(id.ToString("D")); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + } + + (await CountAsync(proof, tenant, organization?.Value, + "SELECT count(*) FROM public.data_subject_requests WHERE organization_id IS NOT DISTINCT FROM @organization::uuid", + ("organization", (object?)organization?.Value ?? DBNull.Value))).Should().Be(1, "a replay files nothing"); + + // ADR-0106 § 7: one active export per subject and group. + using (var conflict = await SendAsync(client, token, OwnPath + "/exports", "POST", "{}", key: Key())) + { + var problem = await ProblemAsync(conflict, HttpStatusCode.Conflict, "business_rule_violation"); + problem.GetProperty("errors").GetProperty("$")[0].GetProperty("key").GetString().Should().Be("lockey_request_already_active"); + } + + var pending = await ReceiptAsync(client, token, id); + pending.GetProperty("status").GetString().Should().Be("requested"); + pending.GetProperty("origin").GetString().Should().Be("self"); + pending.GetProperty("artifact").ValueKind.Should().Be(JsonValueKind.Null); + pending.TryGetProperty("membershipIds", out _).Should().BeFalse("the subject's receipt names no internal identifier"); + + await RunExportAsync(proof, tenant, organization?.Value, id); + + var completed = await ReceiptAsync(client, token, id); + completed.GetProperty("status").GetString().Should().Be("completed"); + completed.GetProperty("completedAt").GetString().Should().NotBeNull(); + completed.GetProperty("retained").EnumerateArray().Select(item => item.GetProperty("kind").GetString()) + .Should().Contain("request_receipt"); + var artifact = completed.GetProperty("artifact"); + artifact.GetProperty("status").GetString().Should().Be("available"); + artifact.GetProperty("readable").GetBoolean().Should().BeTrue(); + artifact.TryGetProperty("keyVersion", out _).Should().BeFalse("the receipt names no key material or label"); + + using (var list = await SendAsync(client, token, OwnPath)) + { + var page = await JsonAsync(list); + page.GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()).Should().Equal(id.ToString("D")); + } + + var (ticket, bundle) = await DownloadAsync(client, token, id); + using (var document = JsonDocument.Parse(bundle)) + { + document.RootElement.GetProperty("request").GetProperty("id").GetString().Should().Be(id.ToString("D")); + document.RootElement.GetProperty("request").GetProperty("scope").GetString().Should().Be(scope); + document.RootElement.GetProperty("sections").GetProperty("identity").GetProperty("memberships").GetArrayLength().Should().Be(1); + } + + var artifactId = artifact.GetProperty("id").GetString()!; + var chunks = artifact.GetProperty("chunkCount").GetInt32(); + (await AuditCountAsync(proof, tenant, organization?.Value, "identity.data_export.mint_ticket")).Should().Be(1); + (await AuditCountAsync(proof, tenant, organization?.Value, "identity.data_export.read_chunk")).Should().Be(chunks, + "every chunk read is its own MUST row"); + (await CountAsync(proof, tenant, organization?.Value, + "SELECT count(*) FROM public.data_export_tickets WHERE artifact_id=@artifact AND consumed_at IS NOT NULL", + ("artifact", Guid.Parse(artifactId)))).Should().Be(1, "serving the final chunk consumed the ticket"); + + // A consumed cursor reads nothing more; a repeated download mints a new ticket. + using (var reused = await ChunkAsync(client, token, id, ticket, 0)) + await ProblemAsync(reused, HttpStatusCode.NotFound, "not_found"); + var (_, again) = await DownloadAsync(client, token, id); + again.Should().Equal(bundle); + + // Nothing secret or personal reached a log: no ticket, no plaintext, no ciphertext. + var rendered = string.Join('\n', logs.Entries.Select(entry => entry.RenderMessage(System.Globalization.CultureInfo.InvariantCulture) + " " + string.Join(' ', + entry.Properties.Select(property => property.Key + "=" + property.Value)))); + rendered.Should().NotContain(ticket); + rendered.Should().NotContain(Convert.ToBase64String(bundle.AsSpan(0, Math.Min(bundle.Length, 48)))); + + // The receipt and the idempotency row hold no ticket or content. + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.idempotency_keys WHERE convert_from(body, 'UTF8') LIKE '%' || @ticket || '%'", + ("ticket", ticket))).Should().Be(0); + } + + private sealed class LogCapture : ILogEventSink + { + internal ConcurrentQueue Entries { get; } = new(); + public void Emit(LogEvent logEvent) => Entries.Enqueue(logEvent); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Mutations.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Mutations.cs new file mode 100644 index 00000000..ab94a274 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Mutations.cs @@ -0,0 +1,145 @@ +using System.Net; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataRequestHttpTests +{ + [Fact] + public async Task A_requested_export_is_cancelled_only_with_its_current_version_and_its_job_then_completes_as_a_no_op() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var token = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var (id, version) = await FileExportAsync(client, token); + var cancel = OwnPath + "/" + id.ToString("D") + "/cancellations"; + + // If-Match is required, canonical and current. + using (var missing = await SendAsync(client, token, cancel, "POST", "{}", key: Key())) + await ProblemAsync(missing, HttpStatusCode.BadRequest, "validation_failed"); + using (var stale = await SendAsync(client, token, cancel, "POST", "{}", version: (Number(version) + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), key: Key())) + await ProblemAsync(stale, HttpStatusCode.Conflict, "concurrency_conflict"); + + var key = Key(); + string cancelled; + using (var response = await SendAsync(client, token, cancel, "POST", "{}", version: version, key: key)) + { + var receipt = await JsonAsync(response); + receipt.EnumerateObject().Select(property => property.Name).Should().Equal("version"); + cancelled = Version(receipt); + Number(cancelled).Should().Be(Number(version) + 1); + response.Headers.ETag!.Tag.Should().Be("\"" + cancelled + "\""); + } + + using (var replay = await SendAsync(client, token, cancel, "POST", "{}", version: version, key: key)) + { + Version(await JsonAsync(replay)).Should().Be(cancelled, "the replay discloses the original receipt"); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + } + + using (var again = await SendAsync(client, token, cancel, "POST", "{}", version: cancelled, key: Key())) + await ProblemAsync(again, HttpStatusCode.Conflict, "business_rule_violation"); + (await ReceiptAsync(client, token, id)).GetProperty("status").GetString().Should().Be("cancelled"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.cancel", id.ToString("D"))).Should().Be(1); + + await RunExportAsync(proof, tenant, null, id); + var after = await ReceiptAsync(client, token, id); + after.GetProperty("status").GetString().Should().Be("cancelled", "a cancelled request's job is a recorded no-op"); + after.GetProperty("artifact").ValueKind.Should().Be(System.Text.Json.JsonValueKind.Null); + + // A terminal request frees the slot. + await FileExportAsync(client, token); + } + + [Fact] + public async Task Revocation_deletes_the_chunks_at_once_and_an_expired_artifact_is_unreadable_and_cannot_be_revoked() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var token = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + + var (first, _) = await FileExportAsync(client, token); + await RunExportAsync(proof, tenant, null, first); + var artifact = (await ReceiptAsync(client, token, first)).GetProperty("artifact"); + var artifactId = Guid.Parse(artifact.GetProperty("id").GetString()!); + var revoke = OwnPath + "/" + first.ToString("D") + "/artifact/revocations"; + using (var stale = await SendAsync(client, token, revoke, "POST", "{}", version: "99", key: Key())) + await ProblemAsync(stale, HttpStatusCode.Conflict, "concurrency_conflict"); + using (var revoked = await SendAsync(client, token, revoke, "POST", "{}", version: Version(artifact), key: Key())) + Number(Version(await JsonAsync(revoked))).Should().Be(Number(Version(artifact)) + 1, "the receipt carries the artifact's version"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_export_chunks WHERE artifact_id=@artifact", + ("artifact", artifactId))).Should().Be(0, "revocation purges the chunks at once"); + var receipt = (await ReceiptAsync(client, token, first)).GetProperty("artifact"); + receipt.GetProperty("status").GetString().Should().Be("revoked"); + receipt.GetProperty("readable").GetBoolean().Should().BeFalse(); + using (var ticket = await SendAsync(client, token, OwnPath + "/" + first.ToString("D") + "/artifact/tickets", "POST", "{}")) + { + var problem = await ProblemAsync(ticket, HttpStatusCode.Conflict, "business_rule_violation"); + problem.GetProperty("errors").GetProperty("artifact")[0].GetProperty("key").GetString().Should().Be("lockey_data_export_unavailable"); + } + (await AuditCountAsync(proof, tenant, null, "identity.data_export.revoke", artifactId.ToString("D"))).Should().Be(1); + + // A second export, then its artifact moved past its expiry: expiry is a time check whether or not the purge ran. + var (second, _) = await FileExportAsync(client, token); + await RunExportAsync(proof, tenant, null, second); + var current = (await ReceiptAsync(client, token, second)).GetProperty("artifact"); + await BackdateArtifactAsync(proof, tenant, Guid.Parse(current.GetProperty("id").GetString()!)); + var expired = (await ReceiptAsync(client, token, second)).GetProperty("artifact"); + expired.GetProperty("status").GetString().Should().Be("expired", "an artifact past its expiry is displayed expired"); + expired.GetProperty("readable").GetBoolean().Should().BeFalse(); + using (var ticket = await SendAsync(client, token, OwnPath + "/" + second.ToString("D") + "/artifact/tickets", "POST", "{}")) + await ProblemAsync(ticket, HttpStatusCode.Conflict, "business_rule_violation"); + using (var late = await SendAsync(client, token, OwnPath + "/" + second.ToString("D") + "/artifact/revocations", "POST", "{}", + version: Version(expired), key: Key())) + await ProblemAsync(late, HttpStatusCode.Conflict, "business_rule_violation"); + } + + [Fact] + public async Task A_dead_job_reads_as_failed_without_a_write_and_the_next_creation_stores_the_failure_and_files_anew() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var token = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var (id, version) = await FileExportAsync(client, token); + await using (var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.OutboxConnectionString)) + await ExecuteAsync(dispatcher, null, """ + UPDATE background_jobs SET phase='quarantined', quarantine_reason='unknown_outcome' + WHERE definition_key='identity.data_export_tenant.v1' AND tenant_id=@tenant + """, ("tenant", tenant)); + + var shown = await ReceiptAsync(client, token, id); + shown.GetProperty("status").GetString().Should().Be("failed", "the receipt reads failed from the dead job"); + shown.GetProperty("failureReason").GetString().Should().Be("execution_failed"); + Version(shown).Should().Be(version, "displaying failed writes nothing"); + + var (next, _) = await FileExportAsync(client, token); + next.Should().NotBe(id); + var stored = await ReceiptAsync(client, token, id); + stored.GetProperty("status").GetString().Should().Be("failed"); + Number(Version(stored)).Should().Be(Number(version) + 2, "the creation stored requested → fulfilling → failed before filing"); + } + + /// Moves an artifact eight days into the past as the owner, with its guard paused and restored. + private static async Task BackdateArtifactAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid artifact) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_artifacts DISABLE TRIGGER tg_data_export_artifacts_mutation_guard"); + await ScopeAsync(owner, transaction, tenant); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_export_artifacts SET created_at=created_at - interval '8 days', expires_at=expires_at - interval '8 days' + WHERE id=@id + """, ("id", artifact)); + await ExecuteAsync(owner, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_artifacts ENABLE TRIGGER tg_data_export_artifacts_mutation_guard"); + await transaction.CommitAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs new file mode 100644 index 00000000..80fa2abc --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs @@ -0,0 +1,148 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataRequestHttpTests +{ + [Fact] + public async Task A_ticket_reads_only_in_its_own_session_for_its_own_artifact_until_it_expires_and_never_when_tampered() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var session = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var (first, _) = await FileExportAsync(client, session); + await RunExportAsync(proof, tenant, null, first); + + using var minted = await SendAsync(client, session, OwnPath + "/" + first.ToString("D") + "/artifact/tickets", "POST", "{}"); + var ticket = (await JsonAsync(minted)).GetProperty("ticket").GetString()!; + minted.Headers.CacheControl!.NoStore.Should().BeTrue(); + + // Another session of the same person: a different validated credential. + var other = AccountSiteHttpTests.Token(proof.Issuer, English, actor: EnglishLearner.Value, + subject: IdentityPublicReadFixture.FoundationSubject(EnglishLearner), tokenId: "another-session"); + other.Should().NotBe(session); + using (var foreignSession = await ChunkAsync(client, other, first, ticket, 0)) + await ProblemAsync(foreignSession, HttpStatusCode.NotFound, "not_found"); + + // A tampered ticket is a well-formed unknown one; a malformed one never reaches a lookup. + var tampered = (ticket[0] == 'A' ? 'B' : 'A') + ticket[1..]; + using (var forged = await ChunkAsync(client, session, first, tampered, 0)) + await ProblemAsync(forged, HttpStatusCode.NotFound, "not_found"); + using (var malformed = await ChunkAsync(client, session, first, ticket + "=", 0)) + await ProblemAsync(malformed, HttpStatusCode.BadRequest, "validation_failed"); + using (var negative = await ChunkAsync(client, session, first, ticket, -1)) + await ProblemAsync(negative, HttpStatusCode.BadRequest, "validation_failed"); + using (var beyond = await ChunkAsync(client, session, first, ticket, 512)) + await ProblemAsync(beyond, HttpStatusCode.NotFound, "not_found"); + + // A ticket never travels in a URL, and the ticket operations take no key or precondition. + using (var query = await SendAsync(client, session, OwnPath + "/" + first.ToString("D") + "/artifact/chunks?ticket=" + ticket, "POST", + JsonSerializer.Serialize(new { ticket, index = 0 }))) + await ProblemAsync(query, HttpStatusCode.BadRequest, "validation_failed"); + using (var keyed = await SendAsync(client, session, OwnPath + "/" + first.ToString("D") + "/artifact/tickets", "POST", "{}", key: Key())) + await ProblemAsync(keyed, HttpStatusCode.BadRequest, "validation_failed"); + + // The ticket binds its artifact: presented for another request of the same person it is absent. + await using (var app = await OpenAppAsync(proof)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, tenant); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.data_export_tickets WHERE consumed_at IS NULL")) + .Should().Be(1); + } + + var (second, _) = await FileExportAsync(client, session, path: OwnPath + "/exports"); + await RunExportAsync(proof, tenant, null, second); + using (var wrongArtifact = await ChunkAsync(client, session, second, ticket, 0)) + await ProblemAsync(wrongArtifact, HttpStatusCode.NotFound, "not_found"); + + // The second export revoked the first artifact on completion; its ticket reads nothing now. + using (var revoked = await ChunkAsync(client, session, first, ticket, 0)) + await ProblemAsync(revoked, HttpStatusCode.NotFound, "not_found"); + + // An expired ticket refuses although unconsumed. + using var fresh = await SendAsync(client, session, OwnPath + "/" + second.ToString("D") + "/artifact/tickets", "POST", "{}"); + var current = (await JsonAsync(fresh)).GetProperty("ticket").GetString()!; + using (var ok = await ChunkAsync(client, session, second, current, 0)) + await JsonAsync(ok); + await BackdateTicketsAsync(proof, tenant); + using (var late = await ChunkAsync(client, session, second, current, 0)) + await ProblemAsync(late, HttpStatusCode.NotFound, "not_found"); + + // An administrator who files nothing and is not the subject reaches no ticket. + using (var admin = await SendAsync(client, proof.Token(EnglishAdmin, English), OwnPath + "/" + second.ToString("D") + "/artifact/tickets", "POST", "{}")) + await ProblemAsync(admin, HttpStatusCode.NotFound, "not_found"); + } + + [Theory] + [InlineData("identity.data_export.mint_ticket")] + [InlineData("identity.data_export.read_chunk")] + [InlineData("identity.data_request.read")] + public async Task A_disclosure_whose_MUST_audit_row_cannot_be_written_is_refused(string operation) + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var token = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var (id, _) = await FileExportAsync(client, token); + await RunExportAsync(proof, tenant, null, id); + string? ticket = null; + if (operation == "identity.data_export.read_chunk") + { + using var minted = await SendAsync(client, token, OwnPath + "/" + id.ToString("D") + "/artifact/tickets", "POST", "{}"); + ticket = (await JsonAsync(minted)).GetProperty("ticket").GetString(); + } + + await proof.OwnerAsync($$""" + CREATE FUNCTION data_request_audit_refusal() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + IF NEW.operation='{{operation}}' AND NEW.outcome='success' THEN + RAISE EXCEPTION 'fixed data request audit refusal' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER tg_data_request_audit_refusal BEFORE INSERT ON public.audit_log FOR EACH ROW EXECUTE FUNCTION data_request_audit_refusal(); + """); + try + { + using var refused = operation switch + { + "identity.data_export.mint_ticket" => await SendAsync(client, token, OwnPath + "/" + id.ToString("D") + "/artifact/tickets", "POST", "{}"), + "identity.data_export.read_chunk" => await ChunkAsync(client, token, id, ticket!, 0), + _ => await SendAsync(client, proof.Token(EnglishAdmin, English), AdminPath + "/" + id.ToString("D")), + }; + var text = await refused.Content.ReadAsStringAsync(); + refused.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, text); + text.Should().Contain("audit_unavailable"); + text.Should().NotContain("\"ticket\"").And.NotContain("\"bytes\"").And.NotContain("\"status\":\"completed\""); + if (operation == "identity.data_export.mint_ticket") + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_export_tickets")).Should().Be(0, "nothing committed"); + } + finally + { + await proof.OwnerAsync("DROP TRIGGER tg_data_request_audit_refusal ON public.audit_log; DROP FUNCTION data_request_audit_refusal();"); + } + } + + /// Moves every ticket of the tenant past its fifteen minutes as the owner, with its guard paused and restored. + private static async Task BackdateTicketsAsync(IdentityAuthorizationHttpProof proof, Guid tenant) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_tickets DISABLE TRIGGER tg_data_export_tickets_mutation_guard"); + await ScopeAsync(owner, transaction, tenant); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_export_tickets SET created_at=created_at - interval '1 hour', expires_at=expires_at - interval '1 hour' + WHERE consumed_at IS NULL + """); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_tickets ENABLE TRIGGER tg_data_export_tickets_mutation_guard"); + await transaction.CommitAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.cs new file mode 100644 index 00000000..967b1363 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.cs @@ -0,0 +1,221 @@ +using System.Globalization; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0106 and ADR-0107 § 4 through the actual Program, signed provider tokens and real PostgreSQL as +/// learnstack_app: the live-session data-request API end to end, the export job through the actual job runtime, +/// the ticketed download, and every refusal the decision names. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed partial class DataRequestHttpTests(PublicReadFixture parent) +{ + private const string OwnPath = "/api/v1/identity/me/data-requests"; + private const string AdminPath = "/api/v1/identity/data-requests"; + private static readonly SeedTenant English = SeedData.English; + private static readonly Guid LearnerMembership = SeedData.IdentityMemberships[1].MembershipId; + + private async Task CreatePreparedAsync() + { + var proof = await CreateAsync(parent); + try + { + await using var source = ApplicationDataSource.Build(proof.Database.AppConnectionString); + var runner = new SeedAdministrationOriginRunner(context => SeedComposition.Build(source, context, + NullLoggerFactory.Instance, identityAuthority: proof.Database.Registration, + seedOriginAdmission: new FixedSeedAdministrationOriginAdmission())); + (await runner.RunAsync(SeedData.All.Select(tenant => tenant.TenantId))).Should().Be(2); + return proof; + } + catch { await proof.DisposeAsync(); throw; } + } + + private static string Key() => "data-request-" + Guid.NewGuid().ToString("N"); + + private static async Task SendAsync(HttpClient client, string token, string path, string method = "GET", + string? body = null, string? version = null, string? key = null, string? host = null) + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + request.Headers.Host = host ?? English.Host; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + if (version is not null) request.Headers.TryAddWithoutValidation("If-Match", "\"" + version + "\""); + if (key is not null) request.Headers.TryAddWithoutValidation("Idempotency-Key", key); + if (body is not null) request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + return await client.SendAsync(request); + } + + private static async Task JsonAsync(HttpResponseMessage response, HttpStatusCode expected = HttpStatusCode.OK) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(expected, text); + response.Headers.CacheControl?.NoStore.Should().BeTrue(); + using var document = JsonDocument.Parse(text); + return document.RootElement.Clone(); + } + + private static async Task ProblemAsync(HttpResponseMessage response, HttpStatusCode status, string code) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(status, text); + response.Headers.CacheControl?.NoStore.Should().BeTrue(); + using var document = JsonDocument.Parse(text); + document.RootElement.GetProperty("code").GetString().Should().Be(code); + return document.RootElement.Clone(); + } + + /// Files an export through the API and returns its id, after checking the 202 contract. + private static async Task<(Guid Id, string Version)> FileExportAsync(HttpClient client, string token, string? key = null, + string path = OwnPath + "/exports", string body = "{}") + { + using var response = await SendAsync(client, token, path, "POST", body, key: key ?? Key()); + var accepted = await JsonAsync(response, HttpStatusCode.Accepted); + accepted.EnumerateObject().Select(property => property.Name).Should().Equal("id", "kind", "status", "version"); + accepted.GetProperty("kind").GetString().Should().Be("export"); + accepted.GetProperty("status").GetString().Should().Be("requested"); + var id = Guid.Parse(accepted.GetProperty("id").GetString()!); + id.Version.Should().Be(7); + response.Headers.Location!.OriginalString.Should().EndWith("/" + id.ToString("D")); + response.Headers.ETag!.Tag.Should().Be("\"" + accepted.GetProperty("version").GetString() + "\""); + return (id, accepted.GetProperty("version").GetString()!); + } + + private static async Task ReceiptAsync(HttpClient client, string token, Guid id, string path = OwnPath) + { + using var response = await SendAsync(client, token, path + "/" + id.ToString("D")); + var receipt = await JsonAsync(response); + response.Headers.ETag!.Tag.Should().Be("\"" + receipt.GetProperty("version").GetString() + "\""); + return receipt; + } + + /// Runs the request's export job through the actual job runtime of a host on the same database. + private static async Task RunExportAsync(IdentityAuthorizationHttpProof proof, Guid tenant, + Guid? organization, Guid request) + { + var parameters = BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(request), typeof(DataExportJobParameters), + BackgroundJobPayloadKind.Parameters); + Guid job; + await using (var app = await OpenAppAsync(proof)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, tenant, organization); + job = await ScalarAsync(app, transaction, """ + SELECT id FROM public.background_jobs + WHERE definition_key=@definition AND parameters=@parameters AND organization_id IS NOT DISTINCT FROM @organization::uuid + """, ("definition", organization is null ? "identity.data_export_tenant.v1" : "identity.data_export_organization.v1"), + ("parameters", parameters), ("organization", (object?)organization ?? DBNull.Value)); + } + + await using var host = new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", proof.Database.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", proof.Database.OutboxConnectionString); + }); + var executor = host.Services.GetRequiredService(); + var start = await executor.ExecuteAsync(await RoutingClaim.ClaimAsync(proof.Database.OutboxConnectionString, + BackgroundJobId.From(job)), BackgroundJobTestRun.Create()); + start.Outcome.Should().Be(JobStartExecutionOutcome.Started); + var result = await executor.ExecuteBusinessAsync(start.Receipt!, start.Receipt!.Run.OpenBoundary(BackgroundJobCheckpointKind.Transactional)); + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + return result; + } + + private static async Task OpenAppAsync(IdentityAuthorizationHttpProof proof) + { + var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + return app; + } + + /// A count read as the application role inside one group. + private static async Task CountAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, string sql, + params (string Name, object? Value)[] values) + { + await using var app = await OpenAppAsync(proof); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + return await ScalarAsync(app, transaction, sql, values); + } + + private static Task AuditCountAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, string operation, + string? entity = null, string outcome = "success") => CountAsync(proof, tenant, organization, """ + SELECT count(*) FROM public.audit_log + WHERE operation=@operation AND outcome=@outcome AND organization_id IS NOT DISTINCT FROM @organization::uuid + AND (@entity::text IS NULL OR entity_id=@entity::text) + """, ("operation", operation), ("outcome", outcome), ("organization", (object?)organization ?? DBNull.Value), + ("entity", (object?)entity ?? DBNull.Value)); + + /// Mints a ticket through the API and reads every chunk in order, returning the reassembled bundle. + private static async Task<(string Ticket, byte[] Bundle)> DownloadAsync(HttpClient client, string token, Guid request) + { + using var minted = await SendAsync(client, token, OwnPath + "/" + request.ToString("D") + "/artifact/tickets", "POST", "{}"); + var grant = await JsonAsync(minted); + grant.EnumerateObject().Select(property => property.Name).Should().Equal("ticket", "expiresAt", "chunkCount", "byteCount"); + minted.Headers.ETag.Should().BeNull(); + var ticket = grant.GetProperty("ticket").GetString()!; + ticket.Should().MatchRegex("^[A-Za-z0-9_-]{43}$"); + var count = grant.GetProperty("chunkCount").GetInt32(); + var bytes = new List(); + for (var index = 0; index < count; index++) + { + using var read = await ChunkAsync(client, token, request, ticket, index); + var chunk = await JsonAsync(read); + chunk.EnumerateObject().Select(property => property.Name).Should().Equal("index", "count", "bytes"); + chunk.GetProperty("index").GetInt32().Should().Be(index); + chunk.GetProperty("count").GetInt32().Should().Be(count); + bytes.AddRange(Convert.FromBase64String(chunk.GetProperty("bytes").GetString()!)); + } + + bytes.Count.Should().Be(checked((int)grant.GetProperty("byteCount").GetInt64())); + return (ticket, bytes.ToArray()); + } + + private static Task ChunkAsync(HttpClient client, string token, Guid request, string ticket, int index) => + SendAsync(client, token, OwnPath + "/" + request.ToString("D") + "/artifact/chunks", "POST", + JsonSerializer.Serialize(new { ticket, index })); + + private sealed class RoutingClaim : BackgroundJobRoutingClaim.MintingSource + { + internal static async Task ClaimAsync(string connectionString, BackgroundJobId job) + { + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand(""" + UPDATE background_jobs SET ownership_token=@token,ownership_kind='routing', + ownership_until=clock_timestamp()+interval '4 minutes' WHERE id=@job + RETURNING id,tenant_id,organization_id,definition_key,queue,wake_generation,ownership_token, + ownership_until,original_due_at,profile,phase,clock_timestamp() + """, dispatcher); + command.Parameters.AddWithValue("job", job.Value); + command.Parameters.AddWithValue("token", Guid.NewGuid()); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return MintClaim(row); + } + } + + private static string Version(JsonElement element) => element.GetProperty("version").GetString()!; + + private static long Number(string value) => long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs new file mode 100644 index 00000000..a204e1ea --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs @@ -0,0 +1,87 @@ +using FluentAssertions; +using LearnStack.Application.Messaging; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The request API's storage seams as learnstack_app on the seeded data-request rows: the explicit group +/// predicate that the canonical row policy alone does not supply, the one-active index mapped to a refusal rather +/// than an exception, and the exact Membership snapshot the creation guard demands. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataRequestServiceStorageTests(SchemaFixture fixture) +{ + [Fact] + public async Task Reads_name_exactly_the_announced_group_although_the_row_policy_shows_an_organization_the_tenant_wide_rows() + { + await using var database = await OpenDatabaseAsync(); + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, SchemaFixture.OrgA1)) + { + // The policy alone admits the tenant-wide group's row into an organization context. + (await ScalarAsync(scope.Connection, scope.Transaction, "SELECT count(*) FROM public.data_subject_requests WHERE organization_id IS NULL")) + .Should().Be(1, "the canonical row policy shows an organization context the tenant-wide rows"); + var reader = new DataRequestReader(scope.Db, scope.Unit, scope.Context); + (await reader.ListAsync(null, null, 101, CancellationToken.None)).Select(request => request.Id.Value) + .Should().Equal(BranchA1.Request); + (await reader.ListAsync(UserId.From(PersonA), null, 101, CancellationToken.None)).Select(request => request.Id.Value) + .Should().Equal(BranchA1.Request); + (await reader.FindAsync(DataSubjectRequestId.From(TenantWideA.Request), CancellationToken.None)).Should().BeNull(); + (await reader.ReadArtifactsAsync([DataSubjectRequestId.From(TenantWideA.Request)], CancellationToken.None)).Should().BeEmpty(); + (await reader.FindArtifactLockedAsync(DataSubjectRequestId.From(TenantWideA.Request), CancellationToken.None)).Should().BeNull(); + (await Store(scope).ReadSubjectMembershipsAsync(UserId.From(PersonA), CancellationToken.None)).Select(member => member.Value) + .Should().Equal(BranchMembershipA1); + (await reader.FindMembershipSubjectAsync(MembershipId.From(LearnerMembershipA), CancellationToken.None)).Should().BeNull( + "another group's Membership is absent"); + await scope.Frame.FailAsync(); + } + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + var reader = new DataRequestReader(scope.Db, scope.Unit, scope.Context); + (await reader.ListAsync(null, null, 101, CancellationToken.None)).Select(request => request.Id.Value) + .Should().Equal(TenantWideA.Request); + var artifacts = await reader.ReadArtifactsAsync([DataSubjectRequestId.From(TenantWideA.Request)], CancellationToken.None); + artifacts.Should().ContainSingle().Which.Value.Readable.Should().BeTrue(); + (await reader.FindMembershipSubjectAsync(MembershipId.From(LearnerMembershipA), CancellationToken.None)) + .Should().Be(UserId.From(PersonA)); + await scope.Frame.FailAsync(); + } + } + + [Fact] + public async Task The_one_active_index_refuses_a_second_active_export_as_a_mapped_refusal_that_leaves_the_transaction_rollback_only() + { + await using var database = await OpenDatabaseAsync(); + await using var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantB, SchemaFixture.OrgB1, + [PersonB]); + var store = Store(scope); + var active = await store.FindActiveLockedAsync(UserId.From(PersonB), DataRequestKind.Export, CancellationToken.None); + active!.Id.Value.Should().Be(BranchB.Request, "the seeded requested export holds the slot"); + // Bypass the eligibility judgment on purpose: the index is the backstop a race meets. + var second = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, UserId.From(PersonB), + new DataRequestScopeGroup(scope.Context.TenantId, scope.Context.OrganizationId), [MembershipId.From(BranchMembershipB)], + DateTimeOffset.UtcNow).Value!; + (await store.TryAddAsync(second, CancellationToken.None)).Should().BeFalse(); + scope.Unit.IsRollbackOnly.Should().BeTrue(); + scope.Db.ChangeTracker.Entries().Should().NotContain(entry => entry.Entity == second); + } + + private static DataRequestStore Store(DataExportTestKit.GroupScope scope) => + new(scope.Db, scope.Unit, new ProducerExecution(scope.Unit), scope.Context); + + private async Task OpenDatabaseAsync() + { + var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await BackgroundJobSchemaSeed.SeedTenantsAsync(database.AppConnectionString); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + return database; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index e8da4cb3..8157ceac 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -227,12 +227,16 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() dataRequests.Should().Throw().WithMessage("Data request 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."); + Action deliveryInspection = () => _ = new LearnStack.Infrastructure.Persistence.Migrations.grant_platform_delivery_inspection().DownOperations; + deliveryInspection.Should().Throw().WithMessage("The platform role's column grants require a reviewed forward migration."); + Action dataRequestReceipts = () => _ = new LearnStack.Infrastructure.Persistence.Migrations.add_data_request_protected_receipts().DownOperations; + dataRequestReceipts.Should().Throw().WithMessage("Retained data request 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, "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."), + (platform, "20261120120000_grant_platform_delivery_inspection", PlatformReversibleHead, + "20261122160000_add_data_request_protected_receipts", "Retained data request receipts require a reviewed forward migration."), (identity, "20261122013001_add_data_subject_requests", IdentityReversibleHead, "20261122140000_add_own_data_request_scopes", "The retained own data-request scope requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/HttpDataExportSessionBindingTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/HttpDataExportSessionBindingTests.cs new file mode 100644 index 00000000..b6829ae3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/HttpDataExportSessionBindingTests.cs @@ -0,0 +1,75 @@ +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Authentication; + +/// ADR-0107 § 4: a download ticket binds the validated credential, actor and group of the request that minted it. +public sealed class HttpDataExportSessionBindingTests +{ + private static readonly UserId Actor = UserId.From(Guid.CreateVersion7()); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly OrganizationId Organization = OrganizationId.From(Guid.CreateVersion7()); + + [Fact] + public void The_binding_is_a_stable_digest_of_the_presented_credential_actor_and_group_and_never_the_credential() + { + var binding = Capture(Request("token-one")); + binding.Should().MatchRegex("^[0-9a-f]{64}$"); + binding.Should().NotContain("token-one"); + Capture(Request("token-one")).Should().Be(binding, "the same session binds the same way on every request"); + Capture(Request("token-two")).Should().NotBe(binding, "another session's credential binds differently"); + Capture(Request("token-one"), organization: Organization).Should().NotBe(binding, "the group is bound"); + Capture(Request("token-one"), tenant: TenantId.From(Guid.CreateVersion7())).Should().NotBe(binding); + } + + [Theory] + [InlineData("no-credential")] + [InlineData("other-actor")] + [InlineData("two-headers")] + [InlineData("not-bearer")] + [InlineData("empty-bearer")] + [InlineData("aborted")] + [InlineData("no-context")] + public void Without_one_validated_bearer_credential_of_the_same_actor_there_is_no_binding(string variant) + { + var http = variant == "no-context" ? null : Request("token-one"); + switch (variant) + { + case "no-credential": http!.Features.Set(null); break; + case "other-actor": + http!.Features.Get()!.Identity = new ValidatedTenantIdentity("https://issuer.test/realms/learnstack", + "subject", UserId.From(Guid.CreateVersion7()), Tenant, null); + break; + case "two-headers": http!.Request.Headers.Authorization = new(["Bearer token-one", "Bearer token-two"]); break; + case "not-bearer": http!.Request.Headers.Authorization = "Basic token-one"; break; + case "empty-bearer": http!.Request.Headers.Authorization = "Bearer "; break; + case "aborted": + using (var source = new CancellationTokenSource()) + { + source.Cancel(); + http!.RequestAborted = source.Token; + } + break; + } + + new HttpDataExportSessionBinding(new HttpContextAccessor { HttpContext = http }).Capture(Actor, Tenant, null).Should().BeNull(); + } + + private static string? Capture(DefaultHttpContext http, TenantId? tenant = null, OrganizationId? organization = null) => + new HttpDataExportSessionBinding(new HttpContextAccessor { HttpContext = http }).Capture(Actor, tenant ?? Tenant, organization); + + private static DefaultHttpContext Request(string token) + { + var http = new DefaultHttpContext(); + http.Request.Headers.Authorization = "Bearer " + token; + http.Features.Set(new TenantCredentialFeature + { + VerifiedSubject = new VerifiedProviderSubject("https://issuer.test/realms/learnstack", "subject", Actor, Tenant, null), + Identity = new ValidatedTenantIdentity("https://issuer.test/realms/learnstack", "subject", Actor, Tenant, null), + }); + return http; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs index ad20c10a..71351cd7 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs @@ -196,7 +196,7 @@ public Task AuthorizeAsync(OperationInvocation invoc // Deliberately bypass the private minter to prove the coordinator's independent boundary. var constructor = typeof(ProtectedOperationDecision).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single(); return Task.FromResult((ProtectedOperationDecision)constructor.Invoke( - [invocation, ProtectedOperationOutcome.Allowed, decision.MembershipIds, decision.RoleIds, clause, witness, null, null])); + [invocation, ProtectedOperationOutcome.Allowed, decision.MembershipIds, decision.RoleIds, clause, witness, null, null, null])); } } diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs index 920971a8..d19d37ac 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs @@ -36,10 +36,19 @@ 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(136, actual.Length); + Assert.Equal(154, 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)); + Assert.Equal(67, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.Protected)); + // ADR-0106 § 4: eight own live-session data-request operations carry no key and no grant. + Assert.All(catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequest), policy => + { + Assert.StartsWith("identity.data_request.", policy.Id, StringComparison.Ordinal); + Assert.Null(policy.RequiredPermission); + Assert.Empty(policy.Alternatives); + Assert.Equal(OperationReadScope.Scoped, policy.ReadScope); + }); + Assert.Equal(8, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.OwnDataRequest)); var ownReads = catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnMembershipRead).ToArray(); Assert.Equal(new[] { typeof(GetOwnMembershipProfileQuery), typeof(ReadOwnMembershipProfileReceiptQuery), typeof(ReadOwnGrantedFieldConsentReceiptQuery), typeof(GetOwnMembershipContextsQuery), typeof(GetOwnCapabilitiesQuery), typeof(GetOwnMembershipCustomFieldsQuery), typeof(GetOwnMembershipFieldConsentQuery), typeof(GetTenantInvitationPolicyQuery), typeof(ReadInvitationPolicyReceiptQuery) } @@ -64,7 +73,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(51, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.FiniteTrusted)); + Assert.Equal(55, 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); diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestCodecTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestCodecTests.cs new file mode 100644 index 00000000..25519856 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestCodecTests.cs @@ -0,0 +1,73 @@ +using System.Security.Cryptography; +using System.Text; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// ADR-0107 § 4's opaque ticket and the data-request page cursor: canonical spellings only, digests only stored. +public sealed class DataRequestCodecTests +{ + [Fact] + public void A_minted_ticket_is_32_random_bytes_in_canonical_base64url_and_only_its_domain_separated_digest_is_kept() + { + var (ticket, digest) = DataExportTicketCodec.Mint(); + var (other, otherDigest) = DataExportTicketCodec.Mint(); + + ticket.Should().MatchRegex("^[A-Za-z0-9_-]{43}$"); + other.Should().NotBe(ticket); + digest.Should().MatchRegex("^[0-9a-f]{64}$").And.NotBe(otherDigest); + DataExportTicketCodec.TryDigest(ticket).Should().Be(digest); + var raw = Convert.FromBase64String(ticket.Replace('-', '+').Replace('_', '/') + "="); + raw.Should().HaveCount(32); + Convert.ToHexStringLower(SHA256.HashData(raw)).Should().NotBe(digest, "the digest is domain-separated, never a bare hash"); + digest.Should().NotContain(ticket); + } + + [Theory] + [InlineData("")] + [InlineData("short")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")] + public void A_noncanonical_or_malformed_ticket_has_no_digest(string ticket) => + DataExportTicketCodec.TryDigest(ticket).Should().BeNull(); + + [Fact] + public void A_one_character_change_is_a_different_well_formed_ticket() + { + var (ticket, digest) = DataExportTicketCodec.Mint(); + var forged = (ticket[0] == 'A' ? 'B' : 'A') + ticket[1..]; + DataExportTicketCodec.TryDigest(forged).Should().NotBeNull().And.NotBe(digest); + } + + [Fact] + public void A_cursor_round_trips_only_under_the_scope_it_was_minted_for() + { + var actor = UserId.From(Guid.CreateVersion7()); + var tenant = TenantId.From(Guid.CreateVersion7()); + var organization = OrganizationId.From(Guid.CreateVersion7()); + var anchor = Guid.CreateVersion7(); + var scope = DataRequestCursorCodec.Scope("identity.data_request.list_own", actor, tenant, null); + var cursor = DataRequestCursorCodec.Encode(scope, anchor); + + DataRequestCursorCodec.TryDecode(cursor, scope, out var decoded).Should().BeTrue(); + decoded.Should().Be(anchor); + foreach (var other in new[] + { + DataRequestCursorCodec.Scope("identity.data_request.list", actor, tenant, null), + DataRequestCursorCodec.Scope("identity.data_request.list_own", UserId.From(Guid.CreateVersion7()), tenant, null), + DataRequestCursorCodec.Scope("identity.data_request.list_own", actor, tenant, organization), + }) + DataRequestCursorCodec.TryDecode(cursor, other, out _).Should().BeFalse(); + DataRequestCursorCodec.TryDecode(cursor + "A", scope, out _).Should().BeFalse(); + DataRequestCursorCodec.TryDecode(Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"v\":1}")), scope, out _).Should().BeFalse(); + DataRequestCursorCodec.TryDecode(DataRequestCursorCodec.Encode(scope, Guid.NewGuid()), scope, out _).Should().BeFalse( + "only a UUIDv7 anchors a page"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs index ff958639..5f41ff5d 100644 --- a/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs @@ -26,7 +26,7 @@ public async Task A_requested_export_submits_the_export_definition_of_its_group( var jobs = new RecordingScheduler(); var request = Request(DataRequestKind.Export, organization); - await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(request, CancellationToken.None); + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(request.Id.Value, request.Kind, request.Status, request.Group, CancellationToken.None); jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataExportJobParameters(request.Id.Value), (DateTimeOffset?)null)); } @@ -52,7 +52,7 @@ public async Task Anything_but_a_requested_export_of_the_announced_group_is_a_pr var context = new Context(variant == "other_group" ? Organization : null); - await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, context).SubmitAsync(request, CancellationToken.None).AsTask()) + await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, context).SubmitAsync(request.Id.Value, request.Kind, request.Status, request.Group, CancellationToken.None).AsTask()) .Should().ThrowAsync(); jobs.Submitted.Should().BeEmpty(); } @@ -67,11 +67,11 @@ public async Task A_purge_is_scheduled_for_its_artifact_at_the_due_time(string s var artifact = DataExportArtifactId.From(Guid.CreateVersion7()); var due = At + DataRequestLimits.ArtifactLifetime; - await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SchedulePurgeAsync(artifact, due, CancellationToken.None); + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SchedulePurgeAsync(artifact.Value, due, CancellationToken.None); jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataExportPurgeParameters(artifact.Value), (DateTimeOffset?)due)); await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, new Context(organization)) - .SchedulePurgeAsync(DataExportArtifactId.From(Guid.NewGuid()), due, CancellationToken.None).AsTask()) + .SchedulePurgeAsync(Guid.NewGuid(), due, CancellationToken.None).AsTask()) .Should().ThrowAsync("an artifact identity is a UUIDv7"); } diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs new file mode 100644 index 00000000..4cbe38da --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs @@ -0,0 +1,573 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// The data-request handler cores of ADR-0106 and ADR-0107 § 4 against in-memory ports: who reaches which request, +/// the creation fences and refusals, the conditional mutations, and the ticket and chunk rules. +/// +public sealed class DataRequestServiceTests +{ + private static readonly DateTimeOffset At = new(2026, 11, 22, 9, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly UserId Subject = UserId.From(Guid.CreateVersion7()); + private static readonly UserId Administrator = UserId.From(Guid.CreateVersion7()); + private static readonly MembershipId SubjectMembership = MembershipId.From(Guid.CreateVersion7()); + private static readonly MembershipId AdministratorMembership = MembershipId.From(Guid.CreateVersion7()); + + [Fact] + public async Task A_subject_files_for_themselves_under_their_User_fence_and_the_job_is_submitted_on_the_same_transaction() + { + var harness = new Harness(); + var result = await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + result.IsSuccess.Should().BeTrue(); + var request = harness.Store.Requests.Should().ContainSingle().Subject; + request.Origin.Should().Be(DataRequestOrigin.Self); + request.SnapshotMembershipIds.Should().Equal(SubjectMembership); + harness.Locks.Acquired.Should().ContainSingle().Which.UserIds.Should().Equal(Subject); + harness.Locks.Acquired[0].TenantMode.Should().Be(IdentityTenantLockMode.Shared); + harness.Scheduler.Submitted.Should().Equal(request.Id); + harness.Audit.Designated.Should().Contain(request); + harness.Rechecks.Should().Be(1, "authority is re-evaluated once the fences are held"); + } + + [Fact] + public async Task An_administrator_files_for_a_member_never_for_themselves_and_an_unknown_Membership_is_absent() + { + var harness = new Harness(); + var caller = harness.Caller(Administrator, DataRequestRole.Administrator); + + Code(await harness.Service.CreateExportForMembershipAsync(caller, AdministratorMembership.Value, CancellationToken.None)) + .Should().Be("business_rule_violation"); + Code(await harness.Service.CreateExportForMembershipAsync(caller, Guid.CreateVersion7(), CancellationToken.None)) + .Should().Be("not_found"); + Code(await harness.Service.CreateExportForMembershipAsync(harness.Caller(Subject, DataRequestRole.Subject), + SubjectMembership.Value, CancellationToken.None)).Should().Be("forbidden"); + harness.Store.Requests.Should().BeEmpty(); + + (await harness.Service.CreateExportForMembershipAsync(caller, SubjectMembership.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + var request = harness.Store.Requests.Should().ContainSingle().Subject; + request.Origin.Should().Be(DataRequestOrigin.Administrator); + request.RequesterUserId.Should().Be(Administrator); + request.SubjectUserId.Should().Be(Subject); + } + + [Theory] + [InlineData("eligibility")] + [InlineData("index")] + public async Task A_second_active_export_is_refused_as_request_already_active_whether_judged_or_caught_by_the_index(string path) + { + var harness = new Harness(); + if (path == "eligibility") + { + (await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue(); + } + else + { + harness.Store.RejectAdd = true; + } + + var refused = await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + Code(refused).Should().Be("business_rule_violation"); + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_request_already_active"); + harness.Scheduler.Submitted.Should().HaveCount(path == "eligibility" ? 1 : 0, "a refused creation submits nothing"); + } + + [Fact] + public async Task A_dead_jobs_request_is_stored_failed_under_the_held_fences_before_the_one_active_rule_is_judged() + { + var harness = new Harness(); + await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var dead = harness.Store.Requests.Single(); + harness.Phases.Phase[dead.Id] = DataRequestJobPhase.Dead; + var next = new Harness(harness.Store, harness.Phases); + + (await next.Service.CreateExportAsync(next.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)).IsSuccess.Should().BeTrue(); + + dead.Status.Should().Be(DataRequestStatus.Failed); + dead.FailureReason.Should().Be(DataRequestFailureReason.ExecutionFailed); + next.Locks.Acquired.Should().ContainSingle("the reconciler proves the held plan instead of taking a second one"); + next.Store.Requests.Should().HaveCount(2); + } + + [Fact] + public async Task A_hold_refuses_creation_with_its_closed_code_and_files_nothing() + { + var harness = new Harness(hold: true); + var refused = await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_blocked_hold"); + harness.Store.Requests.Should().BeEmpty(); + } + + [Fact] + public async Task Authority_lost_while_waiting_for_the_fences_refuses_the_creation() + { + var harness = new Harness { RecheckResult = Result.Fail(new Error(LearnStack.SharedKernel.Localization.LocalizedMessage.Of("lockey_forbidden"))) }; + Code(await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .Should().Be("forbidden"); + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty(); + } + + [Fact] + public async Task Cancellation_needs_the_current_version_and_reaches_only_the_subject_or_the_filing_administrator() + { + var harness = new Harness(); + await harness.Service.CreateExportForMembershipAsync(harness.Caller(Administrator, DataRequestRole.Administrator), + SubjectMembership.Value, CancellationToken.None); + var request = harness.Store.Requests.Single(); + var other = UserId.From(Guid.CreateVersion7()); + + Code(await harness.Service.CancelAsync(harness.Caller(other, DataRequestRole.Administrator), request.Id.Value, 0, CancellationToken.None)) + .Should().Be("not_found", "another administrator did not file it"); + Code(await harness.Service.CancelAsync(harness.Caller(other, DataRequestRole.Subject), request.Id.Value, 0, CancellationToken.None)) + .Should().Be("not_found", "another person is not its subject"); + Code(await harness.Service.CancelAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, 5, CancellationToken.None)) + .Should().Be("concurrency_conflict"); + + var cancelled = await harness.Service.CancelAsync(harness.Caller(Administrator, DataRequestRole.Administrator), request.Id.Value, 0, + CancellationToken.None); + cancelled.Value!.Version.Should().Be(1); + request.Status.Should().Be(DataRequestStatus.Cancelled); + Code(await harness.Service.CancelAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, 1, CancellationToken.None)) + .Should().Be("business_rule_violation", "a terminal request accepts no transition"); + } + + [Fact] + public async Task Only_the_subject_mints_a_ticket_in_a_bound_session_over_a_readable_artifact_and_only_its_digest_is_stored() + { + var harness = new Harness(); + var request = harness.Completed(origin: DataRequestOrigin.Administrator); + var subject = harness.Caller(Subject, DataRequestRole.Subject); + + Code(await harness.Download.MintTicketAsync(harness.Caller(Administrator, DataRequestRole.Administrator), request.Id.Value, + CancellationToken.None)).Should().Be("forbidden", "an administrator never gets a ticket"); + Code(await harness.Download.MintTicketAsync(harness.Caller(Administrator, DataRequestRole.Subject), request.Id.Value, + CancellationToken.None)).Should().Be("not_found", "the self path reaches no request about another person"); + harness.Sessions.Binding = null; + Code(await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Should().Be("forbidden"); + harness.Sessions.Binding = Binding('a'); + harness.Store.Artifacts[request.Id] = harness.Store.Artifacts[request.Id] with { Readable = false }; + (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Error!.Details!["artifact"].Single().Key + .Should().Be("lockey_data_export_unavailable"); + harness.Store.Artifacts[request.Id] = harness.Store.Artifacts[request.Id] with { Readable = true }; + + var grant = await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + + grant.IsSuccess.Should().BeTrue(); + var ticket = harness.Store.Tickets.Should().ContainSingle().Subject; + ticket.Digest.Should().Be(DataExportTicketCodec.TryDigest(grant.Value!.Ticket)); + ticket.SessionBindingDigest.Should().Be(Binding('a')); + ticket.ExpiresAt.Should().Be(At + DataRequestLimits.TicketLifetime); + grant.Value.ChunkCount.Should().Be(2); + grant.Value.ToString().Should().NotContain(grant.Value.Ticket); + harness.Audit.Designated.Should().Contain(ticket); + } + + [Fact] + public async Task A_chunk_reads_only_through_its_own_session_and_the_final_chunk_consumes_the_ticket() + { + var harness = new Harness(); + var request = harness.Completed(); + var subject = harness.Caller(Subject, DataRequestRole.Subject); + var ticket = (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Value!.Ticket; + + harness.Sessions.Binding = Binding('b'); + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 0, CancellationToken.None)) + .Should().Be("not_found", "another session's credential does not bind this ticket"); + harness.Sessions.Binding = Binding('a'); + var forged = (ticket[0] == 'A' ? 'B' : 'A') + ticket[1..]; + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, forged, 0, CancellationToken.None)).Should().Be("not_found"); + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket + "=", 0, CancellationToken.None)).Should().Be("validation_failed"); + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 2, CancellationToken.None)).Should().Be("not_found"); + Code(await harness.Download.ReadChunkAsync(harness.Caller(Subject, DataRequestRole.Administrator), request.Id.Value, ticket, 0, + CancellationToken.None)).Should().Be("forbidden"); + + var first = await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 0, CancellationToken.None); + first.Value!.Index.Should().Be(0); + harness.Store.Tickets.Single().ConsumedAt.Should().BeNull(); + harness.Store.TicketSaves.Should().Be(0); + var last = await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 1, CancellationToken.None); + last.Value!.Count.Should().Be(2); + harness.Store.Tickets.Single().ConsumedAt.Should().Be(At); + harness.Store.TicketSaves.Should().Be(1); + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 0, CancellationToken.None)) + .Should().Be("not_found", "a consumed cursor reads nothing more"); + harness.Audit.Designated.Should().Contain(harness.Store.Tickets.Single()); + } + + [Fact] + public async Task An_expired_ticket_never_reaches_the_plaintext_and_a_failed_consumption_clears_the_decrypted_chunk() + { + var harness = new Harness(); + var request = harness.Completed(); + var subject = harness.Caller(Subject, DataRequestRole.Subject); + var ticket = (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Value!.Ticket; + harness.Clock.Now = At + DataRequestLimits.TicketLifetime; + + Code(await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 1, CancellationToken.None)).Should().Be("not_found"); + harness.Artifacts.Served.Should().BeEmpty("an expired ticket never reaches the plaintext"); + + harness.Clock.Now = At; + harness.Store.FailConsumption = true; + await FluentActions.Awaiting(() => harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 1, CancellationToken.None)) + .Should().ThrowAsync(); + harness.Artifacts.Served.Should().ContainSingle().Which.Should().OnlyContain(value => value == 0, "the decrypted chunk is zeroed"); + } + + [Fact] + public async Task Receipts_show_a_dead_job_as_failed_an_overdue_artifact_as_expired_and_Memberships_only_to_an_administrator() + { + var harness = new Harness(); + await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var requested = harness.Store.Requests.Single(); + harness.Phases.Phase[requested.Id] = DataRequestJobPhase.Dead; + + var own = (await harness.Service.GetAsync(harness.Caller(Subject, DataRequestRole.Subject), requested.Id.Value, CancellationToken.None)).Value!; + own.Status.Should().Be("failed"); + own.FailureReason.Should().Be("execution_failed"); + own.MembershipIds.Should().BeNull(); + requested.Status.Should().Be(DataRequestStatus.Requested, "displaying failed writes nothing"); + + var admin = (await harness.Service.GetAsync(harness.Caller(Administrator, DataRequestRole.Administrator), requested.Id.Value, + CancellationToken.None)).Value!; + admin.MembershipIds.Should().Equal(SubjectMembership.Value); + admin.RequestedByCaller.Should().BeFalse(); + + var other = new Harness(); + var completed = other.Completed(); + other.Store.Artifacts[completed.Id] = other.Store.Artifacts[completed.Id] with { Readable = false }; + var view = (await other.Service.GetAsync(other.Caller(Subject, DataRequestRole.Subject), completed.Id.Value, CancellationToken.None)).Value!; + view.Artifact!.Status.Should().Be("expired"); + view.Artifact.Readable.Should().BeFalse(); + Code(await other.Service.GetAsync(other.Caller(UserId.From(Guid.CreateVersion7()), DataRequestRole.Subject), completed.Id.Value, + CancellationToken.None)).Should().Be("not_found"); + } + + [Fact] + public async Task A_page_cursor_is_bound_to_its_operation_actor_and_group() + { + var harness = new Harness(); + for (var index = 0; index < 3; index++) + { + var request = harness.Completed(); + request.Status.Should().Be(DataRequestStatus.Completed); + } + + var caller = harness.Caller(Subject, DataRequestRole.Subject); + var first = (await harness.Service.ListAsync(caller, "identity.data_request.list_own", null, 2, CancellationToken.None)).Value!; + first.Items.Should().HaveCount(2); + first.PageInfo.HasNext.Should().BeTrue(); + var second = (await harness.Service.ListAsync(caller, "identity.data_request.list_own", first.PageInfo.NextCursor, 2, CancellationToken.None)).Value!; + second.Items.Should().ContainSingle(); + first.Items.Concat(second.Items).Select(item => item.RequestId).Should().OnlyHaveUniqueItems().And.BeInDescendingOrder(); + Code(await harness.Service.ListAsync(caller, "identity.data_request.list", first.PageInfo.NextCursor, 2, CancellationToken.None)) + .Should().Be("validation_failed", "another operation's cursor is refused"); + Code(await harness.Service.ListAsync(harness.Caller(Administrator, DataRequestRole.Subject), "identity.data_request.list_own", + first.PageInfo.NextCursor, 2, CancellationToken.None)).Should().Be("validation_failed", "another actor's cursor is refused"); + } + + [Fact] + public async Task Eligibility_judges_only_exports_of_the_announced_group_and_excludes_the_executing_request() + { + var store = new Store(); + var context = new Context(Subject); + var eligibility = new DataRequestEligibility(store, new NoHoldSource(), context); + var group = new DataRequestScopeGroup(Tenant, null); + + await FluentActions.Awaiting(() => eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Erasure, + DataRequestOrigin.Self, Subject, group, DataRequestEligibilityStage.Creation), CancellationToken.None)).Should().ThrowAsync(); + await FluentActions.Awaiting(() => eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, + DataRequestOrigin.Self, Subject, new DataRequestScopeGroup(Tenant, OrganizationId.From(Guid.CreateVersion7())), + DataRequestEligibilityStage.Creation), CancellationToken.None)).Should().ThrowAsync(); + (await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, DataRequestOrigin.Self, + UserId.From(Guid.CreateVersion7()), group, DataRequestEligibilityStage.Creation), CancellationToken.None)).Reason + .Should().Be(DataRequestIneligibility.NoMembership); + + var request = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, Subject, group, + [SubjectMembership], At).Value!; + store.Requests.Add(request); + (await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, DataRequestOrigin.Self, Subject, group, + DataRequestEligibilityStage.Creation), CancellationToken.None)).Reason.Should().Be(DataRequestIneligibility.RequestAlreadyActive); + (await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, DataRequestOrigin.Self, Subject, group, + DataRequestEligibilityStage.Execution, request.Id.Value), CancellationToken.None)).IsEligible.Should().BeTrue(); + (await new DataRequestEligibility(store, new FixedHold(), context).EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, + DataRequestOrigin.Self, Subject, group, DataRequestEligibilityStage.Execution, request.Id.Value), CancellationToken.None)) + .Reason.Should().Be(DataRequestIneligibility.BlockedHold); + } + + private static string Binding(char fill) => new(fill, 64); + + private static string? Code(Result result) => result.IsFailure ? result.Error!.Code : null; + + /// The cores over in-memory ports, in the tenant-wide group, as one request's scope. + private sealed class Harness + { + public Harness(Store? store = null, Phases? phases = null, bool hold = false) + { + Store = store ?? new Store(); + Phases = phases ?? new Phases(); + var context = new Context(null); + var reconciler = new DataRequestFailureReconciler(Store, Phases, Locks, context, Clock); + Service = new DataRequestService(Store, Store, Phases, reconciler, + new DataRequestEligibility(Store, hold ? new FixedHold() : new NoHoldSource(), context), Scheduler, Artifacts, + Locks, context, Audit, new Ids(), Clock); + Download = new DataExportDownloadService(Store, Store, Artifacts, Sessions, context, Audit, new Ids(), Clock); + } + + public Store Store { get; } + public Phases Phases { get; } + public Locks Locks { get; } = new(); + public RecordingScheduler Scheduler { get; } = new(); + public ArtifactCustody Artifacts { get; } = new(); + public SessionBinding Sessions { get; } = new() { Binding = Binding('a') }; + public RecordingAudit Audit { get; } = new(); + public FixedClock Clock { get; } = new(); + public DataRequestService Service { get; } + public DataExportDownloadService Download { get; } + public int Rechecks { get; private set; } + public Result RecheckResult { get; init; } = Result.Ok(None.Value); + + public DataRequestCaller Caller(UserId actor, DataRequestRole role) => new(actor, role, _ => + { + Rechecks++; + return Task.FromResult(RecheckResult); + }); + + /// A completed export about the subject with a readable two-chunk artifact. + public DataSubjectRequest Completed(DataRequestOrigin origin = DataRequestOrigin.Self) + { + var group = new DataRequestScopeGroup(Tenant, null); + var request = (origin == DataRequestOrigin.Self + ? DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, Subject, group, + [SubjectMembership], At) + : DataSubjectRequest.FileForSubject(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Export, Administrator, + Subject, group, [SubjectMembership], At)).Value!; + request.StartFulfilling(At, UserId.SystemActor).IsSuccess.Should().BeTrue(); + var artifact = DataExportArtifact.Create(DataExportArtifactId.From(Guid.CreateVersion7()), request, 200_000, "v1", At, + UserId.SystemActor).Value!; + request.Complete([], At, UserId.SystemActor).IsSuccess.Should().BeTrue(); + Store.Requests.Add(request); + Store.Artifacts[request.Id] = new DataRequestArtifactRow(artifact, true); + return request; + } + } + + private sealed class Context(UserId? actor) : ITenantContext + { + public bool IsResolved => true; + public TenantContextOrigin? Origin => TenantContextOrigin.HostAndClaim; + public TenantId TenantId => Tenant; + public OrganizationId? OrganizationId => null; + public UserId? UserId => actor; + public string? CorrelationId => null; + public string? ModuleName => null; + } + + private sealed class Store : IDataRequestStore, IDataRequestReader, IDataExportTicketStore + { + public List Requests { get; } = []; + public Dictionary Artifacts { get; } = []; + public List Tickets { get; } = []; + public bool RejectAdd { get; set; } + public bool FailConsumption { get; set; } + public int TicketSaves { get; private set; } + + public BackgroundJobId RequireCurrentJob() => throw new InvalidOperationException("No job in a request."); + + public Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) => + Task.FromResult(Requests.SingleOrDefault(request => request.Id == requestId)); + + public Task FindArtifactOfRequestAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task> FindAvailableArtifactsAsync(UserId subject, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task SaveAsync(DataSubjectRequest request, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task> ReadSubjectMembershipsAsync(UserId subject, CancellationToken cancellationToken) => + Task.FromResult>(subject == Subject ? [SubjectMembership] + : subject == Administrator ? [AdministratorMembership] : []); + + public Task FindMembershipSubjectAsync(MembershipId membership, CancellationToken cancellationToken) => + Task.FromResult(membership == SubjectMembership ? Subject : membership == AdministratorMembership ? Administrator : (UserId?)null); + + public Task FindActiveLockedAsync(UserId subject, DataRequestKind kind, CancellationToken cancellationToken) => + Task.FromResult(Requests.FirstOrDefault(request => request.SubjectUserId == subject && request.Kind == kind && !request.IsTerminal)); + + public Task AddAsync(DataSubjectRequest aggregate, CancellationToken cancellationToken = default) => + throw new NotSupportedException("The cores file through the mapped one-active refusal."); + + public Task TryAddAsync(DataSubjectRequest request, CancellationToken cancellationToken) + { + if (RejectAdd) + { + return Task.FromResult(false); + } + + Requests.Add(request); + return Task.FromResult(true); + } + + public Task FindArtifactLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) => + Task.FromResult(Artifacts.GetValueOrDefault(requestId)); + + public Task AddAsync(DataExportTicket ticket, CancellationToken cancellationToken = default) + { + Tickets.Add(ticket); + return Task.CompletedTask; + } + + public Task FindLockedAsync(DataExportArtifactId artifactId, string digest, CancellationToken cancellationToken) => + Task.FromResult(Tickets.SingleOrDefault(ticket => ticket.ArtifactId == artifactId && ticket.Digest == digest)); + + public Task UpdateAsync(DataExportTicket ticket, CancellationToken cancellationToken = default) + { + if (FailConsumption) + { + throw new InvalidOperationException("Synthetic consumption failure."); + } + + TicketSaves++; + return Task.CompletedTask; + } + + public Task> ListAsync(UserId? subject, Guid? before, int take, CancellationToken cancellationToken) => + Task.FromResult>(Requests + .Where(request => (subject is null ? request.Kind != DataRequestKind.Closure : request.SubjectUserId == subject) + && (before is null || request.Id.Value.CompareTo(before.Value) < 0)) + .OrderByDescending(request => request.Id.Value).Take(take).ToList()); + + public Task FindAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) => + Task.FromResult(Requests.SingleOrDefault(request => request.Id == requestId)); + + public Task> ReadArtifactsAsync( + IReadOnlyCollection requestIds, CancellationToken cancellationToken) => + Task.FromResult>( + Artifacts.Where(entry => requestIds.Contains(entry.Key)).ToDictionary(entry => entry.Key, entry => entry.Value)); + } + + private sealed class Phases : IDataRequestJobPhaseReader + { + public Dictionary Phase { get; } = []; + + public Task ReadAsync(DataSubjectRequestId requestId, DataRequestKind kind, CancellationToken cancellationToken) => + Task.FromResult(kind == DataRequestKind.Export ? Phase.GetValueOrDefault(requestId, DataRequestJobPhase.Pending) : DataRequestJobPhase.Unavailable); + + public Task> ReadManyAsync( + IReadOnlyCollection exportRequestIds, CancellationToken cancellationToken) => + Task.FromResult>( + exportRequestIds.Distinct().ToDictionary(id => id, id => Phase.GetValueOrDefault(id, DataRequestJobPhase.Pending))); + } + + /// + /// Each core call stands for its own request transaction, so the latest plan is the current one; a fresh harness + /// proves a single call acquires exactly once. + /// + private sealed class Locks : IIdentityMutationLocks + { + private IdentityMutationLockPlan? _current; + + public List Acquired { get; } = []; + + public Task AcquireAsync(IdentityMutationLockPlan plan, CancellationToken cancellationToken = default) + { + _current = plan; + Acquired.Add(plan); + return Task.CompletedTask; + } + + public void RequireCurrent(IdentityMutationLockPlan plan) + { + if (!ReferenceEquals(plan, _current)) + { + throw new IdentityMutationLockException(); + } + } + } + + private sealed class RecordingScheduler : IDataRequestFulfillmentScheduler + { + public List Submitted { get; } = []; + + public ValueTask SubmitAsync(Guid requestId, DataRequestKind kind, DataRequestStatus status, DataRequestScopeGroup group, + CancellationToken cancellationToken) + { + Submitted.Add(DataSubjectRequestId.From(requestId)); + return ValueTask.CompletedTask; + } + + public ValueTask SchedulePurgeAsync(Guid artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) => + throw new NotSupportedException(); + } + + private sealed class ArtifactCustody : IDataExportArtifactStore + { + public List Served { get; } = []; + + public Task PutAsync(DataExportArtifactPut put, IAsyncEnumerable> plaintextChunks, + CancellationToken cancellationToken) => throw new NotSupportedException(); + + public Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, CancellationToken cancellationToken) + { + var bytes = Enumerable.Repeat((byte)(index + 1), 16).ToArray(); + Served.Add(bytes); + return Task.FromResult(new DataExportPlaintextChunk(index, 2, bytes)); + } + + public Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken) => Task.FromResult(outcome); + } + + private sealed class SessionBinding : IDataExportSessionBinding + { + public string? Binding { get; set; } + + public string? Capture(UserId actor, TenantId tenant, OrganizationId? organization) => Binding; + } + + private sealed class RecordingAudit : IAuditSubject + { + public List Designated { get; } = []; + + public void Designate(IAggregateRoot aggregate) where TId : struct, IStronglyTypedId => Designated.Add(aggregate); + } + + private sealed class FixedClock : IClock + { + public DateTimeOffset Now { get; set; } = At; + public DateTimeOffset UtcNow => Now; + } + + private sealed class Ids : IGuidFactory + { + public Guid NewUuidV7() => Guid.CreateVersion7(); + public Guid NewUuidV4() => Guid.NewGuid(); + } + + private sealed class FixedHold : IDataRequestHoldSource + { + public Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) => Task.FromResult(true); + } +} diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index 8e363234..9391ed2c 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -810,6 +810,78 @@ the module's side of it. deletes its federated links; the account review is the realm administrator's, by runbook. +### Subject data request API (P03-10 Step 1) + +The live-session API of [ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) +and [ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 4. The +[permission matrix](permissions.md#subject-data-request-bindings) owns who may call each operation and +the [audit matrix](audit.md#data-request-bindings) its classification; the OpenAPI document owns the +exact wire shapes. + +| Route (under `/api/v1`) | Operation | Request | +|---|---|---| +| `POST identity/me/data-requests/exports` | `identity.data_request.create_own_export` | `CreateOwnDataExportCommand` | +| `GET identity/me/data-requests` | `identity.data_request.list_own` | `ListOwnDataRequestsQuery` | +| `GET identity/me/data-requests/{id}` | `identity.data_request.read_own` | `GetOwnDataRequestQuery` | +| `POST identity/me/data-requests/{id}/cancellations` | `identity.data_request.cancel_own` | `CancelOwnDataRequestCommand` | +| `POST identity/me/data-requests/{id}/artifact/revocations` | `identity.data_request.revoke_own_export` | `RevokeOwnDataExportCommand` | +| `POST identity/me/data-requests/{id}/artifact/tickets` | `identity.data_request.mint_export_ticket` | `MintOwnDataExportTicketCommand` | +| `POST identity/me/data-requests/{id}/artifact/chunks` | `identity.data_request.read_export_chunk` | `ReadOwnDataExportChunkCommand` | +| (keyed replay only) | `identity.data_request.read_own_receipt` | `ReadOwnDataRequestReceiptQuery` | +| `POST identity/data-requests/exports` | `identity.data_request.create_export` | `CreateDataExportForSubjectCommand` | +| `GET identity/data-requests` | `identity.data_request.list` | `ListDataRequestsQuery` | +| `GET identity/data-requests/{id}` | `identity.data_request.read` | `GetDataRequestQuery` | +| `POST identity/data-requests/{id}/cancellations` | `identity.data_request.cancel` | `CancelDataRequestCommand` | +| `POST identity/data-requests/{id}/artifact/revocations` | `identity.data_request.revoke_export` | `RevokeDataExportCommand` | +| (keyed replay only) | `identity.data_request.read_receipt` | `ReadDataRequestReceiptQuery` | + +- **The group is the context's.** Every read and write names the announced tenant and + `organization_id IS NOT DISTINCT FROM` the announced organization: the canonical row + policy also shows an organization context the tenant-wide group's rows, so the predicate + keeps each group's requests out of the other's pages. One handler core serves each + operation; the request types are thin admissions over it, so the retained own-scope path + of ADR-0106 § 9 adds its own request types over the same cores. +- **Creation.** `IdentityMutationLockPlan([subject], tenant, Shared)` takes the subject's + exclusive User fence and the shared tenant fence the creation guard demands, then the + authority is rechecked. A request whose export job is dead is stored `failed` through + `DataRequestFailureReconciler` under the held plan before `DataRequestEligibility` (the + default `IDataRequestEligibility`) judges the one-active rule; the partial unique index is + the backstop and maps to the same `409 business_rule_violation` with + `errors.$ = lockey_request_already_active`. The frozen snapshot is every Membership of the + subject in the group, of any status, and the export job is submitted on the creating + transaction. The answer is `202` with `{id, kind, status, version}`, the `Location` of the + receipt and its `ETag`. An administrator names the subject by a Membership of the group, + of any status, and never themselves. +- **Receipts.** Identity, kind, origin, status, timestamps, the recorded refusal or failure + code, the closed retained-reference kinds and counts, and the artifact's status, expiry, + byte and chunk counts and truncation statement. A request whose job is dead is displayed + `failed` (`execution_failed`) without a write, and an artifact past its expiry is displayed + `expired`. The administrator's view adds the frozen Membership identifiers and + `requestedByYou`; neither view holds content, a key version or the subject's `UserId`. +- **Cancellation and revocation.** Each needs `If-Match` (the request's version for a + cancellation, the artifact's for a revocation) and an `Idempotency-Key`. The subject + cancels or revokes any request about them; an administrator only one they filed. + Revocation goes through `IDataExportArtifactStore.PurgeAsync(Revoked)`, which deletes the + chunks at once, and is refused for an artifact already past its expiry. +- **Download.** A ticket is 32 random bytes returned once as 43 base64url characters and + stored only as a domain-separated SHA-256 digest beside a session-binding digest: + `HttpDataExportSessionBinding` hashes the group, the actor, the verified issuer and + subject and the digest of the exact bearer credential the request presented. The ticket + travels only in a request body; neither ticket operation is keyed or conditional. While + the ticket is unconsumed, unexpired (fifteen minutes) and presented in its own session, + it authorizes reads of any index below the chunk count; serving the final chunk + (`count - 1`) consumes it on the same transaction, and a resumed or repeated download + mints a new ticket. Every refusal of a chunk read is the same `404 not_found`. The chunk + is written as `{index, count, bytes}` straight from its plaintext buffer, which is then + zeroed; responses are `no-store`. +- **One root per executor.** `DataRequestService` writes only `DataSubjectRequest`, through + `IDataRequestStore`; `DataExportDownloadService` writes only `DataExportTicket`, through + `IDataExportTicketStore`. Both derive the typed aggregate write store, the readers + (`IDataRequestReader`, `IDataRequestJobPhaseReader`) take typed keys through enumerated + read methods only, and the fulfilment scheduler takes plain values, so the + cross-aggregate census of [ADR-0042](../../decisions/0042-tenant-provisioning-cross-aggregate-transaction.md) + counts every data-request handler as a single-root writer. + ## Entity-relationship diagram ```mermaid diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index a9df6541..b21135a9 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -88,6 +88,29 @@ race returns conflict with truthful failed-attempt evidence, never another successful acceptance row. No provider attempt receipt or UI poll declares a successful Membership mutation. +## Data request bindings + +The live-session request API of [ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) +§ 13 and [ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 4. +Every creation, cancellation and revocation is a MUST row about its aggregate on the +business transaction. An administrator's read of the group's requests and every ticket +mint and chunk read are MUST `read-sensitive` rows written before the disclosure commits, +so an audit row that cannot be written refuses the disclosure (`audit_unavailable`). The +subject's own list, receipt and replay-receipt reads (`ListOwnDataRequestsQuery`, +`GetOwnDataRequestQuery`, `ReadOwnDataRequestReceiptQuery`) are explicit Off registrations, +as the other own reads are. + +| Resource | Operation | Class | Why | +|---|---|---|---| +| DataSubjectRequest | `identity.data_request.create_export` | **MUST** (`create`) | `CreateOwnDataExportCommand` (the subject) and `CreateDataExportForSubjectCommand` (an administrator) share this slug; one row about the new request with its frozen Membership snapshot, on the transaction that also submits its export job. A refused creation (`request_already_active`, `blocked_hold`) writes the row with its refusal and stores nothing. | +| DataSubjectRequest | `identity.data_request.cancel` | **MUST** (`update`) | `CancelOwnDataRequestCommand` and `CancelDataRequestCommand`; `requested → cancelled` under the shared tenant fence with the expected version. | +| DataExportArtifact | `identity.data_export.revoke` | **MUST** (`delete`) | `RevokeOwnDataExportCommand` and `RevokeDataExportCommand`; the unexpired artifact becomes `revoked` and its chunks are deleted on the same transaction. Ciphertext is never tracked, so no chunk reaches the row. | +| DataExportTicket | `identity.data_export.mint_ticket` | **MUST** (`read-sensitive`) | `MintOwnDataExportTicketCommand`; one row about the new ticket. Its digest and session-binding digest are `[PiiSensitive]` and redacted in the capture; the ticket itself exists only in the response. | +| DataExportTicket | `identity.data_export.read_chunk` | **MUST** (`read-sensitive`) | `ReadOwnDataExportChunkCommand`; one row per chunk read, about the ticket that authorized it; the final chunk's row also carries the ticket's consumption. No plaintext, ciphertext or ticket enters the row. | +| Data request directory | `identity.data_request.list` | **MUST** (`read-sensitive`) | `ListDataRequestsQuery`: the group's export and erasure requests, status and counts only, never a closure. | +| DataSubjectRequest | `identity.data_request.read` | **MUST** (`read-sensitive`) | `GetDataRequestQuery`: an administrator's read of another person's request (ADR-0106 § 13), status and counts only. | +| Original DataSubjectRequest outcome | `identity.data_request.read_receipt` | **MUST** (`read-sensitive`) | `ReadDataRequestReceiptQuery`: fresh disclosure admission of the original request before an administrator's keyed replay; never reruns the mutation. | + `AcceptInvitationCommandHandler` is the only added two-root exception: central plural MUST intents for Invitation and the actual Membership share one ordinary unit of work. No User/provider transaction joins it. A missing required row or diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md index 92f1b82f..b2288c15 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -45,6 +45,7 @@ adoption supplies identity facts; it does not independently grant seed authority | `MembershipProfile` | – | Tenant + Organization | – | – | Exact v1 manifest, bounded contextual fields | | `Invitation` | – | – | – | Existing Tenant + Organization membership-admin | ADR-0093's exact invitation operations; no new assignable key | | `FederationConnection` | – | – | – | Tenant `identity.federation.admin` | Registry v4; granted to no Role by registration; explicit Tenant Admin adoption only | +| `DataSubjectRequest` | – | – | – | Existing Tenant + Organization membership-admin | ADR-0106 § 4: the administrator's operations reuse the existing pairs; the subject's own operations carry no key. No assignable key is added | Empty cells mean no foundation key exists. Bootstrap/seed verification reads do not invent directory/read keys; their exact owner/audit classification is @@ -176,6 +177,28 @@ session admission. Private SMTP source custody/job execution is finite trusted infrastructure admission, not a human permission or SystemActor bypass; Standard 05 and the module specification own its exact source/lease consumers. +## Subject data request bindings + +**Accepted under [ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) § 3–§ 4 +and [ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 4.** No assignable +key is added and the grant union's bytes do not change. The subject's live-session operations use the +key-less `OwnDataRequest` kind (an Active Membership in exactly the announced group; operation ids under +`identity.data_request.`); the administrator's are Protected on the existing +`[identity.membership.admin at Tenant, at Organization]` alternatives. Every operation is confined to the +announced group, and a request of another group, person or tenant is absent (`not_found`). The +[audit matrix](audit.md#data-request-bindings) owns the classifications. + +| Application consumer | Capability / exact authority | Boundary | +|---|---|---| +| `CreateOwnDataExportCommand` | `OwnDataRequest` | The subject files for themselves under their exclusive User fence and the shared tenant fence; one active export per subject and group | +| `ListOwnDataRequestsQuery`, `GetOwnDataRequestQuery`, `ReadOwnDataRequestReceiptQuery` | `OwnDataRequest` | Only requests about the actor, in the group; Off | +| `CancelOwnDataRequestCommand` | `OwnDataRequest` | The subject cancels a request about them, whoever filed it, with `If-Match` | +| `RevokeOwnDataExportCommand` | `OwnDataRequest` | The subject revokes an unexpired artifact of a request about them, including one an administrator filed | +| `MintOwnDataExportTicketCommand`, `ReadOwnDataExportChunkCommand` | `OwnDataRequest` and the session binding | Subject only; the ticket binds the credential of the session that minted it. An administrator never gets a ticket or content | +| `CreateDataExportForSubjectCommand` | Applicable membership-admin covering the group | For the person who holds or held the named Membership of any status in the group; never for oneself; a Tenant holder files in the announced group, an Organization holder only in their organization's | +| `ListDataRequestsQuery`, `GetDataRequestQuery`, `ReadDataRequestReceiptQuery` | Same | The group's exports and erasures, status and counts only, never a closure; MUST sensitive read | +| `CancelDataRequestCommand`, `RevokeDataExportCommand` | Same, and the actor filed the request | Another administrator reads the request but cannot cancel it or revoke its artifact | + ## Proof ownership P03-1 Step 4 proves actual command metadata, the nonempty five-pair registry, diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 2ea40c11..639ce78a 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -5531,12 +5531,14 @@ structural test proves — and what it does not. #### `Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly` -- **Asserts:** the production census closes the finite HTTP surface at 72 MVC - actions and 67 distinct `IRequest` roots (both totals asserted on the literal census +- **Asserts:** the production census closes the finite HTTP surface at 84 MVC + actions and 79 distinct `IRequest` roots (both totals asserted on the literal census that the rule binds to production), including the public and authenticated - reads, the anonymous sign-in read, 23 protected keyed writes, native - session-scope admission and the eleven ADR-0099 federation actions, which reach - their requests only through `FederationOperationRunner`. It also + reads, the anonymous sign-in read, 29 protected keyed writes, native + session-scope admission, the eleven ADR-0099 federation actions, which reach + their requests only through `FederationOperationRunner`, and the twelve + ADR-0106/ADR-0107 data-request actions (six of them keyed; the ticket mint and + the chunk read each sit on a controller of their own, unkeyed). It also checks the separate three exact GlobalSelf middleware routes. The canonical name is historical: administration includes writes, and sensitive reads can require a ReadWrite owner to commit MUST audit evidence. AccountSite and public diff --git a/frontend/packages/sdk/src/administration-contract.ts b/frontend/packages/sdk/src/administration-contract.ts index 72e91789..d89e4374 100644 --- a/frontend/packages/sdk/src/administration-contract.ts +++ b/frontend/packages/sdk/src/administration-contract.ts @@ -94,4 +94,8 @@ export const ADMINISTRATION_GET_CONTRACTS = Object.freeze({ '/api/v1/identity/invitations/{id}': 'GetInvitation', '/api/v1/identity/invitable-roles': 'ListInvitableRoles', '/api/v1/tenancy/settings/invitation-policy': 'GetTenantInvitationPolicy', + '/api/v1/identity/me/data-requests': 'ListOwnDataRequests', + '/api/v1/identity/me/data-requests/{id}': 'GetOwnDataRequest', + '/api/v1/identity/data-requests': 'ListDataRequests', + '/api/v1/identity/data-requests/{id}': 'GetDataRequest', } as const); diff --git a/frontend/packages/sdk/src/authenticated-contract.test.ts b/frontend/packages/sdk/src/authenticated-contract.test.ts index d6aa7c56..ec02908a 100644 --- a/frontend/packages/sdk/src/authenticated-contract.test.ts +++ b/frontend/packages/sdk/src/authenticated-contract.test.ts @@ -84,6 +84,10 @@ describe('generated GET contract ownership', () => { '/api/v1/identity/invitations/{id}': 'GetInvitation', '/api/v1/identity/invitable-roles': 'ListInvitableRoles', '/api/v1/tenancy/settings/invitation-policy': 'GetTenantInvitationPolicy', + '/api/v1/identity/me/data-requests': 'ListOwnDataRequests', + '/api/v1/identity/me/data-requests/{id}': 'GetOwnDataRequest', + '/api/v1/identity/data-requests': 'ListDataRequests', + '/api/v1/identity/data-requests/{id}': 'GetDataRequest', }); expect(PUBLIC_GET_CONTRACTS).toEqual({ '/api/v1/public/site': 'GetPublicSite', @@ -123,6 +127,10 @@ describe('generated GET contract ownership', () => { | 'GetOwnMembershipFieldConsent' | 'ListOwnFieldConsentScopes' | 'ListOwnMembershipFieldConsents' + | 'ListOwnDataRequests' + | 'GetOwnDataRequest' + | 'ListDataRequests' + | 'GetDataRequest' >(); expect(RootContracts).toBe(AUTHENTICATED_GET_CONTRACTS); expectTypeOf().toEqualTypeOf(); diff --git a/frontend/packages/sdk/src/generated/schema.d.ts b/frontend/packages/sdk/src/generated/schema.d.ts index 7c268b4c..7d079931 100644 --- a/frontend/packages/sdk/src/generated/schema.d.ts +++ b/frontend/packages/sdk/src/generated/schema.d.ts @@ -267,6 +267,210 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/identity/me/data-requests/exports": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject files an export of their own data in the session's group (ADR-0106 § 3). Requires an Active Membership in exactly that group; no permission key. The request holds the frozen snapshot of the subject's Memberships of any status in the group and its job is submitted on the same transaction. Strict empty JSON object. MUST audited. */ + post: operations["CreateOwnDataExport"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description The subject's own requests in the session's group, newest first. A request whose job died is shown failed. Audit Off. No request body. */ + get: operations["ListOwnDataRequests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description The subject's own request receipt: identity, kind, origin, status, timestamps, the recorded refusal or failure code, the closed retained-reference kinds and counts and the artifact's metadata. No content. Audit Off. No request body. */ + get: operations["GetOwnDataRequest"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests/{id}/cancellations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject cancels a requested export (requested to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited. */ + post: operations["CancelOwnDataRequest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests/{id}/artifact/revocations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject revokes an unexpired available artifact of a request about them, which deletes its chunks at once; the metadata stays as the receipt. Strict empty JSON object. MUST audited. */ + post: operations["RevokeOwnDataExport"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests/{id}/artifact/tickets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject mints a fifteen-minute download cursor over their own available, unexpired artifact, bound to the credential of this session; an administrator never gets one. Stored only as a digest; not keyed and never replayed; no If-Match. Strict empty JSON object. MUST read-sensitive audited; refused when the row cannot be written. */ + post: operations["MintOwnDataExportTicket"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/data-requests/{id}/artifact/chunks": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Reads one decrypted chunk through a ticket presented in the body, never the URL, in the session that minted it. Any index below count may be read while the ticket is unconsumed and unexpired; serving the final chunk (count - 1) consumes it, and a resumed download mints a new ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written. */ + post: operations["ReadOwnDataExportChunk"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-requests/exports": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description An administrator holding identity.membership.admin over the group files an export for the person who holds or held the named Membership, of any status, in the group; never for themselves. The administrator sees status and counts only and never receives the bundle. Strict JSON object with membershipId only. MUST audited. */ + post: operations["CreateDataExportForSubject"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-requests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description The group's export and erasure requests, newest first: status and counts only, never content, never a closure. MUST read-sensitive audited; refused when the row cannot be written. No request body. */ + get: operations["ListDataRequests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-requests/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description One request of the group: status and counts only, never content. MUST read-sensitive audited; refused when the row cannot be written. No request body. */ + get: operations["GetDataRequest"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-requests/{id}/cancellations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The administrator who filed an export cancels it while it is still requested. Strict empty JSON object. MUST audited. */ + post: operations["CancelDataRequest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-requests/{id}/artifact/revocations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The administrator who filed an export revokes its unexpired available artifact, which deletes its chunks at once. Strict empty JSON object. MUST audited. */ + post: operations["RevokeDataExport"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/identity/federation": { parameters: { query?: never; @@ -1346,6 +1550,105 @@ export interface components { [key: string]: components["schemas"]["CustomFieldValueNode2"]; }; CustomFieldValueNode2: string | number | boolean; + DataExportArtifactResponse: { + /** Format: uuid */ + id: string; + /** @enum {string} */ + status: "available" | "revoked" | "expired" | "purged"; + /** Format: date-time */ + expiresAt: string; + /** Format: date-time */ + purgedAt: null | string; + /** Format: int64 */ + byteCount: number; + /** Format: int32 */ + chunkCount: number; + truncations: components["schemas"]["DataExportTruncationResponse"][]; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + readable: boolean; + }; + DataExportChunkInput: { + /** @description Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log. */ + ticket: string; + /** Format: int32 */ + index: number; + }; + DataExportChunkResponse: { + /** Format: int32 */ + index: number; + /** Format: int32 */ + count: number; + /** @description Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk in index order yields the bundle. */ + bytes: string; + }; + DataExportForSubjectInput: { + /** Format: uuid */ + membershipId: string; + }; + DataExportTicketResponse: { + /** @description Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log. */ + ticket: string; + /** Format: date-time */ + expiresAt: string; + /** Format: int32 */ + chunkCount: number; + /** Format: int64 */ + byteCount: number; + }; + DataExportTruncationResponse: { + collection: string; + /** Format: int64 */ + included: number; + /** Format: int64 */ + total: number; + }; + DataRequestAcceptedResponse: { + /** Format: uuid */ + id: string; + /** @enum {string} */ + kind: "export"; + /** @enum {string} */ + status: "requested"; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; + DataRequestPage: { + items: components["schemas"]["DataRequestResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + DataRequestResponse: { + /** Format: uuid */ + id: string; + /** @enum {string} */ + kind: "export" | "erasure" | "closure"; + /** @enum {string} */ + origin: "self" | "administrator" | "closure_fanout"; + /** @enum {string} */ + status: "requested" | "scheduled" | "fulfilling" | "awaiting_privileged_step" | "completed" | "blocked" | "failed" | "cancelled"; + /** Format: date-time */ + createdAt: string; + /** Format: date-time */ + updatedAt: null | string; + /** Format: date-time */ + completedAt: null | string; + /** @enum {null|string} */ + lastRefusal: "blocked_window" | "blocked_hold" | "blocked_last_administrator" | null; + /** @enum {null|string} */ + failureReason: "export_too_large" | "execution_failed" | null; + retained: components["schemas"]["DataRequestRetainedResponse"][]; + artifact: components["schemas"]["DataExportArtifactResponse"] | null; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + requestedByYou: boolean; + membershipIds: string[]; + }; + DataRequestRetainedResponse: { + /** @enum {string} */ + kind: "consent_evidence" | "invitation_record" | "invitation_envelope" | "audit_actor_reference" | "audit_entity_reference" | "audit_metadata_reference" | "unscoped_audit_rows" | "transport_evidence" | "execution_evidence" | "provider_event_record" | "idempotency_cache" | "attribution_reference" | "federation_actor_reference" | "request_receipt" | "external_copy" | "unserved_group"; + /** Format: int64 */ + count: number; + }; DefaultOrganizationInput: { /** Format: uuid */ organizationId: string; @@ -1690,6 +1993,34 @@ export interface components { canManageCustomFields: boolean; canManageFederation: boolean; }; + OwnDataRequestPage: { + items: components["schemas"]["OwnDataRequestResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + OwnDataRequestResponse: { + /** Format: uuid */ + id: string; + /** @enum {string} */ + kind: "export" | "erasure" | "closure"; + /** @enum {string} */ + origin: "self" | "administrator" | "closure_fanout"; + /** @enum {string} */ + status: "requested" | "scheduled" | "fulfilling" | "awaiting_privileged_step" | "completed" | "blocked" | "failed" | "cancelled"; + /** Format: date-time */ + createdAt: string; + /** Format: date-time */ + updatedAt: null | string; + /** Format: date-time */ + completedAt: null | string; + /** @enum {null|string} */ + lastRefusal: "blocked_window" | "blocked_hold" | "blocked_last_administrator" | null; + /** @enum {null|string} */ + failureReason: "export_too_large" | "execution_failed" | null; + retained: components["schemas"]["DataRequestRetainedResponse"][]; + artifact: components["schemas"]["DataExportArtifactResponse"] | null; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; OwnFieldConsentCurrentResponse: { consent: components["schemas"]["ConsentDetailsResponse"] | null; }; @@ -4620,6 +4951,1580 @@ export interface operations { }; }; }; + CreateOwnDataExport: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Accepted: the request's initial resource. Its export runs as a background job; read the Location for its status. */ + 202: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + /** @description Exact same-API relative location of the new request's receipt. */ + Location: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataRequestAcceptedResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ListOwnDataRequests: { + parameters: { + query?: { + /** @description Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse. */ + cursor?: string; + /** @description Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse. */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current receipt-safe projection: status and counts, never content. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OwnDataRequestPage"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetOwnDataRequest: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current receipt-safe projection: status and counts, never content. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OwnDataRequestResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CancelOwnDataRequest: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + /** @description One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + RevokeOwnDataExport: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + /** @description One canonical strong quoted decimal artifact version (the receipt's artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The artifact's version after the revocation. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + MintOwnDataExportTicket: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataExportTicketResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ReadOwnDataExportChunk: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["DataExportChunkInput"]; + }; + }; + responses: { + /** @description One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataExportChunkResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no live session the ticket can bind. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CreateDataExportForSubject: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["DataExportForSubjectInput"]; + }; + }; + responses: { + /** @description Accepted: the request's initial resource. Its export runs as a background job; read the Location for its status. */ + 202: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + /** @description Exact same-API relative location of the new request's receipt. */ + Location: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataRequestAcceptedResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden without current identity.membership.admin covering the context's group. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke). */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ListDataRequests: { + parameters: { + query?: { + /** @description Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse. */ + cursor?: string; + /** @description Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse. */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current receipt-safe projection: status and counts, never content. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataRequestPage"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden without current identity.membership.admin covering the context's group. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke). */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetDataRequest: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current receipt-safe projection: status and counts, never content. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataRequestResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden without current identity.membership.admin covering the context's group. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke). */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CancelDataRequest: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + /** @description One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden without current identity.membership.admin covering the context's group. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke). */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + RevokeDataExport: { + parameters: { + query?: never; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + /** @description One canonical strong quoted decimal artifact version (the receipt's artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The artifact's version after the revocation. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, extra or repeated query, an unexpected body, an invalid key or precondition, or a key or precondition on a ticket operation. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden without current identity.membership.admin covering the context's group. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke). */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 16 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; GetFederationConnection: { parameters: { query?: never; diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 524e7bc9..bb21c362 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -82,6 +82,8 @@ "LearnStack.Tests.Integration.Database.DataExportArtifactStoreTests", "LearnStack.Tests.Integration.Database.DataExportExecutionTests", "LearnStack.Tests.Integration.Database.DataExportParticipantTests", + "LearnStack.Tests.Integration.Database.DataRequestHttpTests", + "LearnStack.Tests.Integration.Database.DataRequestServiceStorageTests", "LearnStack.Tests.Integration.Database.DataRequestStorageControlTests", "LearnStack.Tests.Integration.Database.DataRequestStorageTests", "LearnStack.Tests.Integration.Database.DatabaseQualificationProofTests", From 33ab8f6282f7c189850e6a0d360e17fb7466ef1e Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 10:13:46 +0300 Subject: [PATCH 08/61] feat(identity): add the retained data-request native entry P03-10 Step 1, unit 4b: the six retained-entry operations for a person without a live Membership (a Suspended or revoked one), mirroring the consent-subject entry: the closed OwnDataRequestOperation paths, the native credential capture, the one minting source and resolver branch, the OwnDataRequestEntry policies and handlers over the live executors, keyed create and cancel replays, the ticket session binding, and the closed-set negative tests. Also pins the new controllers in the job manifest census. ADR: 0106, 0107, 0095 Module: Identity, Api Co-Authored-By: Claude Sonnet 5.5 --- backend/openapi/v1.json | 1900 +++++++++++++++++ .../HttpAuthorizationTransportSource.cs | 5 +- .../HttpDataExportSessionBinding.cs | 38 + .../LiveAuthorizationRegistration.cs | 5 + .../NativeSessionSourceFeature.cs | 9 +- .../NativeSessionSourceMiddleware.cs | 5 +- .../OperationAuthorizationPolicyProvider.cs | 12 +- .../OperationHttpClassification.cs | 8 +- .../OwnDataRequestEntryRequest.cs | 18 + .../Authentication/OwnDataRequestHttpInput.cs | 224 ++ .../Authentication/OwnDataRequestOperation.cs | 44 + .../OwnDataRequestSubjectSource.cs | 185 ++ .../TenantAuthenticationRegistration.cs | 8 + .../TenantAuthorizationCandidateSource.cs | 16 +- ...enantIdentityBindingAdmissionMiddleware.cs | 2 +- .../ValidatedOwnDataRequestCredential.cs | 83 + .../Common/AdministrationHttpSurface.cs | 3 + .../ProtectedAdministrationOperation.cs | 21 +- .../ProtectedAdministrationResult.cs | 4 +- .../Idempotency/ProtectedIdempotencyFilter.cs | 4 +- .../ProtectedReceiptReplayDispatcher.cs | 5 + .../ProtectedReplayHttpAdmission.cs | 38 +- .../DataRequestDocumentTransformer.cs | 160 ++ .../Identity/DataRequestEntryController.cs | 112 + .../Tenancy/TenantResolverMiddleware.cs | 20 + .../DataRequests/DataRequestOperations.cs | 54 + .../Audit/IdentityAuditCatalogSource.cs | 8 + .../RetainedDataRequestHandlers.cs | 171 ++ .../IdentityOperationPolicySource.cs | 16 + .../IdentityFoundationRegistration.cs | 4 + ...HttpSurfaceTests.ConsentAndCustomFields.cs | 37 + ...eTests.ProtectedAdministration.Controls.cs | 4 +- ...ttpSurfaceTests.ProtectedAdministration.cs | 2 + ...edHttpSurfaceTests.ProtectedDescriptors.cs | 10 +- .../AuthenticatedHttpSurfaceTests.cs | 29 +- ...uthenticationAuthorityTests.DataRequest.cs | 218 ++ .../AuthenticationAuthorityTests.Shapes.cs | 31 +- .../AuthenticationAuthorityTests.cs | 26 +- .../BackgroundJobManifestBoundaryTests.cs | 5 + .../IdempotencyConventionTests.cs | 19 +- ...itConventionTests.AuthorizationEvidence.cs | 4 + .../OperationPolicyOwnershipTests.Http.cs | 17 +- .../OperationPolicyOwnershipTests.cs | 2 +- .../OwnDataRequestScopeConventionTests.cs | 102 +- .../OpenApiContractTests.DataRequests.cs | 89 + .../OpenApiContractTests.cs | 5 +- .../Api/OperationHttpClassificationTests.cs | 17 +- ...ticatedHttpSurfaceRuntimeTests.Metadata.cs | 3 +- .../AuthenticatedHttpSurfaceRuntimeTests.cs | 36 +- .../DataRequestHttpTests.RetainedEntry.cs | 401 ++++ .../OwnDataRequestEntryInputTests.cs | 175 ++ .../OperationPolicyCatalogTests.cs | 16 +- docs/modules/identity/README.md | 48 + docs/modules/identity/audit.md | 15 + docs/modules/identity/permissions.md | 21 + docs/standards/05-database.md | 5 +- docs/standards/11-security.md | 19 + .../21-architecture-tests-catalogue.md | 37 +- .../sdk/src/administration-contract.ts | 2 + .../sdk/src/authenticated-contract.test.ts | 4 + .../packages/sdk/src/generated/schema.d.ts | 900 ++++++++ 61 files changed, 5388 insertions(+), 93 deletions(-) create mode 100644 backend/src/LearnStack.Api/Authentication/OwnDataRequestEntryRequest.cs create mode 100644 backend/src/LearnStack.Api/Authentication/OwnDataRequestHttpInput.cs create mode 100644 backend/src/LearnStack.Api/Authentication/OwnDataRequestOperation.cs create mode 100644 backend/src/LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs create mode 100644 backend/src/LearnStack.Api/Authentication/ValidatedOwnDataRequestCredential.cs create mode 100644 backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs create mode 100644 backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs create mode 100644 backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.DataRequest.cs create mode 100644 backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs create mode 100644 backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs diff --git a/backend/openapi/v1.json b/backend/openapi/v1.json index e209654e..c1b5e300 100644 --- a/backend/openapi/v1.json +++ b/backend/openapi/v1.json @@ -6175,6 +6175,1817 @@ "x-version-introduced": "v1" } }, + "/api/v1/identity/data-request-entry/scopes": { + "get": { + "tags": [ + "DataRequestEntry" + ], + "description": "The retained own scope of ADR-0106 \u00A7 9: the groups on the real host where the verified subject holds or held a Membership of any status or has a data request. On an organization host only that organization\u0027s group. No Active Membership, no ordinary native session and no tenant or organization selector. Audit Off. No request body.", + "operationId": "ListRetainedDataRequestScopes", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "The previous page\u0027s nextCursor: the last group\u0027s key (tenant or an organization UUIDv7).", + "schema": { + "maxLength": 36, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + "schema": { + "maximum": 20, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "The subject\u0027s retained groups on the real host, in order.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetainedDataRequestScopePageResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-request-entry/requests": { + "get": { + "tags": [ + "DataRequestEntry" + ], + "description": "The subject\u0027s own requests in one retained group, newest first, for a Suspended person, a person whose Membership was revoked or a group where only a request survives. A request whose job died is shown failed. Audit Off. No request body.", + "operationId": "ListRetainedDataRequests", + "parameters": [ + { + "name": "group", + "in": "query", + "description": "The one retained group the operation acts in: tenant for the real host\u0027s tenant-wide group, or the organization\u0027s canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 6, + "pattern": "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + "type": "string" + } + }, + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "schema": { + "maxLength": 1024, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + "schema": { + "maximum": 20, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnDataRequestPage" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-request-entry/exports": { + "post": { + "tags": [ + "DataRequestEntry" + ], + "description": "The subject files an export of their own data in one retained group (ADR-0106 \u00A7 3, \u00A7 9). Refused when the subject holds no Membership of any status there. Strict empty JSON object. MUST audited.", + "operationId": "CreateRetainedDataExport", + "parameters": [ + { + "name": "group", + "in": "query", + "description": "The one retained group the operation acts in: tenant for the real host\u0027s tenant-wide group, or the organization\u0027s canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 6, + "pattern": "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + "type": "string" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "Accepted: the request\u0027s initial resource. Its export runs as a background job; read the group\u0027s requests for its status.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataRequestAcceptedResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-request-entry/cancellations": { + "post": { + "tags": [ + "DataRequestEntry" + ], + "description": "The subject cancels their own requested export in one retained group (requested to cancelled). Strict JSON object with requestId only. MUST audited.", + "operationId": "CancelRetainedDataRequest", + "parameters": [ + { + "name": "group", + "in": "query", + "description": "The one retained group the operation acts in: tenant for the real host\u0027s tenant-wide group, or the organization\u0027s canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 6, + "pattern": "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + "type": "string" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "description": "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetainedDataRequestTargetInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + }, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-request-entry/tickets": { + "post": { + "tags": [ + "DataRequestEntry" + ], + "description": "The subject mints a fifteen-minute download cursor over their own available, unexpired artifact in one retained group, bound to this retained-entry credential; never honoured on the live path. Strict JSON object with requestId only. Not keyed and never replayed; no If-Match. MUST read-sensitive audited; refused when the row cannot be written.", + "operationId": "MintRetainedDataExportTicket", + "parameters": [ + { + "name": "group", + "in": "query", + "description": "The one retained group the operation acts in: tenant for the real host\u0027s tenant-wide group, or the organization\u0027s canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 6, + "pattern": "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetainedDataRequestTargetInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportTicketResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/data-request-entry/chunks": { + "post": { + "tags": [ + "DataRequestEntry" + ], + "description": "Reads one decrypted chunk through a ticket presented in the body, never the URL, with the retained-entry credential that minted it. Serving the final chunk consumes the ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written.", + "operationId": "ReadRetainedDataExportChunk", + "parameters": [ + { + "name": "group", + "in": "query", + "description": "The one retained group the operation acts in: tenant for the real host\u0027s tenant-wide group, or the organization\u0027s canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + "required": true, + "schema": { + "maxLength": 36, + "minLength": 6, + "pattern": "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetainedDataExportChunkInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DataExportChunkResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; request bodies are at most 4 KiB.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, "/api/v1/identity/me/data-requests/exports": { "post": { "tags": [ @@ -29497,6 +31308,92 @@ } } }, + "RetainedDataExportChunkInput": { + "required": [ + "requestId", + "ticket", + "index" + ], + "type": "object", + "properties": { + "requestId": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "ticket": { + "maxLength": 43, + "minLength": 43, + "pattern": "^[A-Za-z0-9_-]{43}$", + "type": "string", + "description": "Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log." + }, + "index": { + "maximum": 511, + "minimum": 0, + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "RetainedDataRequestScopePageResponse": { + "required": [ + "items", + "pageInfo" + ], + "type": "object", + "properties": { + "items": { + "maxItems": 20, + "type": "array", + "items": { + "$ref": "#/components/schemas/RetainedDataRequestScopeResponse" + } + }, + "pageInfo": { + "$ref": "#/components/schemas/PageInfo" + } + }, + "additionalProperties": false + }, + "RetainedDataRequestScopeResponse": { + "required": [ + "tenantId", + "organizationId" + ], + "type": "object", + "properties": { + "tenantId": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + }, + "organizationId": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": [ + "null", + "string" + ], + "format": "uuid" + } + }, + "additionalProperties": false + }, + "RetainedDataRequestTargetInput": { + "required": [ + "requestId" + ], + "type": "object", + "properties": { + "requestId": { + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, "RoleDetailResponse": { "required": [ "roleId", @@ -29803,6 +31700,9 @@ { "name": "PublicSite" }, + { + "name": "DataRequestEntry" + }, { "name": "OwnDataRequests" }, diff --git a/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs b/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs index 54f57371..1cbc8368 100644 --- a/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs +++ b/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs @@ -29,7 +29,10 @@ internal sealed class HttpAuthorizationTransportSource(IHttpContextAccessor acce } private static bool MatchesScope(HttpContext http, ValidatedTenantIdentity identity, OperationInvocation invocation) => - http.Features.Get() is { } consent + http.Features.Get() is { } dataRequest + ? invocation.TenantId is { } scope && dataRequest.MatchesScope(http, scope, invocation.OrganizationId) + && dataRequest.Actor == invocation.Actor + : http.Features.Get() is { } consent ? invocation.TenantId is { } tenant && consent.MatchesScope(http, tenant, invocation.OrganizationId) : http.Features.Get() is { } invitation ? invitation.IsCurrent(http) && invitation.Offer!.Actor == invocation.Actor && invitation.Offer.TenantId == invocation.TenantId diff --git a/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs b/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs index fb05a842..55300fb4 100644 --- a/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs +++ b/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs @@ -21,15 +21,31 @@ namespace LearnStack.Api.Authentication; /// The raw credential never leaves this method; only its digest enters the binding, and the binding is itself only /// a digest on the ticket row, which the audit capture redacts. /// +/// +/// The retained own-scope entry (ADR-0106 § 9) binds under its own domain. There the binding is captured only +/// while the request's is current on a ticket or chunk purpose for exactly +/// this actor and group, from the digest of the exact Authorization header its credential capture recorded at +/// validation. The separate domain means a ticket minted on one path is never honoured on the other, even for the +/// same person, group and credential. As on the live path the native credential is the session: when the BFF's entry +/// handle refreshes it the binding no longer matches, that download's cursor ends and the resumed download mints a +/// new ticket. +/// /// internal sealed class HttpDataExportSessionBinding(IHttpContextAccessor accessor) : IDataExportSessionBinding { private const string Domain = "learnstack.data_export.session.v1"; + private const string RetainedDomain = "learnstack.data_export.retained_session.v1"; private const string Prefix = "Bearer "; public string? Capture(UserId actor, TenantId tenant, OrganizationId? organization) { var http = accessor.HttpContext; + if (http is not null && (http.Features.Get() is not null + || http.Features.Get()?.DataRequestOperation is not null)) + { + return CaptureRetained(http, actor, tenant, organization); + } + if (http is null || http.RequestAborted.IsCancellationRequested || http.Features.Get() is not { VerifiedSubject: { } subject, Identity: { } identity } || identity.ActorUserId != actor || actor == UserId.SystemActor @@ -50,6 +66,28 @@ internal sealed class HttpDataExportSessionBinding(IHttpContextAccessor accessor return Convert.ToHexStringLower(digest.GetHashAndReset()); } + private static string? CaptureRetained(HttpContext http, UserId actor, TenantId tenant, OrganizationId? organization) + { + if (http.RequestAborted.IsCancellationRequested || actor == UserId.SystemActor + || http.Features.Get() is not { } source + || source.DownloadCredential(http, actor, tenant, organization) is not { } credential + || http.Features.Get() is not { VerifiedSubject: { } subject, Identity: { } identity } + || identity.ActorUserId != actor || !ReferenceEquals(credential.Subject, subject)) + { + return null; + } + + using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Append(digest, RetainedDomain); + Append(digest, tenant.Value.ToString("D")); + Append(digest, organization?.Value.ToString("D") ?? string.Empty); + Append(digest, actor.Value.ToString("D")); + Append(digest, subject.Issuer); + Append(digest, subject.Subject); + Append(digest, credential.CredentialDigest); + return Convert.ToHexStringLower(digest.GetHashAndReset()); + } + private static void Append(IncrementalHash digest, string value) { var bytes = Encoding.UTF8.GetBytes(value); diff --git a/backend/src/LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs b/backend/src/LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs index b643bf98..1d832d85 100644 --- a/backend/src/LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs +++ b/backend/src/LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs @@ -46,6 +46,11 @@ internal static IServiceCollection AddLearnStackLiveAuthorization(this IServiceC provider.GetRequiredService(), provider.GetRequiredService(), () => provider.GetRequiredService())); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => new OwnDataRequestSubjectSource( + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService(), () => provider.GetRequiredService())); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddSingleton(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/src/LearnStack.Api/Authentication/NativeSessionSourceFeature.cs b/backend/src/LearnStack.Api/Authentication/NativeSessionSourceFeature.cs index 21c6baf3..f144bee4 100644 --- a/backend/src/LearnStack.Api/Authentication/NativeSessionSourceFeature.cs +++ b/backend/src/LearnStack.Api/Authentication/NativeSessionSourceFeature.cs @@ -24,7 +24,8 @@ internal sealed class NativeSessionSourceFeature internal NativeSessionSourceFeature(HttpContext request, HostClassification host, VerifiedProviderSubject subject, SubjectAdmissionDecision decision, TenantSubjectAdmissionProvenance provenance, TenantId? tenant, OrganizationId? organization, - GlobalSelfOperation? operation, EffectiveHostAccessor hosts, NativeSessionSourcePolicy policy, IClock clock, InvitationEntryOperation? invitationOperation = null, ConsentSubjectOperation? consentOperation = null) + GlobalSelfOperation? operation, EffectiveHostAccessor hosts, NativeSessionSourcePolicy policy, IClock clock, InvitationEntryOperation? invitationOperation = null, ConsentSubjectOperation? consentOperation = null, + OwnDataRequestOperation? dataRequestOperation = null) { _request = request; _host = host; @@ -43,6 +44,7 @@ internal NativeSessionSourceFeature(HttpContext request, HostClassification host GlobalOperation = operation; InvitationOperation = invitationOperation; ConsentOperation = consentOperation; + DataRequestOperation = dataRequestOperation; } internal TenantId? Tenant { get; } @@ -50,6 +52,7 @@ internal NativeSessionSourceFeature(HttpContext request, HostClassification host internal GlobalSelfOperation? GlobalOperation { get; } internal InvitationEntryOperation? InvitationOperation { get; } internal ConsentSubjectOperation? ConsentOperation { get; } + internal OwnDataRequestOperation? DataRequestOperation { get; } internal bool IsCurrent(HttpContext request) => ReferenceEquals(_request, request) && !request.RequestAborted.IsCancellationRequested @@ -71,7 +74,9 @@ internal bool IsCurrent(HttpContext request) => && ReferenceEquals(InvitationEntryOperation.ForPath(request.Request.Path), InvitationOperation) && (InvitationOperation is null || InvitationOperation.Matches(request)) && ReferenceEquals(ConsentSubjectOperation.ForPath(request.Request.Path), ConsentOperation) - && (ConsentOperation is null || ConsentOperation.Matches(request)); + && (ConsentOperation is null || ConsentOperation.Matches(request)) + && ReferenceEquals(OwnDataRequestOperation.ForPath(request.Request.Path), DataRequestOperation) + && (DataRequestOperation is null || DataRequestOperation.Matches(request)); public override string ToString() => nameof(NativeSessionSourceFeature); diff --git a/backend/src/LearnStack.Api/Authentication/NativeSessionSourceMiddleware.cs b/backend/src/LearnStack.Api/Authentication/NativeSessionSourceMiddleware.cs index 46efef22..a1b49388 100644 --- a/backend/src/LearnStack.Api/Authentication/NativeSessionSourceMiddleware.cs +++ b/backend/src/LearnStack.Api/Authentication/NativeSessionSourceMiddleware.cs @@ -63,11 +63,12 @@ public async Task InvokeAsync(HttpContext context, EffectiveHostAccessor hosts, var operation = GlobalSelfOperation.ForPath(context.Request.Path); var invitation = InvitationEntryOperation.ForPath(context.Request.Path); var consent = ConsentSubjectOperation.ForPath(context.Request.Path); + var dataRequest = OwnDataRequestOperation.ForPath(context.Request.Path); var hasTenant = context.Request.Headers.ContainsKey(NativeSessionSourcePolicy.TenantHeader); var hasOrganization = context.Request.Headers.ContainsKey(NativeSessionSourcePolicy.OrganizationHeader); TenantId? tenant = null; OrganizationId? organization = null; - if (operation is not null || invitation is not null || consent is not null) + if (operation is not null || invitation is not null || consent is not null || dataRequest is not null) { if (hasTenant || hasOrganization) { @@ -100,7 +101,7 @@ public async Task InvokeAsync(HttpContext context, EffectiveHostAccessor hosts, } context.Features.Set(new NativeSessionSourceFeature(context, host, subject, decision, provenance, - tenant, organization, operation, hosts, policy, clock, invitation, consent)); + tenant, organization, operation, hosts, policy, clock, invitation, consent, dataRequest)); await next(context); } diff --git a/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs b/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs index c25a618a..f5f6b145 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationAuthorizationPolicyProvider.cs @@ -25,7 +25,7 @@ internal sealed class OperationAuthorizationPolicyProvider(IOptions() is { } dataRequest && dataRequest.IsCurrent(http) + && dataRequest.EffectiveRequestType is { } dataRequestType + ? ProtectedAdministrationDescriptor.ForRequest(policy.RequestType) is not null + ? await ProtectedReplayHttpAdmission.AuthorizeAsync(http, policy, classifier, + tenantContext, store, candidates, operations) + : await operations().CheckHttpAsync(dataRequestType, http.GetEndpoint()!, http.RequestAborted) + : LearnStack.SharedKernel.Results.Result.Fail(TenantContextFactory.Refused) + : policy.Kind == OperationPolicyKind.OwnConsentEntry ? http.Features.Get() is { } consent && consent.IsCurrent(http) && consent.EffectiveRequestType is { } consentType ? ProtectedAdministrationDescriptor.ForRequest(policy.RequestType) is not null diff --git a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs index e736dd46..9b0da761 100644 --- a/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs +++ b/backend/src/LearnStack.Api/Authentication/OperationHttpClassification.cs @@ -94,7 +94,7 @@ internal HttpOperationClassification Classify(Endpoint? endpoint, out OperationP } else if (found.Kind is OperationPolicyKind.AccountRead or OperationPolicyKind.Protected or OperationPolicyKind.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead or OperationPolicyKind.InvitationEntry or OperationPolicyKind.OwnConsentEntry or OperationPolicyKind.OwnFieldConsentGrant - or OperationPolicyKind.OwnDataRequest) + or OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry) { if (anonymous.Count != 0 || authorization.Count != 1 || authorization[0].AuthenticationSchemes != TenantAuthenticationRegistration.Scheme @@ -223,6 +223,12 @@ private static bool IsFrameworkMethodRejection(Endpoint endpoint) => endpoint.Ge var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Get)) => (typeof(GetDataRequestQuery), "GetDataRequest", "GET"), var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Cancel)) => (typeof(CancelDataRequestCommand), "CancelDataRequest", "POST"), var pair when pair == (typeof(DataRequestsController), nameof(DataRequestsController.Revoke)) => (typeof(RevokeDataExportCommand), "RevokeDataExport", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.Scopes)) => (typeof(ListRetainedDataRequestScopesQuery), "ListRetainedDataRequestScopes", "GET"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.Requests)) => (typeof(ListRetainedDataRequestsQuery), "ListRetainedDataRequests", "GET"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.CreateExport)) => (typeof(CreateRetainedDataExportCommand), "CreateRetainedDataExport", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.Cancel)) => (typeof(CancelRetainedDataRequestCommand), "CancelRetainedDataRequest", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.MintTicket)) => (typeof(MintRetainedDataExportTicketCommand), "MintRetainedDataExportTicket", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.ReadChunk)) => (typeof(ReadRetainedDataExportChunkCommand), "ReadRetainedDataExportChunk", "POST"), var pair when pair == (typeof(FederationController), nameof(FederationController.Get)) => (typeof(GetFederationConnectionQuery), "GetFederationConnection", "GET"), var pair when pair == (typeof(FederationController), nameof(FederationController.Configure)) => (typeof(BeginConfigureFederationCommand), "ConfigureFederation", "PUT"), var pair when pair == (typeof(FederationController), nameof(FederationController.RotateSecret)) => (typeof(BeginRotateFederationSecretCommand), "RotateFederationSecret", "POST"), diff --git a/backend/src/LearnStack.Api/Authentication/OwnDataRequestEntryRequest.cs b/backend/src/LearnStack.Api/Authentication/OwnDataRequestEntryRequest.cs new file mode 100644 index 00000000..7b461dfd --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestEntryRequest.cs @@ -0,0 +1,18 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; + +namespace LearnStack.Api.Authentication; + +/// One selected immutable retained-entry request; this feature grants no scope or persistence authority. +internal sealed class OwnDataRequestEntryRequest +{ + internal OwnDataRequestEntryRequest(object request) + { + if (request is not (ListRetainedDataRequestScopesQuery or ListRetainedDataRequestsQuery or CreateRetainedDataExportCommand + or CancelRetainedDataRequestCommand or MintRetainedDataExportTicketCommand or ReadRetainedDataExportChunkCommand + or ReadRetainedDataRequestReceiptQuery)) + throw new ArgumentException("Data request entry request refused."); + Request = request; + } + internal object Request { get; } + public override string ToString() => nameof(OwnDataRequestEntryRequest); +} diff --git a/backend/src/LearnStack.Api/Authentication/OwnDataRequestHttpInput.cs b/backend/src/LearnStack.Api/Authentication/OwnDataRequestHttpInput.cs new file mode 100644 index 00000000..bca7db2a --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestHttpInput.cs @@ -0,0 +1,224 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using LearnStack.Api.Common; +using LearnStack.Api.Idempotency; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Api.Authentication; + +/// +/// Strict request capture for the retained own data-request entry, selected before authorization and model binding +/// (ADR-0106 § 9), as is for the consent subject. +/// +/// +/// +/// The group is a selection, never authority. Every purpose but discovery names exactly one group in the one +/// group query value: the literal tenant for the tenant-wide group or the organization's canonical +/// UUIDv7. The confined definer must then prove that group for the verified subject on the real host. +/// +/// +/// Closed shapes. Only the declared query keys, each once; only the declared body fields, each once; an +/// Idempotency-Key only on creation and cancellation; If-Match only, and always, on cancellation; no +/// other conditional header anywhere. The body is buffered, bounded and cleared once parsed, because the chunk read +/// carries a ticket in it. +/// +/// +internal sealed class OwnDataRequestHttpInput +{ + internal const string TenantWideGroup = "tenant"; + private const int MaximumBody = 4096; + + private readonly string _query; + private readonly string? _ifMatch; + + private OwnDataRequestHttpInput(object request, bool selectsGroup, OrganizationId? organization, DataRequestScopeGroupCursor? after, + int limit, string query, string? ifMatch) + { + Request = request; SelectsGroup = selectsGroup; OrganizationId = organization; After = after; Limit = limit; + _query = query; _ifMatch = ifMatch; + } + + internal object Request { get; } + + /// Whether a group was selected; only discovery selects none. + internal bool SelectsGroup { get; } + + /// The selected group's organization, or for the tenant-wide group. + internal OrganizationId? OrganizationId { get; } + + /// Discovery's cursor: the last group of the previous page. + internal DataRequestScopeGroupCursor? After { get; } + + internal int Limit { get; } + + internal bool IsCurrent(HttpContext http) => (http.Request.QueryString.Value ?? "") == _query + && HeadersAdmit(http.Request, PurposeOf(Request)) + && string.Equals(IfMatch(http.Request), _ifMatch, StringComparison.Ordinal); + + internal static async Task ReadAsync(HttpContext http, OwnDataRequestOperation operation) + { + var purpose = operation.Purpose; + if (!HeadersAdmit(http.Request, purpose)) return null; + long version = 0; + if (purpose == OwnDataRequestPurpose.Cancel && !ProtectedEntityTag.TryRead(http.Request, out version)) return null; + string? cursor = null; string? group = null; var limit = 20; + foreach (var (key, values) in http.Request.Query) + { + if (values.Count != 1 || string.IsNullOrEmpty(values[0])) return null; + var value = values[0]!; + if (key == "group" && purpose != OwnDataRequestPurpose.List && value.Length <= 36) group = value; + else if (key == "cursor" && purpose is OwnDataRequestPurpose.List or OwnDataRequestPurpose.Read + && value.Length <= (purpose == OwnDataRequestPurpose.List ? 36 : DataRequestCursorLimit)) cursor = value; + else if (key == "limit" && purpose is OwnDataRequestPurpose.List or OwnDataRequestPurpose.Read + && int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var parsed) + && parsed is >= 1 and <= OwnDataRequestScopeWitness.MaximumPage + && parsed.ToString(CultureInfo.InvariantCulture) == value) limit = parsed; + else return null; + } + + OrganizationId? organization = null; + if (purpose != OwnDataRequestPurpose.List) + { + if (!TryGroup(group, out organization)) return null; + } + + DataRequestScopeGroupCursor? after = null; + if (purpose == OwnDataRequestPurpose.List && cursor is not null) + { + if (!TryGroup(cursor, out var anchor)) return null; + after = new DataRequestScopeGroupCursor(anchor); + } + + object request; + if (purpose is OwnDataRequestPurpose.List or OwnDataRequestPurpose.Read) + { + if (!await AdministrationHttpInput.ReadHasNoBodyAsync(http)) return null; + request = purpose == OwnDataRequestPurpose.List + ? new ListRetainedDataRequestScopesQuery(cursor, limit) + : new ListRetainedDataRequestsQuery(organization, cursor, limit); + } + else + { + if (!AdministrationHttpInput.SupportsJsonMedia(http.Request)) return null; + var bytes = await ReadBodyAsync(http); + try + { + _ = new UTF8Encoding(false, true).GetCharCount(bytes); + using var json = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 2 }); + var body = json.RootElement; + var parsed = purpose switch + { + OwnDataRequestPurpose.Create => AdministrationHttpInput.HasFields(body) + ? new CreateRetainedDataExportCommand(organization) : null, + OwnDataRequestPurpose.Cancel => TryRequestId(body, out var cancelled, "requestId") + ? new CancelRetainedDataRequestCommand(organization, cancelled, version) : null, + OwnDataRequestPurpose.Ticket => TryRequestId(body, out var ticketed, "requestId") + ? new MintRetainedDataExportTicketCommand(organization, ticketed) : null, + OwnDataRequestPurpose.Chunk => TryChunk(body, organization), + _ => (object?)null, + }; + if (parsed is null) return null; + request = parsed; + } + catch (JsonException) { return null; } + catch (DecoderFallbackException) { return null; } + catch (InvalidOperationException) { return null; } + finally { CryptographicOperations.ZeroMemory(bytes); } + } + + return new(request, purpose != OwnDataRequestPurpose.List, organization, after, limit, + http.Request.QueryString.Value ?? "", IfMatch(http.Request)); + } + + /// The canonical text of a group key: tenant, or the organization's canonical UUID. + internal static string KeyFor(DataRequestScopeGroup group) => + group.OrganizationId is { } organization ? organization.Value.ToString("D") : TenantWideGroup; + + private const int DataRequestCursorLimit = 1024; + + private static bool TryGroup(string? text, out OrganizationId? organization) + { + organization = null; + if (text is null) return false; + if (string.Equals(text, TenantWideGroup, StringComparison.Ordinal)) return true; + if (!AdministrationHttpInput.TryId(text, out var id)) return false; + organization = LearnStack.SharedKernel.Identifiers.OrganizationId.From(id); + return true; + } + + private static bool TryRequestId(JsonElement body, out Guid id, params string[] fields) + { + id = Guid.Empty; + return AdministrationHttpInput.HasFields(body, fields) + && AdministrationHttpInput.TryText(body, "requestId", false, 36, out var text) && AdministrationHttpInput.TryId(text, out id); + } + + private static ReadRetainedDataExportChunkCommand? TryChunk(JsonElement body, OrganizationId? organization) + { + if (!TryRequestId(body, out var id, "requestId", "ticket", "index") + || !AdministrationHttpInput.TryText(body, "ticket", false, 64, out var ticket) || ticket is null + || body.GetProperty("index") is not { ValueKind: JsonValueKind.Number } index + || !index.TryGetInt32(out var position) || position < 0 + || !string.Equals(index.GetRawText(), position.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal)) + return null; + return new ReadRetainedDataExportChunkCommand(organization, id, ticket, position); + } + + private static OwnDataRequestPurpose PurposeOf(object request) => request switch + { + ListRetainedDataRequestScopesQuery => OwnDataRequestPurpose.List, + ListRetainedDataRequestsQuery => OwnDataRequestPurpose.Read, + CreateRetainedDataExportCommand => OwnDataRequestPurpose.Create, + CancelRetainedDataRequestCommand => OwnDataRequestPurpose.Cancel, + MintRetainedDataExportTicketCommand => OwnDataRequestPurpose.Ticket, + ReadRetainedDataExportChunkCommand => OwnDataRequestPurpose.Chunk, + _ => 0, + }; + + /// A key only where the operation is keyed, If-Match only (and always) on cancellation, no other precondition. + private static bool HeadersAdmit(HttpRequest request, OwnDataRequestPurpose purpose) => Enum.IsDefined(purpose) + && !request.Headers.ContainsKey("If-None-Match") && !request.Headers.ContainsKey("If-Modified-Since") + && !request.Headers.ContainsKey("If-Unmodified-Since") + && (purpose == OwnDataRequestPurpose.Cancel ? request.Headers.IfMatch.Count == 1 : !request.Headers.ContainsKey("If-Match")) + && (purpose is OwnDataRequestPurpose.Create or OwnDataRequestPurpose.Cancel + || !request.Headers.ContainsKey(IdempotentAttribute.HeaderName)); + + private static string? IfMatch(HttpRequest request) => request.Headers.IfMatch.Count == 1 ? request.Headers.IfMatch[0] : null; + + private static async Task ReadBodyAsync(HttpContext http) + { + if (http.Request.ContentLength > MaximumBody) throw TooLarge(); + http.Request.EnableBuffering(); + http.Request.Body.Position = 0; + var buffer = new byte[MaximumBody + 1]; + try + { + var count = 0; + while (count < buffer.Length) + { + var read = await http.Request.Body.ReadAsync(buffer.AsMemory(count), http.RequestAborted); + if (read == 0) break; + count += read; + } + if (count > MaximumBody) throw TooLarge(); + return buffer[..count]; + } + finally + { + CryptographicOperations.ZeroMemory(buffer); + http.Request.Body.Position = 0; + } + } + + private static BadHttpRequestException TooLarge() => new("Data request entry body exceeds its limit.", StatusCodes.Status413PayloadTooLarge); + + public override string ToString() => nameof(OwnDataRequestHttpInput); +} + +/// The last group of a discovery page; organization is the tenant-wide group. +internal sealed record DataRequestScopeGroupCursor(OrganizationId? OrganizationId); diff --git a/backend/src/LearnStack.Api/Authentication/OwnDataRequestOperation.cs b/backend/src/LearnStack.Api/Authentication/OwnDataRequestOperation.cs new file mode 100644 index 00000000..cff0ce17 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestOperation.cs @@ -0,0 +1,44 @@ +using LearnStack.Api.Identity; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identity; +using Microsoft.AspNetCore.Mvc.Controllers; + +namespace LearnStack.Api.Authentication; + +/// +/// The closed HTTP purposes of the retained own data-request scope (ADR-0106 § 9): exactly six selector-free native +/// entry operations, each one exact path, method, action and request type. Any other path is not this entry. +/// +internal sealed class OwnDataRequestOperation(string path, string method, string action, Type requestType, OwnDataRequestPurpose purpose) +{ + internal const string Root = "/api/v1/identity/data-request-entry"; + internal Type RequestType { get; } = requestType; + internal OwnDataRequestPurpose Purpose { get; } = purpose; + private static readonly OwnDataRequestOperation Scopes = new(Root + "/scopes", "GET", nameof(DataRequestEntryController.Scopes), typeof(ListRetainedDataRequestScopesQuery), OwnDataRequestPurpose.List); + private static readonly OwnDataRequestOperation Requests = new(Root + "/requests", "GET", nameof(DataRequestEntryController.Requests), typeof(ListRetainedDataRequestsQuery), OwnDataRequestPurpose.Read); + private static readonly OwnDataRequestOperation Exports = new(Root + "/exports", "POST", nameof(DataRequestEntryController.CreateExport), typeof(CreateRetainedDataExportCommand), OwnDataRequestPurpose.Create); + private static readonly OwnDataRequestOperation Cancellations = new(Root + "/cancellations", "POST", nameof(DataRequestEntryController.Cancel), typeof(CancelRetainedDataRequestCommand), OwnDataRequestPurpose.Cancel); + private static readonly OwnDataRequestOperation Tickets = new(Root + "/tickets", "POST", nameof(DataRequestEntryController.MintTicket), typeof(MintRetainedDataExportTicketCommand), OwnDataRequestPurpose.Ticket); + private static readonly OwnDataRequestOperation Chunks = new(Root + "/chunks", "POST", nameof(DataRequestEntryController.ReadChunk), typeof(ReadRetainedDataExportChunkCommand), OwnDataRequestPurpose.Chunk); + + internal static OwnDataRequestOperation? ForPath(PathString path) => path.Value switch + { + Root + "/scopes" => Scopes, + Root + "/requests" => Requests, + Root + "/exports" => Exports, + Root + "/cancellations" => Cancellations, + Root + "/tickets" => Tickets, + Root + "/chunks" => Chunks, + _ => null + }; + + internal bool Matches(HttpContext http) => http.Request.Path == path && http.Request.Method == method + && ReferenceEquals(ForPath(http.Request.Path), this) + && http.GetEndpoint()?.Metadata.GetMetadata() is { } descriptor + && descriptor.ControllerTypeInfo.Assembly == typeof(OwnDataRequestOperation).Assembly + && descriptor.ControllerTypeInfo.FullName == "LearnStack.Api.Identity.DataRequestEntryController" + && descriptor.MethodInfo.DeclaringType == descriptor.ControllerTypeInfo.AsType() && descriptor.MethodInfo.Name == action + && http.GetEndpoint()?.Metadata.GetMetadata()?.RequestType == RequestType; + + public override string ToString() => nameof(OwnDataRequestOperation); +} diff --git a/backend/src/LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs b/backend/src/LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs new file mode 100644 index 00000000..f812d227 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs @@ -0,0 +1,185 @@ +using System.Collections.Immutable; +using LearnStack.Api.Tenancy; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Api.Authentication; + +/// +/// Captures one admitted credential, native request, real host and retained own data-request group (ADR-0106 § 9): +/// the sole minter of , modelled exactly on . +/// +/// +/// +/// Where its authority comes from. The actor is the one completed binding normalization produced from a +/// stock-validated credential, so a Closing, Closed or unknown binding never reaches it, and the system actor never +/// does. The host is the independently classified real host. The group is the one the confined definer proved for +/// that actor under that host ceiling: on an organization host only that organization's group, on a tenant host any +/// group of that tenant where the actor holds or held a Membership or has a request. Nothing the caller sends selects +/// a tenant or widens the host. +/// +/// +/// What it never supplies. No Membership, no ordinary native session, no tenant-wide read and no other +/// operation: its witness is current only for an invocation of +/// the exact request type it captured, on the exact endpoint it captured. +/// +/// +public sealed class OwnDataRequestSubjectSource(IHttpContextAccessor accessor, IOwnDataRequestScopeLookup lookup, + IdentityAuthorityQualification qualification, Func invocations) + : OwnDataRequestScopeWitness.MintingSource, IOwnDataRequestScopeSource +{ + private HttpContext? _http; + private Endpoint? _endpoint; + private NativeSessionSourceFeature? _native; + private ValidatedOwnDataRequestCredential? _credential; + private ValidatedTenantIdentity? _identity; + private HostClassification? _host; + private OwnDataRequestHttpInput? _input; + private OwnDataRequestOperation? _purpose; + private GlobalIdentitySubject? _subject; + private OwnDataRequestScopeWitness? _applicationWitness; + private object? _request; + private OwnDataRequestEntryRequest? _requestFeature; + private OwnDataRequestScopePage? _page; + + /// The proved group; only for discovery, which acts in the host's own scope. + internal DataRequestScopeGroup? Selected { get; private set; } + + internal bool MatchesScope(HttpContext http, TenantId tenant, OrganizationId? organization) => IsCurrent(http) + && (Selected?.TenantId ?? _host!.TenantId) == tenant + && (Selected is null ? _host!.OrganizationId : Selected.OrganizationId) == organization; + + internal UserId? Actor => _identity?.ActorUserId; + internal object? Request => _request; + internal Type? EffectiveRequestType => Request?.GetType(); + + /// The keyed purposes' input, read again from the current request, still equals the captured one. + internal async Task MatchesCapturedMutationAsync(HttpContext http) + { + if (!IsCurrent(http) || _purpose is not { Purpose: OwnDataRequestPurpose.Create or OwnDataRequestPurpose.Cancel } purpose + || _input is not { Request: CreateRetainedDataExportCommand or CancelRetainedDataRequestCommand } captured) return false; + var reread = await OwnDataRequestHttpInput.ReadAsync(http, purpose); + return IsCurrent(http) && reread is not null && reread.Request.GetType() == captured.Request.GetType() + && reread.Request.Equals(captured.Request) && reread.OrganizationId == captured.OrganizationId; + } + + /// + /// A keyed replay discloses the stored receipt of the original request only through a fresh receipt read in this + /// same witness's group: the captured mutation becomes the receipt query, never another operation. + /// + internal bool SelectMutationReceipt(HttpContext http, Guid requestId) + { + if (!IsCurrent(http) || _purpose?.Purpose is not (OwnDataRequestPurpose.Create or OwnDataRequestPurpose.Cancel) + || _request is not (CreateRetainedDataExportCommand or CancelRetainedDataRequestCommand) + || requestId == Guid.Empty || requestId.Version != 7) + return false; + var receipt = new ReadRetainedDataRequestReceiptQuery(requestId); + _request = receipt; + _requestFeature = new OwnDataRequestEntryRequest(receipt); + http.Features.Set(_requestFeature); + return true; + } + + /// + /// Whether this source is the current retained entry for in exactly this group, on a + /// download purpose: the one condition under which a ticket is bound to, or read through, this request's credential. + /// + internal ValidatedOwnDataRequestCredential? DownloadCredential(HttpContext http, UserId actor, TenantId tenant, OrganizationId? organization) => + IsCurrent(http) && _purpose?.Purpose is OwnDataRequestPurpose.Ticket or OwnDataRequestPurpose.Chunk + && Selected is { } group && group.TenantId == tenant && group.OrganizationId == organization + && _identity!.ActorUserId == actor ? _credential : null; + + internal bool IsCurrent(HttpContext http) => IsOpen && ReferenceEquals(_http, http) && ReferenceEquals(accessor.HttpContext, http) + && !http.RequestAborted.IsCancellationRequested && ReferenceEquals(http.GetEndpoint(), _endpoint) + && ReferenceEquals(http.Features.Get(), this) + && ReferenceEquals(http.Features.Get(), _requestFeature) && _requestFeature is not null + && ReferenceEquals(_requestFeature.Request, _request) + && ReferenceEquals(http.Features.Get(), _host) + && _purpose?.Matches(http) is true && ReferenceEquals(_native, http.Features.Get()) + && _native?.IsCurrent(http) is true && _native.DataRequestOperation == _purpose + && ReferenceEquals(_credential, http.Features.Get()) && _credential?.IsCurrent(http) is true + && ReferenceEquals(_identity, http.Features.Get()?.Identity) && _identity is not null + && _input?.IsCurrent(http) is true; + + internal async Task> PrepareAsync(HttpContext http) + { + if (_http is not null || OwnDataRequestOperation.ForPath(http.Request.Path) is not { } purpose || !purpose.Matches(http) + || http.Features.Get() is not { } native || native.DataRequestOperation != purpose || !native.IsCurrent(http) + || http.Features.Get() is not { } credential || !credential.IsCurrent(http) + || http.Features.Get()?.Identity is not { } identity + || identity.ActorUserId == UserId.SystemActor || !StronglyTypedId.IsAssigned(identity.ActorUserId) + || http.Features.Get() is not { TenantId: { } tenant } host + || qualification.Current is not { } authority || identity.Issuer != authority.Issuer) + return Fail("lockey_not_found"); + if (identity.TenantId is { } claimed && (claimed != tenant + || host.OrganizationId is { } branch && identity.OrganizationId != branch)) return Fail("lockey_not_found"); + var input = await OwnDataRequestHttpInput.ReadAsync(http, purpose); + if (input is null) return Fail("lockey_validation_failed"); + DataRequestScopeGroup? selected = null; + OwnDataRequestScopePage? page = null; + if (purpose.Purpose == OwnDataRequestPurpose.List) + { + var after = input.After is { } cursor ? new DataRequestScopeGroup(tenant, cursor.OrganizationId) : null; + if (after is not null && host.OrganizationId is { } ceiling && after.OrganizationId != ceiling) return Fail("lockey_validation_failed"); + var observed = await lookup.LookupAsync(identity.ActorUserId, tenant, host.OrganizationId, OwnDataRequestLookupMode.List, + null, after, input.Limit, http.RequestAborted); + if (!WithinHost(observed, tenant, host.OrganizationId, input.Limit)) return Fail("lockey_not_found"); + var next = observed.Count == input.Limit && (await lookup.LookupAsync(identity.ActorUserId, tenant, host.OrganizationId, + OwnDataRequestLookupMode.List, null, observed[^1], 1, http.RequestAborted)).Count != 0 + ? OwnDataRequestHttpInput.KeyFor(observed[^1]) : null; + page = new OwnDataRequestScopePage(observed.ToImmutableArray(), next); + } + else + { + if (host.OrganizationId is { } hostBranch && input.OrganizationId != hostBranch) return Fail("lockey_not_found"); + var requested = new DataRequestScopeGroup(tenant, input.OrganizationId); + var observed = await lookup.LookupAsync(identity.ActorUserId, tenant, host.OrganizationId, OwnDataRequestLookupMode.Select, + requested, null, 1, http.RequestAborted); + if (!WithinHost(observed, tenant, host.OrganizationId, 1) || observed.Count != 1 || observed[0] != requested) + return Fail("lockey_not_found"); + selected = observed[0]; + if (identity.TenantId is not null && (identity.TenantId != selected.TenantId || identity.OrganizationId != selected.OrganizationId)) + return Fail("lockey_not_found"); + } + if (!native.IsCurrent(http) || !credential.IsCurrent(http) + || !ReferenceEquals(identity, http.Features.Get()?.Identity) + || !ReferenceEquals(host, http.Features.Get()) || !input.IsCurrent(http)) return Fail("lockey_not_found"); + _http = http; _endpoint = http.GetEndpoint(); _purpose = purpose; _native = native; _credential = credential; + _identity = identity; _host = host; _input = input; _request = input.Request; + _subject = new GlobalIdentitySubject(authority.AuthorityId, authority.Issuer, identity.Subject); + Selected = selected; _page = page; _requestFeature = new OwnDataRequestEntryRequest(input.Request); + http.Features.Set(_requestFeature); http.Features.Set(this); + return Result.Ok(None.Value); + } + + public OwnDataRequestScopeWitness? ForInvocation(OperationInvocation invocation) + { + if (_http is null || !IsEvidenceCurrent(this, invocation)) return null; + if (invocation.EntryKind == OperationEntryKind.Application && _applicationWitness is not null) + return ReferenceEquals(_applicationWitness.Invocation, invocation) ? _applicationWitness : null; + var witness = Capture(this, invocation, _subject!, _identity!.ActorUserId, _host!.TenantId!.Value, + _host.OrganizationId, _host.Host, _purpose!.Purpose, Selected, _page); + if (invocation.EntryKind == OperationEntryKind.Application) _applicationWitness = witness; + return witness; + } + + protected override bool IsEvidenceCurrent(object evidence, OperationInvocation invocation) => ReferenceEquals(evidence, this) + && _http is not null && IsCurrent(_http) && ReferenceEquals(invocations().CurrentInvocation, invocation) + && invocation.Policy.RequestType == EffectiveRequestType && invocation.Policy.Kind == OperationPolicyKind.OwnDataRequestEntry + && (invocation.EntryKind == OperationEntryKind.Http ? ReferenceEquals(invocation.Operation, _endpoint) + : ReferenceEquals(invocation.Operation, Request) && (_applicationWitness is null || ReferenceEquals(_applicationWitness.Invocation, invocation))); + + /// Re-checks every observed group against the same host ceiling and bound, so a drifted lookup never widens. + private static bool WithinHost(IReadOnlyList observed, TenantId tenant, OrganizationId? hostOrganization, int limit) => + observed.Count <= limit && observed.Distinct().Count() == observed.Count + && observed.All(group => group is not null && group.TenantId == tenant + && (hostOrganization is not { } branch || group.OrganizationId == branch)); + + private static Result Fail(string key) => Result.Fail(new Error(LocalizedMessage.Of(key))); +} diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs index 5fd5d78d..13b438bd 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs @@ -91,8 +91,10 @@ public override Task MessageReceived(MessageReceivedContext context) { context.HttpContext.Features.Set(null); context.HttpContext.Features.Set(null); + context.HttpContext.Features.Set(null); ValidatedInvitationCredential.ClearPending(context.HttpContext); ValidatedConsentSubjectCredential.ClearPending(context.HttpContext); + ValidatedOwnDataRequestCredential.ClearPending(context.HttpContext); if (!HostClassificationMiddleware.ClassifiesPath(context.Request.Path) || context.HttpContext.Features.Get() is null) { @@ -118,6 +120,7 @@ public override Task MessageReceived(MessageReceivedContext context) context.Token = token; ValidatedInvitationCredential.BeginValidation(context.HttpContext, token); ValidatedConsentSubjectCredential.BeginValidation(context.HttpContext, token); + ValidatedOwnDataRequestCredential.BeginValidation(context.HttpContext, token); } return Task.CompletedTask; @@ -127,6 +130,7 @@ public override Task TokenValidated(TokenValidatedContext context) { context.HttpContext.Features.Set(null); context.HttpContext.Features.Set(null); + context.HttpContext.Features.Set(null); var feature = context.HttpContext.Features.Get(); if (feature is null || context.SecurityToken is not JsonWebToken token || !TenantTokenProfile.TryReadValidated( @@ -134,6 +138,7 @@ public override Task TokenValidated(TokenValidatedContext context) { ValidatedInvitationCredential.ClearPending(context.HttpContext); ValidatedConsentSubjectCredential.ClearPending(context.HttpContext); + ValidatedOwnDataRequestCredential.ClearPending(context.HttpContext); TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ProfileRejected); context.Fail("Tenant credential refused."); } @@ -142,6 +147,7 @@ public override Task TokenValidated(TokenValidatedContext context) feature.VerifiedSubject = identity; context.HttpContext.Features.Set(ValidatedInvitationCredential.Capture(context.HttpContext, token, identity!)); context.HttpContext.Features.Set(ValidatedConsentSubjectCredential.Capture(context.HttpContext, token, identity!)); + context.HttpContext.Features.Set(ValidatedOwnDataRequestCredential.Capture(context.HttpContext, token, identity!)); TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ValidationAccepted); } @@ -152,8 +158,10 @@ public override Task AuthenticationFailed(AuthenticationFailedContext context) { context.HttpContext.Features.Set(null); context.HttpContext.Features.Set(null); + context.HttpContext.Features.Set(null); ValidatedInvitationCredential.ClearPending(context.HttpContext); ValidatedConsentSubjectCredential.ClearPending(context.HttpContext); + ValidatedOwnDataRequestCredential.ClearPending(context.HttpContext); if (context.HttpContext.Features.Get() is { } feature) { feature.Identity = null; diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthorizationCandidateSource.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthorizationCandidateSource.cs index 08d8798c..36d6dbd5 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantAuthorizationCandidateSource.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantAuthorizationCandidateSource.cs @@ -17,15 +17,17 @@ internal sealed class TenantAuthorizationCandidateSource(IHttpContextAccessor ac var native = http?.Features.Get(); var invitation = http?.Features.Get(); var consent = http?.Features.Get(); + var dataRequest = http?.Features.Get(); if (http is null || http.RequestAborted.IsCancellationRequested || http.Features.Get() is not { } host || http.Features.Get() is not { VerifiedSubject: { } subject, Identity: { } identity } || http.Features.Get() is not { IsAcquired: true } decision || http.Features.Get() is not { } provenance || !provenance.Matches(subject) || !MatchesIdentity(identity, subject) + || (consent is not null && dataRequest is not null) || (http.Features.Get() is not null - && (consent is not null ? !consent.IsCurrent(http) : invitation is null ? native is null || !native.IsCurrent(http) : !invitation.IsCurrent(http))) - || (consent is not null ? !consent.MatchesScope(http, tenant, organization) : invitation is not null ? invitation.Offer!.TenantId != tenant || invitation.Offer.OrganizationId != organization + && (dataRequest is not null ? !dataRequest.IsCurrent(http) : consent is not null ? !consent.IsCurrent(http) : invitation is null ? native is null || !native.IsCurrent(http) : !invitation.IsCurrent(http))) + || (dataRequest is not null ? !dataRequest.MatchesScope(http, tenant, organization) : consent is not null ? !consent.MatchesScope(http, tenant, organization) : invitation is not null ? invitation.Offer!.TenantId != tenant || invitation.Offer.OrganizationId != organization : native is null ? identity.TenantId != tenant || organization != (identity.OrganizationId ?? host.OrganizationId) : native.Tenant != tenant || native.Organization != organization) @@ -34,7 +36,7 @@ internal sealed class TenantAuthorizationCandidateSource(IHttpContextAccessor ac return null; return ForCandidate(AuthorizationSourceKind.Http, identity.ActorUserId, tenant, organization, - new CredentialWitness(http, host, subject, identity, decision, provenance, native, invitation, consent)); + new CredentialWitness(http, host, subject, identity, decision, provenance, native, invitation, consent, dataRequest)); } protected override bool IsEvidenceCurrent(object? evidence) => evidence is CredentialWitness witness @@ -47,7 +49,9 @@ protected override bool IsEvidenceCurrent(object? evidence) => evidence is Crede && ReferenceEquals(witness.Http.Features.Get(), witness.Decision) && ReferenceEquals(witness.Http.Features.Get(), witness.Provenance) && witness.Provenance.Matches(witness.Subject) - && (witness.Consent is not null ? ReferenceEquals(witness.Http.Features.Get(), witness.Consent) + && ReferenceEquals(witness.Http.Features.Get(), witness.DataRequest) + && (witness.DataRequest is not null ? witness.DataRequest.IsCurrent(witness.Http) + : witness.Consent is not null ? ReferenceEquals(witness.Http.Features.Get(), witness.Consent) && witness.Consent.IsCurrent(witness.Http) : witness.Invitation is not null ? ReferenceEquals(witness.Http.Features.Get(), witness.Invitation) && witness.Invitation.IsCurrent(witness.Http) : witness.Native is null ? witness.Http.Features.Get() is null @@ -63,7 +67,8 @@ private static bool MatchesIdentity(ValidatedTenantIdentity identity, VerifiedPr private sealed class CredentialWitness(HttpContext http, HostClassification host, VerifiedProviderSubject subject, ValidatedTenantIdentity identity, SubjectAdmissionDecision decision, - TenantSubjectAdmissionProvenance provenance, NativeScopeEvidence? native, InvitationEntrySource? invitation, ConsentSubjectSource? consent) + TenantSubjectAdmissionProvenance provenance, NativeScopeEvidence? native, InvitationEntrySource? invitation, ConsentSubjectSource? consent, + OwnDataRequestSubjectSource? dataRequest) { internal HttpContext Http { get; } = http; internal HostClassification Host { get; } = host; @@ -74,6 +79,7 @@ private sealed class CredentialWitness(HttpContext http, HostClassification host internal NativeScopeEvidence? Native { get; } = native; internal InvitationEntrySource? Invitation { get; } = invitation; internal ConsentSubjectSource? Consent { get; } = consent; + internal OwnDataRequestSubjectSource? DataRequest { get; } = dataRequest; public override string ToString() => nameof(CredentialWitness); } diff --git a/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs b/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs index 1cd4318f..3d4cd513 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs @@ -91,7 +91,7 @@ public async Task InvokeAsync(HttpContext context, ITenantIdentityBindingResolve feature.Identity = new ValidatedTenantIdentity(subject.Issuer, subject.Subject, actor, subject.TenantId, subject.OrganizationId); - if (context.Features.Get() is { InvitationOperation: null, ConsentOperation: null }) + if (context.Features.Get() is { InvitationOperation: null, ConsentOperation: null, DataRequestOperation: null }) { var native = NativeScopeEvidence.TryMint(context, feature.Identity); if (native is null) diff --git a/backend/src/LearnStack.Api/Authentication/ValidatedOwnDataRequestCredential.cs b/backend/src/LearnStack.Api/Authentication/ValidatedOwnDataRequestCredential.cs new file mode 100644 index 00000000..26d74722 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/ValidatedOwnDataRequestCredential.cs @@ -0,0 +1,83 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.IdentityModel.JsonWebTokens; + +namespace LearnStack.Api.Authentication; + +/// +/// Retains only the stock-validated credential of an exact retained data-request entry request for its request lifetime +/// (ADR-0106 § 9), as does for the consent entry. Its digest of the exact +/// presented header is also what a download ticket on this path is bound to (ADR-0107 § 4). +/// +internal sealed class ValidatedOwnDataRequestCredential +{ + private readonly HttpContext _http; + private readonly TenantCredentialFeature _feature; + private readonly byte[] _headerDigest; + private readonly PathString _path; + private readonly string _method; + private readonly Endpoint? _endpoint; + private readonly CancellationToken _requestCancellation; + + private ValidatedOwnDataRequestCredential(HttpContext http, TenantCredentialFeature feature, + VerifiedProviderSubject subject, string header) + { + _http = http; + _feature = feature; + _headerDigest = SHA256.HashData(Encoding.UTF8.GetBytes(header)); + _path = http.Request.Path; + _method = http.Request.Method; + _endpoint = http.GetEndpoint(); + _requestCancellation = http.RequestAborted; + Subject = subject; + } + + internal VerifiedProviderSubject Subject { get; } + + /// The lower-case hex SHA-256 of the exact presented Authorization header; never the header itself. + internal string CredentialDigest => Convert.ToHexStringLower(_headerDigest); + + internal static void BeginValidation(HttpContext http, string token) + { + if (OwnDataRequestOperation.ForPath(http.Request.Path) is { } purpose && purpose.Matches(http) + && http.Request.Headers.Authorization.Count == 1 && http.Request.Headers.Authorization[0] is { } header) + http.Features.Set(new PendingValidation(SHA256.HashData(Encoding.UTF8.GetBytes(header)), + SHA256.HashData(Encoding.UTF8.GetBytes(token)))); + } + + internal static void ClearPending(HttpContext http) => http.Features.Set(null); + + internal static ValidatedOwnDataRequestCredential? Capture(HttpContext http, JsonWebToken token, + VerifiedProviderSubject subject) + { + var pending = http.Features.Get(); + ClearPending(http); + if (pending is null || OwnDataRequestOperation.ForPath(http.Request.Path) is not { } purpose || !purpose.Matches(http) + || http.Features.Get() is not { } feature + || !ReferenceEquals(feature.VerifiedSubject, subject) + || http.Request.Headers.Authorization.Count != 1 + || http.Request.Headers.Authorization[0] is not { } header + || !CryptographicOperations.FixedTimeEquals(pending.HeaderDigest, SHA256.HashData(Encoding.UTF8.GetBytes(header))) + || !CryptographicOperations.FixedTimeEquals(pending.TokenDigest, SHA256.HashData(Encoding.UTF8.GetBytes(token.EncodedToken)))) + return null; + return new(http, feature, subject, header); + } + + internal bool IsCurrent(HttpContext http) => ReferenceEquals(_http, http) + && !_requestCancellation.IsCancellationRequested && http.RequestAborted == _requestCancellation + && http.Request.Path == _path && string.Equals(http.Request.Method, _method, StringComparison.Ordinal) + && ReferenceEquals(http.GetEndpoint(), _endpoint) + && ReferenceEquals(http.Features.Get(), this) + && ReferenceEquals(http.Features.Get(), _feature) + && ReferenceEquals(_feature.VerifiedSubject, Subject) + && http.Request.Headers.Authorization.Count == 1 + && http.Request.Headers.Authorization[0] is { } header + && CryptographicOperations.FixedTimeEquals(_headerDigest, SHA256.HashData(Encoding.UTF8.GetBytes(header))); + + private sealed record PendingValidation(byte[] HeaderDigest, byte[] TokenDigest) + { + public override string ToString() => nameof(PendingValidation); + } + + public override string ToString() => nameof(ValidatedOwnDataRequestCredential); +} diff --git a/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs index 0113db07..c22471c6 100644 --- a/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs +++ b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs @@ -23,6 +23,9 @@ internal static bool IsPath(PathString path) ("identity", "invitations" or "invitable-roles", 5) => true, ("identity", "invitations", 6) => true, ("identity", "invitation-entry", 6) => parts[5].ToLowerInvariant() is "inspections" or "acceptances" or "results", + // ADR-0106 § 9: the retained own-scope native entry of the subject's data requests. + ("identity", "data-request-entry", 6) => parts[5].ToLowerInvariant() is "scopes" or "requests" or "exports" + or "cancellations" or "tickets" or "chunks", ("identity", "invitations", 7) => parts[6].ToLowerInvariant() is "revocations" or "reissues", ("tenancy", "settings", 6) => parts[5].Equals("invitation-policy", StringComparison.OrdinalIgnoreCase), ("identity", "organization-memberships" or "permissions" or "roles", 5) => true, diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs index 50d0e8fc..20a7e046 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs @@ -45,6 +45,8 @@ public enum ProtectedAdministrationOperation CancelDataRequest = 27, RevokeOwnDataExport = 28, RevokeDataExport = 29, + CreateRetainedDataExport = 30, + CancelRetainedDataRequest = 31, } internal sealed record ProtectedAdministrationDescriptor( @@ -62,7 +64,17 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra /// Location and its ETag. Every other keyed creation answers 201 and every other mutation 200. /// internal bool IsDataRequestCreation => Operation is ProtectedAdministrationOperation.CreateOwnDataExport - or ProtectedAdministrationOperation.CreateDataExportForSubject; + or ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateRetainedDataExport; + + /// + /// ADR-0106 § 9: the retained own-scope entry has no per-request route a Location could name; its receipt is read + /// through the group's request list, so its creation answers 202 with the resource and ETag and no Location. + /// + internal bool HasLocation => Creates && Operation != ProtectedAdministrationOperation.CreateRetainedDataExport; + + /// The retained own-scope entry's keyed operations, whose replay reads only through their own witness. + internal bool IsRetainedDataRequest => Operation is ProtectedAdministrationOperation.CreateRetainedDataExport + or ProtectedAdministrationOperation.CancelRetainedDataRequest; internal int SuccessStatus => IsDataRequestCreation ? StatusCodes.Status202Accepted : Creates ? StatusCodes.Status201Created : StatusCodes.Status200OK; @@ -107,6 +119,8 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra ProtectedAdministrationOperation.CancelDataRequest => new(operation, typeof(CancelDataRequestCommand), IdempotencyReplayTargetKind.DataSubjectRequest), ProtectedAdministrationOperation.RevokeOwnDataExport => new(operation, typeof(RevokeOwnDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest), ProtectedAdministrationOperation.RevokeDataExport => new(operation, typeof(RevokeDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.CreateRetainedDataExport => new(operation, typeof(CreateRetainedDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CancelRetainedDataRequest => new(operation, typeof(CancelRetainedDataRequestCommand), IdempotencyReplayTargetKind.DataSubjectRequest), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; @@ -141,6 +155,8 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra CancelDataRequestCommand => ProtectedAdministrationOperation.CancelDataRequest, RevokeOwnDataExportCommand => ProtectedAdministrationOperation.RevokeOwnDataExport, RevokeDataExportCommand => ProtectedAdministrationOperation.RevokeDataExport, + CreateRetainedDataExportCommand => ProtectedAdministrationOperation.CreateRetainedDataExport, + CancelRetainedDataRequestCommand => ProtectedAdministrationOperation.CancelRetainedDataRequest, _ => null, }; @@ -171,6 +187,8 @@ or ProtectedAdministrationOperation.SetMemberCustomFields or ProtectedAdministra CancelDataRequestCommand command => command.ExpectedVersion, RevokeOwnDataExportCommand command => command.ExpectedArtifactVersion, RevokeDataExportCommand command => command.ExpectedArtifactVersion, + CreateRetainedDataExportCommand => null, + CancelRetainedDataRequestCommand command => command.ExpectedVersion, _ => throw new ArgumentException("The protected operation is not registered.", nameof(request)), }; internal bool TryReadPrecondition(HttpRequest request, out long? expected) @@ -191,6 +209,7 @@ internal bool TryReadPrecondition(HttpRequest request, out long? expected) ProtectedAdministrationOperation.RegisterCustomFieldDefinition => "/api/v1/customization/custom-field-definitions/" + id.ToString("D"), ProtectedAdministrationOperation.CreateOwnDataExport => "/api/v1/identity/me/data-requests/" + id.ToString("D"), ProtectedAdministrationOperation.CreateDataExportForSubject => "/api/v1/identity/data-requests/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateRetainedDataExport => throw new InvalidOperationException("The retained entry has no request location."), _ => OrganizationLocationFor(id), }; internal static string OrganizationLocationFor(Guid id) => "/api/v1/tenancy/organizations/" + id.ToString("D"); diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs index 51b1d84f..12a5adc6 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationResult.cs @@ -90,6 +90,8 @@ internal static async Task ExecuteAsync(HttpContext http, ISender CancelDataRequestCommand command => DataRequest(await sender.Send(command, cancellationToken), command.RequestId), RevokeOwnDataExportCommand command => Artifact(await sender.Send(command, cancellationToken), command.RequestId), RevokeDataExportCommand command => Artifact(await sender.Send(command, cancellationToken), command.RequestId), + CreateRetainedDataExportCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CancelRetainedDataRequestCommand command => DataRequest(await sender.Send(command, cancellationToken), command.RequestId), _ => throw new InvalidOperationException("The protected operation is not registered."), }; @@ -151,7 +153,7 @@ public async Task ExecuteResultAsync(ActionContext context) response.StatusCode = Descriptor.SuccessStatus; response.ContentType = "application/json; charset=utf-8"; if (!Descriptor.IsConsent) response.Headers.ETag = EntityTag.For(Version); - if (Descriptor.Creates) response.Headers.Location = Descriptor.LocationFor(Target.Id); + if (Descriptor.HasLocation) response.Headers.Location = Descriptor.LocationFor(Target.Id); // This is the filter's memory capture, not network delivery. A disconnect // after business commit must not prevent recording the completed receipt. await response.Body.WriteAsync(BodyFor(Descriptor, Target.Id, Version), CancellationToken.None); diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs index 9df5cd54..95b4f81e 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedIdempotencyFilter.cs @@ -83,7 +83,7 @@ public async Task OnResourceExecutionAsync(ResourceExecutingContext context, Res case IdempotencyClaim.Completed: // A retained-consent mutation witness cannot become a receipt-read // witness after HTTP authorization. Retry through fresh admission. - if (_descriptor.Operation == ProtectedAdministrationOperation.WithdrawOwnFieldConsent) + if (_descriptor.Operation == ProtectedAdministrationOperation.WithdrawOwnFieldConsent || _descriptor.IsRetainedDataRequest) { context.Result = Problem("lockey_request_in_progress"); return; } await ReplayAsync(context, claim.Stored, cancellationToken); return; @@ -274,7 +274,7 @@ internal static bool ValidStoredResponse(IdempotentResponse stored, ProtectedAdm || stored.StatusCode != descriptor.SuccessStatus || stored.ContentType != "application/json; charset=utf-8" || stored.Body.Length > MaxReceiptBytes || !stored.Body.AsSpan().SequenceEqual(ProtectedAdministrationResult.BodyFor(descriptor, target.Id, version))) return false; - if (descriptor.Creates ? !TryHeader(stored, "Location", out var location) + if (descriptor.HasLocation ? !TryHeader(stored, "Location", out var location) || location != descriptor.LocationFor(target.Id) : stored.Headers.Keys.Any(name => name.Equals("Location", StringComparison.OrdinalIgnoreCase))) return false; var response = new DefaultHttpContext().Response; diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs index 505015b9..6e633718 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedReceiptReplayDispatcher.cs @@ -51,6 +51,11 @@ ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationO or ProtectedAdministrationOperation.RevokeOwnDataExport => sender.Send(new ReadOwnDataRequestReceiptQuery(target.Id), cancellationToken), ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CancelDataRequest or ProtectedAdministrationOperation.RevokeDataExport => sender.Send(new ReadDataRequestReceiptQuery(target.Id), cancellationToken), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CancelRetainedDataRequest + when http?.Features.Get()?.Request is ReadRetainedDataRequestReceiptQuery retained + && retained.RequestId == target.Id => sender.Send(retained, cancellationToken), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CancelRetainedDataRequest => + Task.FromResult(Result.Fail(new Error(LocalizedMessage.Of("lockey_forbidden")))), _ => throw new ArgumentOutOfRangeException(nameof(descriptor)), }; } diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs index 90e35ec8..b4dd839e 100644 --- a/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs +++ b/backend/src/LearnStack.Api/Idempotency/ProtectedReplayHttpAdmission.cs @@ -45,8 +45,19 @@ internal static async Task> AuthorizeAsync(HttpContext http, Operat || context.UserId is not { } actor || !StronglyTypedId.IsAssigned(actor) || actor == UserId.SystemActor) return await operations().CheckHttpAsync(declared.RequestType, endpoint!, http.RequestAborted); ConsentSubjectSource? consent = null; + OwnDataRequestSubjectSource? dataRequest = null; AuthorizationCandidate? candidate = null; - if (descriptor.Operation == ProtectedAdministrationOperation.WithdrawOwnFieldConsent) + if (descriptor.IsRetainedDataRequest) + { + // ADR-0106 § 9: the retained entry is admitted by its own witness, never by an ordinary candidate. + dataRequest = http.Features.Get(); + if (declared.Kind != OperationPolicyKind.OwnDataRequestEntry || context.Origin != TenantContextOrigin.HostAndOwnDataRequestScope + || dataRequest is null || dataRequest.Actor != actor || !dataRequest.MatchesScope(http, context.TenantId, context.OrganizationId) + || dataRequest.Request is not (CreateRetainedDataExportCommand or CancelRetainedDataRequestCommand) + || http.Features.Get() is not null) + return Failure("lockey_forbidden"); + } + else if (descriptor.Operation == ProtectedAdministrationOperation.WithdrawOwnFieldConsent) { consent = http.Features.Get(); if (declared.Kind != OperationPolicyKind.OwnConsentEntry || context.Origin != TenantContextOrigin.HostAndConsentSubjectScope @@ -65,12 +76,13 @@ internal static async Task> AuthorizeAsync(HttpContext http, Operat // actual bytes here before fingerprinting, without consuming model input. if (!AdministrationHttpInput.SupportsJsonMedia(http.Request)) return Failure("lockey_validation_failed"); if (consent is not null && !await consent.MatchesCapturedWithdrawalAsync(http)) return Failure("lockey_forbidden"); + if (dataRequest is not null && !await dataRequest.MatchesCapturedMutationAsync(http)) return Failure("lockey_forbidden"); await AdministrationHttpInput.ReadBodyBytesAsync(http); string fingerprint; try { fingerprint = await ProtectedIdempotencyFilter.ComputeFingerprintAsync(http, context, descriptor, expected, http.RequestAborted); } catch (Exception failure) when (failure is CustomFieldFingerprintUnavailableException or IdempotencyStoreException) { return Failure("lockey_dependency_unavailable"); } - var binding = new RequestBinding(http, endpoint!, classifier, declared, descriptor, context, candidate, consent, key, fingerprint, expected); + var binding = new RequestBinding(http, endpoint!, classifier, declared, descriptor, context, candidate, consent, dataRequest, key, fingerprint, expected); IdempotentResponse? stored; try { stored = await store.ReadCompletedAsync(context.TenantId, key, fingerprint, http.RequestAborted); } catch (IdempotencyStoreException) { return Failure("lockey_dependency_unavailable"); } @@ -84,6 +96,9 @@ internal static async Task> AuthorizeAsync(HttpContext http, Operat if (consent is not null && frozen is not null && (frozen.ReplayTarget is not { } target || !consent.SelectWithdrawalReceipt(http, target.Id))) return Failure("lockey_forbidden"); + if (dataRequest is not null && frozen is not null + && (frozen.ReplayTarget is not { } retained || !dataRequest.SelectMutationReceipt(http, retained.Id))) + return Failure("lockey_forbidden"); var result = await operations().CheckHttpAsync(requestType, endpoint!, http.RequestAborted); if (result.IsFailure) return result; if (!binding.Matches(http, context, descriptor, key, fingerprint, expected)) return Failure("lockey_forbidden"); @@ -96,19 +111,23 @@ internal static async Task> AuthorizeAsync(HttpContext http, Operat async Task> ConsentInputMatchesAsync() { - if (consent is null) return Result.Ok(None.Value); - if (!await consent.MatchesCapturedWithdrawalAsync(http) || !IdempotencyFilter.TryReadKey(http, out var currentKey) + if (consent is null && dataRequest is null) return Result.Ok(None.Value); + if (!await CapturedInputMatchesAsync() || !IdempotencyFilter.TryReadKey(http, out var currentKey) || currentKey != key) return Failure("lockey_forbidden"); try { var currentFingerprint = await ProtectedIdempotencyFilter.ComputeFingerprintAsync(http, context, descriptor, expected, http.RequestAborted); - return fingerprint == currentFingerprint && await consent.MatchesCapturedWithdrawalAsync(http) + return fingerprint == currentFingerprint && await CapturedInputMatchesAsync() && IdempotencyFilter.TryReadKey(http, out currentKey) && currentKey == key ? Result.Ok(None.Value) : Failure("lockey_forbidden"); } catch (Exception failure) when (failure is CustomFieldFingerprintUnavailableException or IdempotencyStoreException) { return Failure("lockey_dependency_unavailable"); } } + + // The captured input outlives a replay's receipt selection, so the reread compares the original mutation either way. + Task CapturedInputMatchesAsync() => consent is not null + ? consent.MatchesCapturedWithdrawalAsync(http) : dataRequest!.MatchesCapturedMutationAsync(http); } internal static ProtectedHttpAdmission Consume(HttpContext http, ITenantContext context, @@ -144,6 +163,8 @@ ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationO or ProtectedAdministrationOperation.RevokeOwnDataExport => typeof(ReadOwnDataRequestReceiptQuery), ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CancelDataRequest or ProtectedAdministrationOperation.RevokeDataExport => typeof(ReadDataRequestReceiptQuery), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CancelRetainedDataRequest => + typeof(ReadRetainedDataRequestReceiptQuery), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; @@ -164,7 +185,8 @@ private sealed class Admission(RequestBinding binding, IdempotentResponse? respo private sealed class RequestBinding(HttpContext http, Endpoint endpoint, OperationHttpClassifier classifier, OperationPolicy policy, ProtectedAdministrationDescriptor descriptor, ITenantContext context, - AuthorizationCandidate? candidate, ConsentSubjectSource? consent, string key, string fingerprint, long? expected) + AuthorizationCandidate? candidate, ConsentSubjectSource? consent, OwnDataRequestSubjectSource? dataRequest, string key, + string fingerprint, long? expected) { private readonly TenantId _tenant = context.TenantId; private readonly OrganizationId? _organization = context.OrganizationId; @@ -177,7 +199,9 @@ internal bool Matches(HttpContext current, ITenantContext scope, ProtectedAdmini && ReferenceEquals(context, scope) && !current.RequestAborted.IsCancellationRequested && scope.IsResolved && scope.TenantId == _tenant && scope.OrganizationId == _organization && scope.UserId == _actor && scope.Origin == _origin - && (consent is not null ? candidate is null && consent.Actor == _actor && consent.MatchesScope(current, _tenant, _organization) + && (dataRequest is not null ? candidate is null && consent is null && dataRequest.Actor == _actor + && dataRequest.MatchesScope(current, _tenant, _organization) + : consent is not null ? candidate is null && consent.Actor == _actor && consent.MatchesScope(current, _tenant, _organization) : candidate is { IsActive: true } && candidate.Actor == _actor && candidate.TenantId == _tenant && candidate.OrganizationId == _organization) && descriptor == operation && key == currentKey && fingerprint == currentFingerprint && expected == currentExpected diff --git a/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs index cd1434f1..7b5066a1 100644 --- a/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs @@ -50,9 +50,163 @@ public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerC || path.Operations?.TryGetValue(contract.Method, out var operation) != true || operation is null) continue; Describe(document, path, operation, contract); } + foreach (var contract in RetainedContracts) + { + if (!document.Paths.TryGetValue("/api/v1/" + contract.Path, out var path) + || path.Operations?.TryGetValue(contract.Method, out var operation) != true || operation is null) continue; + DescribeRetained(document, path, operation, contract); + } return Task.CompletedTask; } + /// + /// ADR-0106 § 9: the retained own-scope native entry. Selector-free (no tenant or organization header), reached only + /// with the native session source credential, every purpose but discovery naming its one group in group. + /// + private static readonly Contract[] RetainedContracts = + [ + new("identity/data-request-entry/scopes", HttpMethod.Get, "ListRetainedDataRequestScopes", Shape.Page, "RetainedDataRequestScopePageResponse", null, true), + new("identity/data-request-entry/requests", HttpMethod.Get, "ListRetainedDataRequests", Shape.Page, "OwnDataRequestPage", null, true), + new("identity/data-request-entry/exports", HttpMethod.Post, "CreateRetainedDataExport", Shape.Create, "DataRequestAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/data-request-entry/cancellations", HttpMethod.Post, "CancelRetainedDataRequest", Shape.Mutation, "AdministrationVersionReceipt", "RetainedDataRequestTargetInput", true), + new("identity/data-request-entry/tickets", HttpMethod.Post, "MintRetainedDataExportTicket", Shape.Ticket, "DataExportTicketResponse", "RetainedDataRequestTargetInput", true), + new("identity/data-request-entry/chunks", HttpMethod.Post, "ReadRetainedDataExportChunk", Shape.Chunk, "DataExportChunkResponse", "RetainedDataExportChunkInput", true), + ]; + + private static void DescribeRetained(OpenApiDocument document, IOpenApiPathItem path, OpenApiOperation operation, Contract contract) + { + operation.OperationId = contract.Name; + operation.Security = [new OpenApiSecurityRequirement + { + [new OpenApiSecuritySchemeReference(TenantAuthenticationRegistration.Scheme, document)] = [], + [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, document)] = [], + }]; + operation.Description = RetainedDescription(contract); + operation.Parameters = []; + var discovery = contract.Name == "ListRetainedDataRequestScopes"; + if (!discovery) operation.Parameters.Add(new OpenApiParameter + { + Name = "group", + In = ParameterLocation.Query, + Required = true, + Schema = new OpenApiSchema + { + Type = JsonSchemaType.String, + MinLength = 6, + MaxLength = 36, + Pattern = "^(tenant|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$", + }, + Description = "The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found.", + }); + if (contract.Shape == Shape.Page) + { + operation.Parameters.Add(new OpenApiParameter + { + Name = "cursor", + In = ParameterLocation.Query, + Schema = new OpenApiSchema { Type = JsonSchemaType.String, MinLength = 1, MaxLength = discovery ? 36 : 1024 }, + Description = discovery + ? "The previous page's nextCursor: the last group's key (tenant or an organization UUIDv7)." + : "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + }); + operation.Parameters.Add(new OpenApiParameter + { + Name = "limit", + In = ParameterLocation.Query, + Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = "20", Default = JsonValue.Create(20) }, + Description = "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + }); + } + if (contract.Body is not null) + { + operation.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary { ["application/json"] = new() { Schema = Ref(document, contract.Body) } }, + }; + if (contract.Shape is Shape.Create or Shape.Mutation) operation.Parameters.Add(new OpenApiParameter + { + Name = IdempotentAttribute.HeaderName, + In = ParameterLocation.Header, + Required = true, + Schema = new OpenApiSchema { Type = JsonSchemaType.String, MinLength = 8, MaxLength = 128, Pattern = "^[!-~]{8,128}$" }, + Description = "Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry.", + }); + if (contract.Shape == Shape.Mutation) operation.Parameters.Add(new OpenApiParameter + { + Name = "If-Match", + In = ParameterLocation.Header, + Required = true, + Schema = EntityTag(), + Description = "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + }); + } + else operation.RequestBody = null; + + operation.Responses ??= []; + var status = contract.Shape == Shape.Create ? "202" : "200"; + foreach (var other in SuccessStatuses.Where(code => code != status)) operation.Responses.Remove(other); + operation.Responses[status] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create => "Accepted: the request's initial resource. Its export runs as a background job; read the group's requests for its status.", + Shape.Ticket => "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", + Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + Shape.Mutation => "Committed receipt, or the retained receipt of a completed exact-key replay.", + _ => discovery ? "The subject's retained groups on the real host, in order." : "Current receipt-safe projection: status and counts, never content.", + }, + Content = new Dictionary { ["application/json"] = new() { Schema = Ref(document, contract.Response) } }, + }; + var methods = string.Join(", ", path.Operations!.Keys.Select(method => method.Method).Order(StringComparer.Ordinal)); + PublicReadDocumentTransformer.DocumentResponses(document, operation, contract.Method, + [ + ("400", "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none."), + ("401", "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge."), + ("403", "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed."), + ("404", "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike."), + ("405", "method_not_allowed after earlier host, credential and scope gates."), + ("413", "payload_too_large; request bodies are at most 4 KiB."), + ("429", "rate_limited by the existing visitor/subject admission."), + ("500", "internal_error without provider, query, identity, ticket or submitted-value diagnostics."), + ("503", "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row."), + ], methods); + if (contract.Body is not null && contract.Shape != Shape.Chunk) operation.Responses["409"] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create => "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + Shape.Ticket => "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + _ => "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + }, + Headers = new Dictionary { ["Cache-Control"] = new OpenApiHeader { Required = true, Schema = Enum("no-store") } }, + Content = new Dictionary { ["application/problem+json"] = new() { Schema = Ref(document, "ProblemDetails") } }, + }; + if (operation.Responses["503"] is OpenApiResponse unavailable) unavailable.Headers?.Remove("Retry-After"); + if (operation.Responses[status] is not OpenApiResponse success) return; + success.Headers ??= new Dictionary(); + if (contract.Shape is Shape.Create or Shape.Mutation) + { + success.Headers["ETag"] = new OpenApiHeader { Required = true, Schema = EntityTag(), Description = "The request's version." }; + success.Headers[IdempotentAttribute.ReplayedHeaderName] = new OpenApiHeader + { + Required = false, + Schema = Enum("true"), + Description = "Present only after fresh original-request disclosure on a replay.", + }; + } + } + + private static string RetainedDescription(Contract contract) => contract.Name switch + { + "ListRetainedDataRequestScopes" => "The retained own scope of ADR-0106 § 9: the groups on the real host where the verified subject holds or held a Membership of any status or has a data request. On an organization host only that organization's group. No Active Membership, no ordinary native session and no tenant or organization selector. Audit Off. No request body.", + "ListRetainedDataRequests" => "The subject's own requests in one retained group, newest first, for a Suspended person, a person whose Membership was revoked or a group where only a request survives. A request whose job died is shown failed. Audit Off. No request body.", + "CreateRetainedDataExport" => "The subject files an export of their own data in one retained group (ADR-0106 § 3, § 9). Refused when the subject holds no Membership of any status there. Strict empty JSON object. MUST audited.", + "CancelRetainedDataRequest" => "The subject cancels their own requested export in one retained group (requested to cancelled). Strict JSON object with requestId only. MUST audited.", + "MintRetainedDataExportTicket" => "The subject mints a fifteen-minute download cursor over their own available, unexpired artifact in one retained group, bound to this retained-entry credential; never honoured on the live path. Strict JSON object with requestId only. Not keyed and never replayed; no If-Match. MUST read-sensitive audited; refused when the row cannot be written.", + _ => "Reads one decrypted chunk through a ticket presented in the body, never the URL, with the retained-entry credential that minted it. Serving the final chunk consumes the ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written.", + }; + private static void Describe(OpenApiDocument document, IOpenApiPathItem path, OpenApiOperation operation, Contract contract) { operation.OperationId = contract.Name; @@ -236,11 +390,17 @@ private static void Schemas(OpenApiDocument document) ("membershipIds", Array(Uuid(), DataRequestLimits.MaximumSnapshotMemberships))]); schemas["DataRequestPage"] = Object(("items", Array(Ref(document, "DataRequestResponse"), 100)), ("pageInfo", Ref(document, "PageInfo"))); schemas["DataExportForSubjectInput"] = Object(("membershipId", Uuid())); + schemas["RetainedDataRequestScopeResponse"] = Object(("tenantId", Uuid()), ("organizationId", Nullable(Uuid()))); + schemas["RetainedDataRequestScopePageResponse"] = Object(("items", Array(Ref(document, "RetainedDataRequestScopeResponse"), 20)), + ("pageInfo", Ref(document, "PageInfo"))); + schemas["RetainedDataRequestTargetInput"] = Object(("requestId", Uuid())); schemas["DataExportTicketResponse"] = Object(("ticket", Ticket()), ("expiresAt", DateTime()), ("chunkCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = DataRequestLimits.MaximumChunkCount.ToString(System.Globalization.CultureInfo.InvariantCulture) }), ("byteCount", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int64", Minimum = "1", Maximum = DataRequestLimits.MaximumBundleBytes.ToString(System.Globalization.CultureInfo.InvariantCulture) })); schemas["DataExportChunkInput"] = Object(("ticket", Ticket()), ("index", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "0", Maximum = (DataRequestLimits.MaximumChunkCount - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) })); + schemas["RetainedDataExportChunkInput"] = Object(("requestId", Uuid()), ("ticket", Ticket()), + ("index", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "0", Maximum = (DataRequestLimits.MaximumChunkCount - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) })); schemas["DataExportChunkResponse"] = Object( ("index", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "0" }), ("count", new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1" }), diff --git a/backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs b/backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs new file mode 100644 index 00000000..9b2d5127 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs @@ -0,0 +1,112 @@ +using LearnStack.Api.Authentication; +using LearnStack.Api.Common; +using LearnStack.Api.Idempotency; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace LearnStack.Api.Identity; + +/// One retained group of the subject on the real host: its tenant and organization, or none for the tenant-wide group. +public sealed record RetainedDataRequestScopeResponse(string TenantId, string? OrganizationId); + +public sealed record RetainedDataRequestScopePageResponse(IReadOnlyList Items, PageInfo PageInfo); + +/// +/// The retained own-scope native entry of the subject's data requests (ADR-0106 § 9, ADR-0107 § 4): six key-less +/// OwnDataRequestEntry operations reached only through the selector-free native session source, for a person +/// whose Membership is Suspended, Revoked or gone. The request each action sends is the exact one the +/// captured before authorization, never a fresh binding of the input, so the +/// witness admits nothing the source did not see. The ticket and the chunk travel only in request and response bodies. +/// +[Route("identity/data-request-entry")] +public sealed class DataRequestEntryController(ISender sender, ITenantContext tenant) : ApiControllerBase +{ + [HttpGet("scopes", Name = "ListRetainedDataRequestScopes")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataRequestScopesOperation)] + [OperationPolicy(typeof(ListRetainedDataRequestScopesQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Scopes(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not ListRetainedDataRequestScopesQuery request) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(request, cancellationToken); + if (result.IsFailure) return result.ToActionResult(); + return Ok(new RetainedDataRequestScopePageResponse(result.Value.Items.Select(group => new RetainedDataRequestScopeResponse( + group.TenantId.Value.ToString("D"), group.OrganizationId?.Value.ToString("D"))).ToArray(), + new(result.Value.NextCursor, null, result.Value.NextCursor is not null, false))); + } + + [HttpGet("requests", Name = "ListRetainedDataRequests")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataRequestListOperation)] + [OperationPolicy(typeof(ListRetainedDataRequestsQuery))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Requests(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not ListRetainedDataRequestsQuery request) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(request, cancellationToken); + return result.IsFailure ? result.ToActionResult() + : Ok(new OwnDataRequestPage(result.Value.Items.Select(DataRequestProjection.Own).ToArray(), result.Value.PageInfo)); + } + + [HttpPost("exports", Name = "CreateRetainedDataExport")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataExportCreateOperation)] + [OperationPolicy(typeof(CreateRetainedDataExportCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateRetainedDataExport)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateExport(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not CreateRetainedDataExportCommand request) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, request, cancellationToken); + } + + [HttpPost("cancellations", Name = "CancelRetainedDataRequest")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataRequestCancelOperation)] + [OperationPolicy(typeof(CancelRetainedDataRequestCommand))] + [Idempotent(ProtectedAdministrationOperation.CancelRetainedDataRequest)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Cancel(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not CancelRetainedDataRequestCommand request) + return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, request, cancellationToken); + } + + [HttpPost("tickets", Name = "MintRetainedDataExportTicket")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataExportTicketOperation)] + [OperationPolicy(typeof(MintRetainedDataExportTicketCommand))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task MintTicket(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not MintRetainedDataExportTicketCommand request) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(request, cancellationToken); + return result.IsFailure ? result.ToActionResult() + : Ok(new DataExportTicketResponse(result.Value.Ticket, DataRequestProjection.Instant(result.Value.ExpiresAt), + result.Value.ChunkCount, result.Value.ByteCount)); + } + + [HttpPost("chunks", Name = "ReadRetainedDataExportChunk")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataExportChunkOperation)] + [OperationPolicy(typeof(ReadRetainedDataExportChunkCommand))] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task ReadChunk(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not ReadRetainedDataExportChunkCommand request) + return AdministrationHttpInput.Invalid(); + var result = await sender.Send(request, cancellationToken); + return result.IsFailure ? result.ToActionResult() : new DataExportChunkResult(result.Value); + } +} diff --git a/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs b/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs index 27a549fb..cb1b6124 100644 --- a/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs +++ b/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs @@ -96,6 +96,26 @@ public async Task InvokeAsync( finally { accessor.Current = previousEntryContext; } return; } + // ADR-0106 § 9: the retained own data-request entry. The source proves the group for the verified subject on the + // real host before any context exists; the factory only reconciles that group against the same host ceiling. + if (OwnDataRequestOperation.ForPath(context.Request.Path) is not null) + { + var previousEntryContext = accessor.Current; + try + { + var source = context.RequestServices.GetRequiredService(); + var scope = await source.PrepareAsync(context); + if (scope.IsFailure) { await OperationClassificationMiddleware.RefuseAsync(context, scope.Error); return; } + var dataRequestIdentity = context.Features.Get()!.Identity!; + var resolved = TenantContextFactory.CreateForOwnDataRequestScope(classification.TenantId!.Value, + classification.OrganizationId, dataRequestIdentity.ActorUserId, source.Selected, Activity.Current?.Id ?? context.TraceIdentifier); + if (resolved.IsFailure) { await OperationClassificationMiddleware.RefuseAsync(context, resolved.Error); return; } + accessor.Current = resolved.Value; + await next(context); + } + finally { accessor.Current = previousEntryContext; } + return; + } if (InvitationEntryOperation.ForPath(context.Request.Path) is not null) { var previousEntryContext = accessor.Current; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs index 343ab643..734ecf4a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs @@ -1,5 +1,6 @@ using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Idempotency; +using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Pagination; using LearnStack.SharedKernel.Results; using MediatR; @@ -151,3 +152,56 @@ public sealed record RevokeDataExportCommand(Guid RequestId, long ExpectedArtifa /// Authorizes only disclosure of a stored receipt for the administrator's original request. public sealed record ReadDataRequestReceiptQuery(Guid RequestId) : IRequest>, IIdempotencyReceiptRead; + +// ---- The subject, through the retained own scope (OperationPolicyKind.OwnDataRequestEntry, ADR-0106 § 9) ---- +// Each type acts in exactly the group the subject's own retained-scope witness proved, never in a Membership's +// context: a Suspended person, a person whose Membership was revoked and a group where only a request survives are +// all served. The group a type names is a selection the witness must agree with, never authority of its own. + +/// One page of the subject's retained groups on the real host, in the function's order. +/// is the last group's key: tenant for the tenant-wide group, else the organization. +public sealed record RetainedDataRequestScopePage(IReadOnlyList Items, string? NextCursor); + +/// Discovers the groups on the real host where the subject holds or held a Membership or has a request. +public sealed record ListRetainedDataRequestScopesQuery(string? Cursor = null, int Limit = 20) : IRequest>; + +/// The subject's own requests in one retained group, newest first. +/// The selected group's organization, or for the tenant-wide group. +public sealed record ListRetainedDataRequestsQuery(OrganizationId? OrganizationId, string? Cursor = null, int Limit = 20) + : IRequest>>; + +/// The subject files an export of their own data in one retained group (ADR-0106 § 3, § 9). +public sealed record CreateRetainedDataExportCommand(OrganizationId? OrganizationId) : IRequest>; + +/// requested → cancelled by the subject in one retained group (ADR-0106 § 8, § 11). +public sealed record CancelRetainedDataRequestCommand(OrganizationId? OrganizationId, Guid RequestId, long ExpectedVersion) + : IRequest>; + +/// Mints a fifteen-minute download cursor over the subject's available artifact in one retained group. +public sealed record MintRetainedDataExportTicketCommand(OrganizationId? OrganizationId, Guid RequestId) : IRequest>; + +/// Reads one decrypted chunk through a ticket in one retained group; the ticket travels only in a request body. +public sealed record ReadRetainedDataExportChunkCommand : IRequest> +{ + public ReadRetainedDataExportChunkCommand(OrganizationId? organizationId, Guid requestId, string ticket, int index) + { + OrganizationId = organizationId; + RequestId = requestId; + Ticket = ticket; + Index = index; + } + + public OrganizationId? OrganizationId { get; } + + public Guid RequestId { get; } + + [PiiSensitive] + public string Ticket { get; } + + public int Index { get; } + + public override string ToString() => nameof(ReadRetainedDataExportChunkCommand); +} + +/// Authorizes only disclosure of a stored receipt for the subject's own original retained-entry request. +public sealed record ReadRetainedDataRequestReceiptQuery(Guid RequestId) : IRequest>, IIdempotencyReceiptRead; 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 5b1df7e1..933818c4 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 @@ -64,6 +64,14 @@ public void Describe(IAuditCatalogBuilder builder) builder.Off(); builder.Off(); builder.Off(); + // ADR-0106 § 9, § 13: the retained own-scope entry writes exactly the live path's rows under the same names. + builder.MustAudit("identity.data_request.create_export", OperationType.Create, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.cancel", OperationType.Update, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_export.mint_ticket", OperationType.ReadSensitive, typeof(DataExportTicket)); + builder.MustAudit("identity.data_export.read_chunk", OperationType.ReadSensitive, typeof(DataExportTicket)); + builder.Off(); + builder.Off(); + builder.Off(); builder.MustAudit(IdentityOperationPolicySource.NativeSessionAdmissionOperation, OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs new file mode 100644 index 00000000..c5f93181 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs @@ -0,0 +1,171 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +// The retained own-scope request types of ADR-0106 § 9 are as thin as the live ones: each consumes the exact live +// witness its own invocation was admitted with, builds the subject's caller and hands over to the same core. No +// Membership read admits them, so a Suspended person, a person whose Membership was revoked and a group where only a +// request survives are served alike; the cores still confine every row to the announced group and to the subject. + +/// +/// Consumes only the exact live retained own data-request scope witness on its physical owner +/// (ADR-0106 § 9), +/// as OwnConsentEntryAuthorization does for the consent subject. +/// +/// +/// The witness was minted by the one HTTP source for this invocation and purpose, after the confined definer proved +/// the group for the verified subject on the real host. Nothing here re-reads the scope: the recheck the cores run +/// after their fences confirms the same witness, decision, owner and context are still live, so a closed request, +/// a replaced feature or a retargeted owner refuses the act. +/// +public sealed class RetainedDataRequestAdmission(IOperationInvocationContext invocations, IOperationPolicyCatalog catalog, + IUnitOfWork unit, ITenantContext context) +{ + internal OwnDataRequestScopeWitness? For(object request, params OwnDataRequestPurpose[] purposes) + { + if (request is not (ListRetainedDataRequestScopesQuery or ListRetainedDataRequestsQuery or CreateRetainedDataExportCommand + or CancelRetainedDataRequestCommand or MintRetainedDataExportTicketCommand or ReadRetainedDataExportChunkCommand + or ReadRetainedDataRequestReceiptQuery) + || invocations.CurrentInvocation is not { IsActive: true, EntryKind: OperationEntryKind.Application, TrustedSource: null } invocation + || !ReferenceEquals(invocation.Operation, request) || !ReferenceEquals(invocation.Context, context) + || !catalog.TryGet(request.GetType(), out var policy) || !ReferenceEquals(policy, invocation.Policy) + || policy.Kind != OperationPolicyKind.OwnDataRequestEntry + || invocation.Candidate is not { IsActive: true, SourceKind: AuthorizationSourceKind.Http } candidate + || invocations.CurrentDecision is not { IsActive: true, Outcome: ProtectedOperationOutcome.Allowed, DataRequestWitness: { } witness } decision + || !ReferenceEquals(decision.Invocation, invocation) || !ReferenceEquals(witness.Invocation, invocation) || !witness.IsActive + || !purposes.Contains(witness.Purpose) + || unit is not IOwnDataRequestUnitOfWork owner || !owner.IsOwnDataRequestOwner(witness) + || !context.IsResolved || context.Origin != TenantContextOrigin.HostAndOwnDataRequestScope + || context.UserId != witness.Actor || context.TenantId != witness.TenantId || context.OrganizationId != witness.OrganizationId + || candidate.Actor != witness.Actor || candidate.TenantId != witness.TenantId || candidate.OrganizationId != witness.OrganizationId) + return null; + return witness; + } + + /// + /// The subject's caller for one exact retained group: is the group the request type + /// selected, which must be the very group the witness proved. + /// + internal Result Admit(object request, OrganizationId? organization, params OwnDataRequestPurpose[] purposes) + { + var witness = For(request, purposes); + if (witness?.Group is not { } group || group.TenantId != context.TenantId || group.OrganizationId != organization) + return DataRequestService.Fail("lockey_forbidden"); + return Result.Ok(new DataRequestCaller(witness.Actor, DataRequestRole.Subject, token => + { + token.ThrowIfCancellationRequested(); + return Task.FromResult(ReferenceEquals(For(request, purposes), witness) + ? Result.Ok(None.Value) : DataRequestService.Fail("lockey_forbidden")); + })); + } + + /// The group a receipt read runs in is the witness's own, whichever keyed purpose it came from. + internal Result AdmitReceipt(ReadRetainedDataRequestReceiptQuery request) => + For(request, OwnDataRequestPurpose.Create, OwnDataRequestPurpose.Cancel) is { Group: { } group } + ? Admit(request, group.OrganizationId, OwnDataRequestPurpose.Create, OwnDataRequestPurpose.Cancel) + : DataRequestService.Fail("lockey_forbidden"); +} + +/// Returns the groups the definer proved for the subject on the real host; it reads nothing more. +public sealed class ListRetainedDataRequestScopesQueryHandler(RetainedDataRequestAdmission admission) + : IRequestHandler> +{ + public Task> Handle(ListRetainedDataRequestScopesQuery request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + cancellationToken.ThrowIfCancellationRequested(); + if (request.Limit is < 1 or > OwnDataRequestScopeWitness.MaximumPage || request.Cursor is { Length: > 64 }) + return Task.FromResult(DataRequestService.Fail("lockey_validation_failed")); + var witness = admission.For(request, OwnDataRequestPurpose.List); + if (witness?.ScopePage is not { } page || page.Items.Length > request.Limit) + return Task.FromResult(DataRequestService.Fail("lockey_forbidden")); + var items = page.Items.ToArray(); + if (!ReferenceEquals(admission.For(request, OwnDataRequestPurpose.List), witness)) + return Task.FromResult(DataRequestService.Fail("lockey_forbidden")); + return Task.FromResult(Result.Ok(new RetainedDataRequestScopePage(items, page.NextCursor))); + } +} + +public sealed class ListRetainedDataRequestsQueryHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler>> +{ + public async Task>> Handle(ListRetainedDataRequestsQuery request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (request.Limit is < 1 or > OwnDataRequestScopeWitness.MaximumPage) + return DataRequestService.Fail>("lockey_validation_failed"); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Read); + return caller.IsFailure ? Result>.Fail(caller.Error) + : await service.ListAsync(caller.Value, IdentityOperationPolicySource.RetainedDataRequestListOperation, request.Cursor, + request.Limit, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class CreateRetainedDataExportCommandHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateRetainedDataExportCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Create); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateExportAsync(caller.Value, caller.Value.Actor, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class CancelRetainedDataRequestCommandHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CancelRetainedDataRequestCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Cancel); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CancelAsync(caller.Value, request.RequestId, request.ExpectedVersion, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class MintRetainedDataExportTicketCommandHandler(RetainedDataRequestAdmission admission, DataExportDownloadService service) + : IRequestHandler> +{ + public async Task> Handle(MintRetainedDataExportTicketCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Ticket); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.MintTicketAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ReadRetainedDataExportChunkCommandHandler(RetainedDataRequestAdmission admission, DataExportDownloadService service) + : IRequestHandler> +{ + public async Task> Handle(ReadRetainedDataExportChunkCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Chunk); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.ReadChunkAsync(caller.Value, request.RequestId, request.Ticket, request.Index, cancellationToken).ConfigureAwait(false); + } +} + +public sealed class ReadRetainedDataRequestReceiptQueryHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(ReadRetainedDataRequestReceiptQuery request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.AdmitReceipt(request); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.ReadReceiptAsync(caller.Value, request.RequestId, cancellationToken).ConfigureAwait(false); + } +} 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 abeaf97a..798f9cb1 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -59,6 +59,15 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource public const string DataRequestCancelOperation = "identity.data_request.cancel"; public const string DataExportRevokeOperation = "identity.data_request.revoke_export"; public const string DataRequestReceiptOperation = "identity.data_request.read_receipt"; + // ADR-0106 § 9: the retained own-scope native entry (OwnDataRequestEntry). The same prefix and no key; each is + // admitted only by the subject's own retained-scope witness, never by a Membership in the announced context. + public const string RetainedDataRequestScopesOperation = "identity.data_request.list_retained_scopes"; + public const string RetainedDataRequestListOperation = "identity.data_request.list_retained"; + public const string RetainedDataExportCreateOperation = "identity.data_request.create_retained_export"; + public const string RetainedDataRequestCancelOperation = "identity.data_request.cancel_retained"; + public const string RetainedDataExportTicketOperation = "identity.data_request.mint_retained_export_ticket"; + public const string RetainedDataExportChunkOperation = "identity.data_request.read_retained_export_chunk"; + public const string RetainedDataRequestReceiptOperation = "identity.data_request.read_retained_receipt"; public const string PublicSignInOperation = "identity.public_sign_in.read"; /// Virtual Portal Public definition for the anonymous sign-in read; never a stored Role grant. public static PermissionDefinition PublicSignIn { get; } = new(PermissionScope.Tenant, "identity.public_sign_in.read"); @@ -91,6 +100,13 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForOwnDataRequest(OwnDataExportTicketOperation), OperationPolicy.ForOwnDataRequest(OwnDataExportChunkOperation), OperationPolicy.ForOwnDataRequest(OwnDataRequestReceiptOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestScopesOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestListOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportCreateOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestCancelOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportTicketOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportChunkOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestReceiptOperation), OperationPolicy.ForProtected(DataExportCreateOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected(DataRequestListOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), OperationPolicy.ForProtected(DataRequestReadOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), 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 d6e67af9..85c2bd0e 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 @@ -73,6 +73,9 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipContextsQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnCapabilitiesQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipCustomFieldsQuery))); + // ADR-0106 § 9: retained discovery and status reads run on a physically read-only owner, as their witness requires. + services.AddSingleton(new ExplicitReadOnlyRequest(typeof(ListRetainedDataRequestScopesQuery))); + services.AddSingleton(new ExplicitReadOnlyRequest(typeof(ListRetainedDataRequestsQuery))); services.TryAddScoped>(provider => () => provider.GetRequiredService()); services.AddIdentityDataRequests(); return services; @@ -105,6 +108,7 @@ private static void AddIdentityDataRequests(this IServiceCollection services) services.TryAddSingleton(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs index 65f54610..ccc9ddcf 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs @@ -32,6 +32,43 @@ private static bool ConsentSubjectHandoff(TypeDefinition controller, MethodDefin && calls.All(target => target.DeclaringType.FullName != ProtectedResult); } + private const string DataRequestEntryController = "LearnStack.Api.Identity.DataRequestEntryController"; + + /// + /// ADR-0106 § 9: like the consent subject, each retained data-request entry action sends exactly the request its + /// source captured before authorization, read once from its request feature, and never constructs one. The keyed + /// purposes hand off to the protected carrier; the rest send once. + /// + private static bool DataRequestEntryHandoff(TypeDefinition controller, MethodDefinition action, Endpoint endpoint) + { + const string Feature = "LearnStack.Api.Authentication.OwnDataRequestEntryRequest"; + if (controller.FullName != DataRequestEntryController + || action.DeclaringType != controller || endpoint.Controller != controller.FullName + || endpoint.Request != (action.Name switch + { + "Scopes" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListRetainedDataRequestScopesQuery), + "Requests" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListRetainedDataRequestsQuery), + "CreateExport" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedDataExportCommand), + "Cancel" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CancelRetainedDataRequestCommand), + "MintTicket" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.MintRetainedDataExportTicketCommand), + "ReadChunk" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ReadRetainedDataExportChunkCommand), + _ => null, + })) return false; + var instructions = ActionBodies(controller, action.Name).SelectMany(method => method.Body.Instructions).ToArray(); + var calls = instructions.Select(item => item.Operand).OfType().ToArray(); + if (instructions.Count(item => item.OpCode == OpCodes.Isinst && item.Operand is TypeReference type + && type.FullName == endpoint.Request.FullName) != 1 + || calls.Count(target => target.DeclaringType.FullName == Feature && target.Name == "get_Request") != 1 + || calls.Count(target => target is GenericInstanceMethod generic && generic.Name == "Get" && generic.GenericArguments.Count == 1 + && generic.GenericArguments[0].FullName == Feature) != 1 + || instructions.Any(item => item.OpCode == OpCodes.Newobj && item.Operand is MethodReference target + && target.DeclaringType.Namespace == endpoint.Request.Namespace)) return false; + return endpoint.ProtectedOperation is not null + ? calls.Count(HandoffSignature) == 1 && calls.All(target => target.DeclaringType.FullName != Sender) + : calls.Count(target => target.DeclaringType.FullName == Sender && target.Name == "Send") == 1 + && calls.All(target => target.DeclaringType.FullName != ProtectedResult); + } + private static bool CustomFieldTransitionHandoff(TypeDefinition controller, MethodDefinition action, Endpoint endpoint) { if (controller.FullName != "LearnStack.Api.Customization.CustomFieldDefinitionsController" diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.Controls.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.Controls.cs index 15451dab..eadf9eba 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.Controls.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.Controls.cs @@ -90,10 +90,10 @@ private static void AssertProtectedAdministrationControls(ModuleDefinition[] mod var controller = map["LearnStack.Api:" + endpoint.Controller]; var action = controller.Methods.Single(method => method.Name == endpoint.Action); ProtectedHandoff(controller, action, endpoint).Should().BeTrue(); - if (controller.FullName == "LearnStack.Api.Tenancy.ConsentSubjectController" + if (controller.FullName is "LearnStack.Api.Tenancy.ConsentSubjectController" or DataRequestEntryController || controller.FullName == "LearnStack.Api.Customization.CustomFieldDefinitionsController" && action.Name is ("Retire" or "Discard")) { - var bodyMethods = controller.FullName == "LearnStack.Api.Tenancy.ConsentSubjectController" + var bodyMethods = controller.FullName is "LearnStack.Api.Tenancy.ConsentSubjectController" or DataRequestEntryController ? ActionBodies(controller, action.Name).ToArray() : ActionBodies(controller, "Transition").ToArray(); var operand = bodyMethods.SelectMany(method => method.Body.Instructions) .First(instruction => instruction.Operand is MethodReference target && HandoffSignature(target)); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.cs index aeba99c1..6649e846 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.cs @@ -22,6 +22,8 @@ private static bool ProtectedHandoff(TypeDefinition controller, MethodDefinition { if (controller.FullName == "LearnStack.Api.Tenancy.ConsentSubjectController") return ConsentSubjectHandoff(controller, action, endpoint); + if (controller.FullName == DataRequestEntryController) + return DataRequestEntryHandoff(controller, action, endpoint); if (controller.FullName == "LearnStack.Api.Customization.CustomFieldDefinitionsController" && action.Name is ("Retire" or "Discard")) return CustomFieldTransitionHandoff(controller, action, endpoint); var bodies = ActionBodies(controller, action.Name).ToArray(); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs index 127393b4..4d2ecec2 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs @@ -40,10 +40,12 @@ private sealed record ProtectedShape(int Operation, string Name, int Kind, strin new(27, "CancelDataRequest", 8, "DataSubjectRequest", "ExpectedVersion"), new(28, "RevokeOwnDataExport", 8, "DataSubjectRequest", "ExpectedArtifactVersion"), new(29, "RevokeDataExport", 8, "DataSubjectRequest", "ExpectedArtifactVersion"), + new(30, "CreateRetainedDataExport", 8, "DataSubjectRequest", null), + new(31, "CancelRetainedDataRequest", 8, "DataSubjectRequest", "ExpectedVersion"), ]; - /// The keyed creations: the three 201 creations and ADR-0106 § 10's two 202 data-request creations. - private static bool Creates(int operation) => operation is 7 or 11 or 15 or 24 or 25; + /// The keyed creations: the three 201 creations and ADR-0106 § 10's three 202 data-request creations. + private static bool Creates(int operation) => operation is 7 or 11 or 15 or 24 or 25 or 30; private static readonly Lazy ProtectedSourceBaseline = new(() => ProtectedSourceOffenders( File.ReadAllText(Path.Combine(RepositoryPaths.BackendSrc(), "LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs")), @@ -159,8 +161,8 @@ private static IEnumerable ProtectedSourceOffenders(string descriptorSou 21 => "Membership(awaitsender.Send(command,cancellationToken),null)", 22 => "Consent(awaitsender.Send(command,cancellationToken),true)", 23 => "Consent(awaitsender.Send(command,cancellationToken),false)", - 24 or 25 => "DataRequest(awaitsender.Send(command,cancellationToken),null)", - 26 or 27 => "DataRequest(awaitsender.Send(command,cancellationToken),command.RequestId)", + 24 or 25 or 30 => "DataRequest(awaitsender.Send(command,cancellationToken),null)", + 26 or 27 or 31 => "DataRequest(awaitsender.Send(command,cancellationToken),command.RequestId)", 28 or 29 => "Artifact(awaitsender.Send(command,cancellationToken),command.RequestId)", _ => throw new InvalidOperationException("Unknown expected protected operation") }; diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs index 3a15d983..c5bfee63 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs @@ -288,6 +288,25 @@ private sealed record Endpoint(string Controller, string Action, string Verb, st new("LearnStack.Api.Identity.DataRequestsController", "Revoke", "POST", "identity/data-requests", "{id}/artifact/revocations", "RevokeDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.RevokeDataExportCommand), "LearnStackOperation:identity.data_request.revoke_export", typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 29, new(OperationClass.Must, OperationType.Delete, "identity.data_export.revoke", typeof(LearnStack.Modules.Identity.Domain.DataExportArtifact))), + // ADR-0106 § 9: the retained own-scope native entry; every action sends the source's captured request. + new("LearnStack.Api.Identity.DataRequestEntryController", "Scopes", "GET", "identity/data-request-entry", "scopes", + "ListRetainedDataRequestScopes", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListRetainedDataRequestScopesQuery), "LearnStackOperation:identity.data_request.list_retained_scopes", + typeof(LearnStack.Api.Identity.RetainedDataRequestScopePageResponse), 200, null, new()), + new("LearnStack.Api.Identity.DataRequestEntryController", "Requests", "GET", "identity/data-request-entry", "requests", + "ListRetainedDataRequests", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ListRetainedDataRequestsQuery), "LearnStackOperation:identity.data_request.list_retained", + typeof(LearnStack.Api.Identity.OwnDataRequestPage), 200, null, new()), + new("LearnStack.Api.Identity.DataRequestEntryController", "CreateExport", "POST", "identity/data-request-entry", "exports", + "CreateRetainedDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedDataExportCommand), "LearnStackOperation:identity.data_request.create_retained_export", + typeof(LearnStack.Api.Identity.DataRequestAcceptedResponse), 202, 30, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_export", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestEntryController", "Cancel", "POST", "identity/data-request-entry", "cancellations", + "CancelRetainedDataRequest", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CancelRetainedDataRequestCommand), "LearnStackOperation:identity.data_request.cancel_retained", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 31, new(OperationClass.Must, OperationType.Update, "identity.data_request.cancel", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestEntryController", "MintTicket", "POST", "identity/data-request-entry", "tickets", + "MintRetainedDataExportTicket", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.MintRetainedDataExportTicketCommand), "LearnStackOperation:identity.data_request.mint_retained_export_ticket", + typeof(LearnStack.Api.Identity.DataExportTicketResponse), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_export.mint_ticket", typeof(LearnStack.Modules.Identity.Domain.DataExportTicket))), + new("LearnStack.Api.Identity.DataRequestEntryController", "ReadChunk", "POST", "identity/data-request-entry", "chunks", + "ReadRetainedDataExportChunk", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.ReadRetainedDataExportChunkCommand), "LearnStackOperation:identity.data_request.read_retained_export_chunk", + typeof(LearnStack.Api.Identity.DataExportChunkResponse), 200, null, new(OperationClass.Must, OperationType.ReadSensitive, "identity.data_export.read_chunk", typeof(LearnStack.Modules.Identity.Domain.DataExportTicket))), // ADR-0099: the protected federation operations hand off to the one runner, without Idempotency-Key. new("LearnStack.Api.Identity.FederationController", "Get", "GET", "identity/federation", null, "GetFederationConnection", typeof(LearnStack.Modules.Identity.Application.Contracts.Federation.GetFederationConnectionQuery), "LearnStackOperation:identity.federation.read", @@ -342,9 +361,9 @@ public void Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly() => WithProdu errors.Should().BeEmpty( "Fix: retain the exact ADR-0064/0076 reads and ADR-0078/0079 finite entry/administration union; all findings: {0}", string.Join("\n", errors)); // The totals Standard 21 publishes for this rule; Violations binds the production surface to this literal census. - Endpoints.Should().HaveCount(84, "the census closes the surface at 84 MVC actions"); - Endpoints.Select(endpoint => endpoint.Request).Distinct().Should().HaveCount(79, - "Standard 21 publishes 79 distinct IRequest roots for the 84 actions"); + Endpoints.Should().HaveCount(90, "the census closes the surface at 90 MVC actions"); + Endpoints.Select(endpoint => endpoint.Request).Distinct().Should().HaveCount(85, + "Standard 21 publishes 85 distinct IRequest roots for the 90 actions"); }); /// ADR-0064's controls mutate the same production route census. @@ -496,7 +515,7 @@ public void Authenticated_http_census_follows_production_helpers_and_nested_disp var map = Types(modules).ToDictionary(Key, StringComparer.Ordinal); var account = map.Values.Single(type => type.FullName == Account); var handlers = HandlerRoots(map).ToArray(); - handlers.Should().HaveCount(58, "all finite HTTP requests have real production handlers; the seven invitation operations and three policy operations share two additional handler classes, the federation commands share one handler class beside its two query handlers, and each of the twelve data-request requests has its own thin handler"); + handlers.Should().HaveCount(64, "all finite HTTP requests have real production handlers; the seven invitation operations and three policy operations share two additional handler classes, the federation commands share one handler class beside its two query handlers, and each of the eighteen data-request requests (twelve live, six retained-entry) has its own thin handler"); Violations(modules, facts).Should().BeEmpty(); AssertPolicyMetadataControls(modules, facts); AssertControllerMetadataControls(modules, facts); @@ -712,6 +731,8 @@ private static SortedSet Violations(ModuleDefinition[] modules, CensusFa foreach (var offender in AttachedFilterOffenders(type, action, map)) errors.Add(offender); if (!(type.FullName == "LearnStack.Api.Tenancy.ConsentSubjectController" ? ConsentSubjectHandoff(type, action, entry) + : type.FullName == DataRequestEntryController + ? DataRequestEntryHandoff(type, action, entry) : type.FullName == "LearnStack.Api.Identity.InvitationEntryController" ? InvitationEntryHandoff(type, action, entry) : type.FullName == FederationController diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.DataRequest.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.DataRequest.cs new file mode 100644 index 00000000..91c1adf5 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.DataRequest.cs @@ -0,0 +1,218 @@ +using FluentAssertions; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0106 § 9: the retained own data-request entry's authority exceptions, each the consent subject's exception +/// applied to the data-request source and credential, and each refusing a substituted value. +/// +public sealed partial class AuthenticationAuthorityTests +{ + private const string DataRequestInput = Authentication + "OwnDataRequestHttpInput"; + private const string DataRequestEntryRequest = Authentication + "OwnDataRequestEntryRequest"; + private const string DataRequestWitnessSource = "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness/MintingSource"; + private static readonly string[] DataRequestResolverActorSubstitutions = ["identity!.ActorUserId", "UserId.SystemActor"]; + private static readonly string DataRequestSourceText = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, + "LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs")); + private static readonly bool DataRequestSourceIsConfined = DataRequestForwardingSourceIsConfined(DataRequestSourceText); + + // The same immediate hash sink as the consent credential: no token storage, claim read or forwarding. + private static bool IsClosedDataRequestTokenRead(Call call, Call[] calls) + { + const string encoded = "System.String Microsoft.IdentityModel.JsonWebTokens.JsonWebToken::get_EncodedToken()"; + if (call.Source.Site != ApprovedSites[DataRequestCredential + ".Capture"] || call.Target.FullName != encoded) return false; + var reads = call.Source.Definition.Body.Instructions.Where(instruction => instruction.Operand is MethodReference target + && target.FullName == encoded).ToArray(); + if (reads.Length != 1 || reads[0].OpCode != OpCodes.Callvirt) return false; + var read = reads[0]; + return read.Previous?.OpCode == OpCodes.Ldarg_1 + && read.Next?.Operand is MethodReference bytes + && bytes.FullName == "System.Byte[] System.Text.Encoding::GetBytes(System.String)" + && read.Next.Next?.Operand is MethodReference hash + && hash.FullName == "System.Byte[] System.Security.Cryptography.SHA256::HashData(System.Byte[])" + && read.Next.Next.Next?.Next?.Operand is MethodReference compare + && compare.FullName == "System.Boolean System.Security.Cryptography.CryptographicOperations::FixedTimeEquals(System.ReadOnlySpan`1,System.ReadOnlySpan`1)" + && calls.Count(candidate => candidate.Target.FullName == ApprovedSites[DataRequestCredential + ".Capture"]) == 1 + && calls.Count(candidate => candidate.Target.FullName == ApprovedSites[DataRequestCredential + ".Capture"] + && candidate.Source.Site == ApprovedSites[Events + ".TokenValidated"]) == 1; + } + + private static bool IsCapturedDataRequestRead(Instruction? read) => read is { OpCode.Code: Code.Callvirt, Operand: MethodReference getter } + && getter.FullName == Signature(DataRequestInput, "get_Request", "System.Object"); + + private static bool IsClosedDataRequestRequestStore(Method method, Instruction instruction) => DataRequestSourceIsConfined + && method.Site == ApprovedSites[DataRequestSource + ".PrepareAsync"] && instruction.OpCode == OpCodes.Stfld + && instruction.Operand is FieldReference field && field.DeclaringType.FullName == DataRequestSource && field.Name == "_request" + && IsCapturedDataRequestRead(instruction.Previous); + + private static bool IsClosedDataRequestForwarding(Method method, Instruction instruction, MethodReference target) + { + if (!DataRequestSourceIsConfined) return false; + if (method.Site == ApprovedSites[DataRequestSource + ".ForInvocation"]) + { + if (target.FullName == Signature(DataRequestWitnessSource, "IsEvidenceCurrent", "System.Boolean", "System.Object", "LearnStack.SharedKernel.Permissions.OperationInvocation")) + return instruction.Previous?.OpCode == OpCodes.Ldarg_1 && instruction.Previous.Previous?.OpCode == OpCodes.Ldarg_0 + && instruction.Previous.Previous.Previous?.OpCode == OpCodes.Ldarg_0; + return target.FullName == Signature(DataRequestWitnessSource, "Capture", "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness", + "System.Object", "LearnStack.SharedKernel.Permissions.OperationInvocation", "LearnStack.SharedKernel.Identity.GlobalIdentitySubject", User, + "LearnStack.SharedKernel.Identifiers.TenantId", Organization, "System.String", "LearnStack.SharedKernel.Identity.OwnDataRequestPurpose", + "LearnStack.SharedKernel.DataProtection.DataRequestScopeGroup", "LearnStack.SharedKernel.Identity.OwnDataRequestScopePage") + && method.Definition.Body.Instructions.Count(candidate => candidate.Operand is MethodReference capture + && capture.FullName == target.FullName) == 1 + && DataRequestCapturePrefix(method) is { } prefix && prefix.OpCode == OpCodes.Ldarg_0 + && prefix.Next?.OpCode == OpCodes.Ldarg_0 && prefix.Next.Next?.OpCode == OpCodes.Ldarg_1; + } + // Preparation forwards one opaque value: the captured input's request, into its request feature. + return method.Site == ApprovedSites[DataRequestSource + ".PrepareAsync"] + && target.FullName == Signature(DataRequestEntryRequest, ".ctor", "System.Void", "System.Object") + && instruction.OpCode == OpCodes.Newobj && IsCapturedDataRequestRead(instruction.Previous); + } + + private static Instruction? DataRequestCapturePrefix(Method method) + { + var subject = method.Definition.Body.Instructions.SingleOrDefault(instruction => instruction.OpCode == OpCodes.Ldfld + && instruction.Operand is FieldReference field && field.DeclaringType.FullName == DataRequestSource && field.Name == "_subject"); + return subject?.Previous?.Previous?.Previous?.Previous; + } + + private static bool DataRequestForwardingSourceIsConfined(string source) + { + var root = CSharpSyntaxTree.ParseText(source).GetRoot(); + if (root.ContainsDiagnostics) return false; + var type = root.DescendantNodes().OfType().SingleOrDefault(node => node.Identifier.ValueText == "OwnDataRequestSubjectSource"); + if (type is null) return false; + var prepare = type.Members.OfType().SingleOrDefault(node => node.Identifier.ValueText == "PrepareAsync"); + var invocation = type.Members.OfType().SingleOrDefault(node => node.Identifier.ValueText == "ForInvocation"); + if (prepare is null || invocation is null) return false; + var assignments = prepare.DescendantNodes().OfType().Where(node => node.Left.ToString() is "_request" or "_requestFeature").ToArray(); + var lambdas = prepare.DescendantNodes().OfType().ToArray(); + // Every scope observation is for the normalized actor under the independently classified host ceiling. + var lookups = prepare.DescendantNodes().OfType() + .Where(node => node.Expression.ToString() == "lookup.LookupAsync").ToArray(); + var mint = invocation.DescendantNodes().OfType() + .Where(node => node.Expression.ToString() is "Capture" or "IsEvidenceCurrent").ToArray(); + return assignments.Length == 2 && Equivalent(assignments[0], "_request = input.Request") + && Equivalent(assignments[1], "_requestFeature = new OwnDataRequestEntryRequest(input.Request)") + && lambdas.Length == 0 + && lookups.Length == 3 && lookups.All(call => call.ArgumentList.Arguments.Count == 8 + && call.ArgumentList.Arguments[0].ToString() == "identity.ActorUserId" + && call.ArgumentList.Arguments[1].ToString() == "tenant" + && call.ArgumentList.Arguments[2].ToString() == "host.OrganizationId") + && mint.Length == 2 && Equivalent(mint[0], "IsEvidenceCurrent(this, invocation)") + && Equivalent(mint[1], "Capture(this, invocation, _subject!, _identity!.ActorUserId, _host!.TenantId!.Value, _host.OrganizationId, _host.Host, _purpose!.Purpose, Selected, _page)"); + + static bool Equivalent(Microsoft.CodeAnalysis.SyntaxNode actual, string expected) => + SyntaxFactory.AreEquivalent(actual, SyntaxFactory.ParseExpression(expected)); + } + + private static bool DataRequestResolverActorIsConfined(string source) + { + var root = CSharpSyntaxTree.ParseText(source).GetRoot(); + if (root.ContainsDiagnostics) return false; + var calls = root.DescendantNodes().OfType().Where(node => + node.Expression.ToString() == "TenantContextFactory.CreateForOwnDataRequestScope").ToArray(); + return calls.Length == 1 && calls[0].Ancestors().OfType().Single().Identifier.ValueText == "InvokeAsync" + && SyntaxFactory.AreEquivalent(calls[0], SyntaxFactory.ParseExpression( + "TenantContextFactory.CreateForOwnDataRequestScope(classification.TenantId!.Value, classification.OrganizationId, dataRequestIdentity.ActorUserId, source.Selected, Activity.Current?.Id ?? context.TraceIdentifier)")); + } + + [Fact] + public void Retained_data_request_authority_exceptions_reject_substituted_values() => WithProduction(modules => + { + Offenders(modules).Should().BeEmpty(); + DataRequestSourceIsConfined.Should().BeTrue(); + var resolverSource = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Api/Tenancy/TenantResolverMiddleware.cs")); + DataRequestResolverActorIsConfined(resolverSource).Should().BeTrue(); + foreach (var replacement in DataRequestResolverActorSubstitutions) + { + var dirty = resolverSource.Replace("dataRequestIdentity.ActorUserId", replacement, StringComparison.Ordinal); + dirty.Should().NotBe(resolverSource); + DataRequestResolverActorIsConfined(dirty).Should().BeFalse("the retained scope uses the completed normalized actor on the real host"); + } + + foreach (var (before, after) in new[] + { + ("_request = input.Request", "_request = identity"), + ("new OwnDataRequestEntryRequest(input.Request)", "new OwnDataRequestEntryRequest(identity)"), + ("IsEvidenceCurrent(this, invocation)", "IsEvidenceCurrent(_identity!, invocation)"), + ("Capture(this, invocation, _subject!", "Capture(_identity!, invocation, _subject!"), + ("lookup.LookupAsync(identity.ActorUserId, tenant, host.OrganizationId", "lookup.LookupAsync(UserId.SystemActor, tenant, host.OrganizationId"), + ("lookup.LookupAsync(identity.ActorUserId, tenant, host.OrganizationId", "lookup.LookupAsync(identity.ActorUserId, tenant, input.OrganizationId"), + }) + { + var dirty = DataRequestSourceText.Replace(before, after, StringComparison.Ordinal); + dirty.Should().NotBe(DataRequestSourceText); + DataRequestForwardingSourceIsConfined(dirty).Should().BeFalse("no source exception may forward identity, widen the host or replace the captured request"); + } + var lambda = DataRequestSourceText.Replace("var input = await OwnDataRequestHttpInput.ReadAsync(http, purpose);", + "var input = await OwnDataRequestHttpInput.ReadAsync(http, purpose); Func leak = () => identity;", StringComparison.Ordinal); + lambda.Should().NotBe(DataRequestSourceText); + DataRequestForwardingSourceIsConfined(lambda).Should().BeFalse("preparation crosses no delegate boundary"); + + var api = modules.Single(module => module.Assembly.Name.Name == "LearnStack.Api"); + var methods = Methods(api.Types.SelectMany(Flatten)).ToArray(); + foreach (var site in new[] { DataRequestSource + ".PrepareAsync", DataRequestSource + ".ForInvocation", DataRequestSource + ".get_Actor", + DataRequestSource + ".DownloadCredential", ExportBinding + ".CaptureRetained" }) + { + var actorReads = methods.Where(method => method.Site == ApprovedSites[site]).SelectMany(method => method.Definition.Body.Instructions) + .Where(instruction => instruction.Operand is MethodReference target && target.FullName == Signature(Identity, "get_ActorUserId", User)) + .ToArray(); + actorReads.Should().NotBeEmpty(site); + var saved = actorReads.Select(instruction => (Instruction: instruction, instruction.OpCode, instruction.Operand)).ToArray(); + foreach (var item in saved) { item.Instruction.OpCode = OpCodes.Nop; item.Instruction.Operand = null; } + Offenders(modules).Should().Contain(error => error.StartsWith("Changed/missing validated ActorUserId consumers:", StringComparison.Ordinal)); + foreach (var item in saved) { item.Instruction.OpCode = item.OpCode; item.Instruction.Operand = item.Operand; } + Offenders(modules).Should().BeEmpty("restoring " + site + " restores its exact normalized actor consumer"); + } + var capture = methods.Single(method => method.Site == ApprovedSites[DataRequestCredential + ".Capture"]); + var read = capture.Definition.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target + && target.FullName == "System.String Microsoft.IdentityModel.JsonWebTokens.JsonWebToken::get_EncodedToken()"); + Check(read.Previous, OpCodes.Ldnull, null, "the encoded token comes from the validated Capture argument"); + Check(read.Next.Next, OpCodes.Nop, null, "the encoded token cannot escape its immediate hash sink"); + var extraRead = Instruction.Create(OpCodes.Callvirt, (MethodReference)read.Operand); + capture.Definition.Body.Instructions.Add(extraRead); + Offenders(modules).Should().NotBeEmpty("an extra encoded-token read is not covered"); + capture.Definition.Body.Instructions.Remove(extraRead); + var prepare = methods.Single(method => method.Site == ApprovedSites[DataRequestSource + ".PrepareAsync"] && method.Definition.Name == "MoveNext"); + foreach (var sink in prepare.Definition.Body.Instructions.Where(instruction => + instruction.Operand is FieldReference field && field.DeclaringType.FullName == DataRequestSource && field.Name == "_request" && instruction.OpCode == OpCodes.Stfld + || instruction.Operand is MethodReference target && target.FullName == Signature(DataRequestEntryRequest, ".ctor", "System.Void", "System.Object")).ToArray()) + Check(sink.Previous, OpCodes.Ldnull, null, "only the captured request getter supplies each opaque request sink"); + var invocation = methods.Single(method => method.Site == ApprovedSites[DataRequestSource + ".ForInvocation"]); + var prefix = DataRequestCapturePrefix(invocation)!; + Check(prefix.Next, OpCodes.Ldnull, null, "the data-request minter accepts only its own captured evidence object"); + var current = invocation.Definition.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target + && target.DeclaringType.FullName == DataRequestWitnessSource && target.Name == "IsEvidenceCurrent"); + Check(current.Previous.Previous, OpCodes.Ldnull, null, "the data-request liveness gate checks only this exact source"); + var witness = api.GetType(CandidateSource).NestedTypes.Single(type => type.FullName == CredentialWitness); + var field = witness.Fields.Single(item => item.Name == "k__BackingField"); + field.IsInitOnly = false; + Offenders(modules).Should().NotBeEmpty("the tenth witness field is immutable"); + field.IsInitOnly = true; + var property = witness.Properties.Single(item => item.Name == "DataRequest"); + witness.Properties.Remove(property); + Offenders(modules).Should().NotBeEmpty("the tenth witness property is a required exact subject"); + witness.Properties.Add(property); + var constructor = witness.Methods.Single(method => method.IsConstructor); + var parameter = constructor.Parameters[^1]; + var originalType = parameter.ParameterType; + parameter.ParameterType = api.TypeSystem.Object; + Offenders(modules).Should().NotBeEmpty("the tenth constructor argument cannot erase the data-request source type"); + parameter.ParameterType = originalType; + Offenders(modules).Should().BeEmpty(); + + void Check(Instruction instruction, OpCode opcode, object? operand, string because) + { + var originalOpcode = instruction.OpCode; var originalOperand = instruction.Operand; + instruction.OpCode = opcode; instruction.Operand = operand; + Offenders(modules).Should().NotBeEmpty(because); + instruction.OpCode = originalOpcode; instruction.Operand = originalOperand; + Offenders(modules).Should().BeEmpty("restoring " + because); + } + }); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 7ee15dbd..966a80e1 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -34,6 +34,18 @@ public sealed partial class AuthenticationAuthorityTests [ConsentSource + ".PrepareAsync"] = Signature(ConsentSource, "PrepareAsync", TaskType + "`1>", Http), [ConsentSource + ".ForInvocation"] = Signature(ConsentSource, "ForInvocation", "LearnStack.SharedKernel.Identity.ConsentSubjectScopeWitness", "LearnStack.SharedKernel.Permissions.OperationInvocation"), [ConsentSource + ".get_Actor"] = Signature(ConsentSource, "get_Actor", OptionalUser), + [DataRequestCredential + "..ctor"] = Signature(DataRequestCredential, ".ctor", "System.Void", Http, Feature, Verified, "System.String"), + [DataRequestCredential + ".Capture"] = Signature(DataRequestCredential, "Capture", DataRequestCredential, Http, "Microsoft.IdentityModel.JsonWebTokens.JsonWebToken", Verified), + [DataRequestCredential + ".get_Subject"] = Signature(DataRequestCredential, "get_Subject", Verified), + [DataRequestCredential + ".IsCurrent"] = Signature(DataRequestCredential, "IsCurrent", "System.Boolean", Http), + [DataRequestSource + ".IsCurrent"] = Signature(DataRequestSource, "IsCurrent", "System.Boolean", Http), + [DataRequestSource + ".PrepareAsync"] = Signature(DataRequestSource, "PrepareAsync", TaskType + "`1>", Http), + [DataRequestSource + ".ForInvocation"] = Signature(DataRequestSource, "ForInvocation", "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness", "LearnStack.SharedKernel.Permissions.OperationInvocation"), + [DataRequestSource + ".get_Actor"] = Signature(DataRequestSource, "get_Actor", OptionalUser), + [DataRequestSource + ".DownloadCredential"] = Signature(DataRequestSource, "DownloadCredential", DataRequestCredential, Http, User, + "LearnStack.SharedKernel.Identifiers.TenantId", Organization), + [ExportBinding + ".Capture"] = Signature(ExportBinding, "Capture", "System.String", User, "LearnStack.SharedKernel.Identifiers.TenantId", Organization), + [ExportBinding + ".CaptureRetained"] = Signature(ExportBinding, "CaptureRetained", "System.String", Http, User, "LearnStack.SharedKernel.Identifiers.TenantId", Organization), [InvitationCredential + "..ctor"] = Signature(InvitationCredential, ".ctor", "System.Void", Http, Feature, "Microsoft.IdentityModel.JsonWebTokens.JsonWebToken", Verified, "System.String"), [InvitationCredential + ".Capture"] = Signature(InvitationCredential, "Capture", InvitationCredential, Http, "Microsoft.IdentityModel.JsonWebTokens.JsonWebToken", Verified), [InvitationCredential + ".get_Subject"] = Signature(InvitationCredential, "get_Subject", Verified), @@ -64,7 +76,8 @@ public sealed partial class AuthenticationAuthorityTests [Native + ".get_Actor"] = Signature(Native, "get_Actor", User), [NativeSource + "..ctor"] = Signature(NativeSource, ".ctor", "System.Void", Http, Host, Verified, Authentication + "SubjectAdmissionDecision", Provenance, Tenant, Organization, Authentication + "GlobalSelfOperation", - "LearnStack.Api.Tenancy.EffectiveHostAccessor", Authentication + "NativeSessionSourcePolicy", "LearnStack.SharedKernel.Time.IClock", Authentication + "InvitationEntryOperation", Authentication + "ConsentSubjectOperation"), + "LearnStack.Api.Tenancy.EffectiveHostAccessor", Authentication + "NativeSessionSourcePolicy", "LearnStack.SharedKernel.Time.IClock", Authentication + "InvitationEntryOperation", Authentication + "ConsentSubjectOperation", + Authentication + "OwnDataRequestOperation"), [NativeSource + ".IsCurrent"] = Signature(NativeSource, "IsCurrent", "System.Boolean", Http), [NativeMiddleware + ".InvokeAsync"] = Signature(NativeMiddleware, "InvokeAsync", TaskType, Http, "LearnStack.Api.Tenancy.EffectiveHostAccessor", Authentication + "NativeSessionSourcePolicy", "LearnStack.SharedKernel.Time.IClock"), @@ -79,7 +92,7 @@ public sealed partial class AuthenticationAuthorityTests [Authentication + "OperationAuthorizationHandler.HandleAsync"] = Signature(Authentication + "OperationAuthorizationHandler", "HandleAsync", TaskType, "Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext"), [CredentialWitness + "..ctor"] = Signature(CredentialWitness, ".ctor", "System.Void", Http, Host, Verified, Identity, - Authentication + "SubjectAdmissionDecision", Provenance, Native, InvitationSource, ConsentSource), + Authentication + "SubjectAdmissionDecision", Provenance, Native, InvitationSource, ConsentSource, DataRequestSource), [CredentialWitness + ".get_Subject"] = Signature(CredentialWitness, "get_Subject", Verified), [CredentialWitness + ".get_Identity"] = Signature(CredentialWitness, "get_Identity", Identity), [Resolver + ".BuildAttemptAsync"] = Signature(Resolver, "BuildAttemptAsync", TaskType + "`1<" + Attempt + ">", Http, Host, ScopeValidator, Membership, Identity), @@ -203,7 +216,8 @@ private static bool HasClosedCredentialWitnessShape(TypeDefinition witness) ["Provenance"] = Provenance, ["Native"] = Native, ["Invitation"] = InvitationSource, - ["Consent"] = ConsentSource + ["Consent"] = ConsentSource, + ["DataRequest"] = DataRequestSource }; return witness.IsSealed && witness.IsNestedPrivate && witness.BaseType.FullName == "System.Object" && !witness.HasInterfaces && !witness.HasEvents && !witness.HasNestedTypes && !witness.HasGenericParameters @@ -259,16 +273,20 @@ private static IEnumerable ProjectionExports(Method method) => meth instruction.OpCode.Code is Code.Box or Code.Stelem_Ref || instruction.OpCode.Code is Code.Stfld or Code.Stsfld && instruction.Operand is FieldReference field && IsOpaqueProjectionArgument(field.FieldType, owner: field.DeclaringType) && !IsClosedExceptionStorage(method, instruction) - && !IsClosedConsentRequestStore(method, instruction) + && !IsClosedConsentRequestStore(method, instruction) && !IsClosedDataRequestRequestStore(method, instruction) || instruction.Operand is MethodReference target && ExportsProjection(target) && !IsClosedWitnessForwarding(method, instruction, target) && !IsClosedUserAgentFormatting(method, instruction, target) && !IsClosedHttpEndpointForwarding(method, instruction, target) && !IsClosedInvitationForwarding(method, instruction, target) && !IsClosedConsentForwarding(method, instruction, target) + && !IsClosedDataRequestForwarding(method, instruction, target) || instruction.OpCode.Code is Code.Stfld or Code.Stsfld && instruction.Operand is FieldReference consentField && consentField.DeclaringType.FullName == ConsentSource && consentField.Name == "_request" - && !IsClosedConsentRequestStore(method, instruction)); + && !IsClosedConsentRequestStore(method, instruction) + || instruction.OpCode.Code is Code.Stfld or Code.Stsfld && instruction.Operand is FieldReference dataRequestField + && dataRequestField.DeclaringType.FullName == DataRequestSource && dataRequestField.Name == "_request" + && !IsClosedDataRequestRequestStore(method, instruction)); // The token is either hashed for the pending-token equality gate or stored in // the request-local credential. No other encoded-token read is admitted here. @@ -456,7 +474,8 @@ private static bool IsClosedHttpEndpointForwarding(Method method, Instruction in var stores = method.Definition.Body.Instructions.Where(i => StoresLocal(i, local)).ToArray(); return stores.Length == 1 && stores[0].Previous?.Operand is MethodReference source && source.FullName is "System.Type LearnStack.Api.Authentication.InvitationEntrySource::get_EffectiveRequestType()" - or "System.Type LearnStack.Api.Authentication.ConsentSubjectSource::get_EffectiveRequestType()"; + or "System.Type LearnStack.Api.Authentication.ConsentSubjectSource::get_EffectiveRequestType()" + or "System.Type LearnStack.Api.Authentication.OwnDataRequestSubjectSource::get_EffectiveRequestType()"; } // Release emits a constrained Object.ToString for the StringValues value. diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs index 60e4ecbe..715c982e 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs @@ -31,6 +31,10 @@ public sealed partial class AuthenticationAuthorityTests private const string InvitationSource = Authentication + "InvitationEntrySource"; private const string ConsentCredential = Authentication + "ValidatedConsentSubjectCredential"; private const string ConsentSource = Authentication + "ConsentSubjectSource"; + private const string DataRequestCredential = Authentication + "ValidatedOwnDataRequestCredential"; + private const string DataRequestSource = Authentication + "OwnDataRequestSubjectSource"; + /// ADR-0107 § 4: the one download-ticket session binding; it reads the validated projection to bind a ticket. + private const string ExportBinding = Authentication + "HttpDataExportSessionBinding"; private const string RecipientReader = Authentication + "CurrentInvitationRecipientReader"; private const string SelfAdmission = Authentication + "HttpIdentitySelfEntryAdmission"; /// ADR-0099 Amendment 6 (S-B): the one reader of the test-record scope flag. @@ -89,7 +93,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) && !IsOperatorTokenProfileRead(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls))) + && !IsClosedRolesAbsenceCheck(call) && !IsOperatorTokenProfileRead(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls) && !IsClosedDataRequestTokenRead(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 @@ -134,12 +138,16 @@ private static SortedSet Offenders(ModuleDefinition[] modules, // Issuer/sub may select a private accounting partition, never permission. // Scope/actor consumption remains explicit even inside the API assembly. - Consumers("Issuer", CandidateSource + ".MatchesIdentity", Native + ".TryMint", RecipientReader + ".Matches", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync"); - Consumers("Subject", CandidateSource + ".MatchesIdentity", Native + ".TryMint", RecipientReader + ".Matches", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync"); + Consumers("Issuer", CandidateSource + ".MatchesIdentity", Native + ".TryMint", RecipientReader + ".Matches", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync", + DataRequestSource + ".PrepareAsync"); + Consumers("Subject", CandidateSource + ".MatchesIdentity", Native + ".TryMint", RecipientReader + ".Matches", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync", + DataRequestSource + ".PrepareAsync"); VerifiedConsumers("Issuer", Limiter + ".AttemptAcquire", BindingResolver + ".ResolveExistingAsync", BindingAdmission + ".InvokeAsync", - CandidateSource + ".MatchesIdentity", Native + ".TryMint", SelfAdmission + ".Allows", SelfAdmission + ".CurrentSubject", SelfAdmission + ".Capture", RecipientReader + ".Matches"); + CandidateSource + ".MatchesIdentity", Native + ".TryMint", SelfAdmission + ".Allows", SelfAdmission + ".CurrentSubject", SelfAdmission + ".Capture", RecipientReader + ".Matches", + ExportBinding + ".Capture", ExportBinding + ".CaptureRetained"); VerifiedConsumers("Subject", Limiter + ".AttemptAcquire", BindingResolver + ".ResolveExistingAsync", BindingAdmission + ".InvokeAsync", - CandidateSource + ".MatchesIdentity", Native + ".TryMint", SelfAdmission + ".Allows", SelfAdmission + ".CurrentSubject", SelfAdmission + ".Capture", RecipientReader + ".Matches", RecipientReader + ".ReadAsync"); + CandidateSource + ".MatchesIdentity", Native + ".TryMint", SelfAdmission + ".Allows", SelfAdmission + ".CurrentSubject", SelfAdmission + ".Capture", RecipientReader + ".Matches", RecipientReader + ".ReadAsync", + ExportBinding + ".Capture", ExportBinding + ".CaptureRetained"); VerifiedConsumers("ClaimedActor", BindingResolver + ".ResolveExistingAsync", CandidateSource + ".MatchesIdentity", Native + ".TryMint", SelfAdmission + ".Allows", SelfAdmission + ".CurrentSubject"); VerifiedConsumers("TenantId", BindingAdmission + ".InvokeAsync", CandidateSource + ".MatchesIdentity", @@ -151,12 +159,14 @@ private static SortedSet Offenders(ModuleDefinition[] modules, "LearnStack.Api.Tenancy.TenantAssertionMiddleware.InvokeAsync", Authentication + "TenantSurfaceAdmissionMiddleware.HasHostAuthority", CandidateSource + ".ForValidatedScope", CandidateSource + ".MatchesIdentity", TransportSource + ".Capture", Native + ".TryMint", Native + ".get_Actor", RecipientReader + ".Matches", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync", - ConsentSource + ".ForInvocation", ConsentSource + ".get_Actor"); + ConsentSource + ".ForInvocation", ConsentSource + ".get_Actor", DataRequestSource + ".PrepareAsync", DataRequestSource + ".ForInvocation", + DataRequestSource + ".get_Actor", DataRequestSource + ".DownloadCredential", ExportBinding + ".Capture", ExportBinding + ".CaptureRetained"); Consumers("TenantId", Resolver + ".BuildAttemptAsync", Resolver + ".InvokeAsync", Authentication + "TenantSurfaceAdmissionMiddleware.HasHostAuthority", CandidateSource + ".ForValidatedScope", CandidateSource + ".MatchesIdentity", - TransportSource + ".MatchesScope", Native + ".TryMint", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync"); + TransportSource + ".MatchesScope", Native + ".TryMint", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync", DataRequestSource + ".PrepareAsync"); Consumers("OrganizationId", Resolver + ".BuildAttemptAsync", Authentication + "TenantSurfaceAdmissionMiddleware.HasHostAuthority", - CandidateSource + ".ForValidatedScope", CandidateSource + ".MatchesIdentity", Native + ".TryMint", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync"); + CandidateSource + ".ForValidatedScope", CandidateSource + ".MatchesIdentity", Native + ".TryMint", InvitationSource + ".PrepareAsync", ConsentSource + ".PrepareAsync", + DataRequestSource + ".PrepareAsync"); foreach (var method in methods) foreach (var instruction in method.Definition.Body.Instructions) diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs index 248843ab..c5d64181 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs @@ -38,6 +38,11 @@ private static readonly (string Controller, string[] Actions)[] JobManifestContr ("LearnStack.Api.Identity.MembershipCustomFieldsController", ["Get", "GetOwn", "Set", "SetOwn"]), ("LearnStack.Api.Tenancy.ConsentSubjectController", ["Scopes", "History", "Withdraw"]), ("LearnStack.Api.Tenancy.OwnFieldConsentController", ["Current", "Grant"]), + ("LearnStack.Api.Identity.OwnDataRequestsController", ["Create", "List", "Get", "Cancel", "Revoke"]), + ("LearnStack.Api.Identity.OwnDataExportTicketsController", ["MintTicket"]), + ("LearnStack.Api.Identity.OwnDataExportChunksController", ["ReadChunk"]), + ("LearnStack.Api.Identity.DataRequestsController", ["Create", "List", "Get", "Cancel", "Revoke"]), + ("LearnStack.Api.Identity.DataRequestEntryController", ["Scopes", "Requests", "CreateExport", "Cancel", "MintTicket", "ReadChunk"]), ("LearnStack.Api.PublicReads.PublicSignInController", ["Get", "Head"]), ("LearnStack.Api.Identity.FederationController", ["Get", "Configure", "RotateSecret", "Rename", "StartTest", "RecordTestResult", "Activate", "Disable", "Enable", "Delete", "Resume"]), diff --git a/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs index 8dfb246f..794752de 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs @@ -38,7 +38,7 @@ public sealed partial class IdempotencyConventionTests typeof(ReadRoleReceiptQuery), typeof(ReadOrganizationReceiptQuery), typeof(ReadDefaultOrganizationReceiptQuery), typeof(ReadInvitationReceiptQuery), typeof(ReadInvitationPolicyReceiptQuery), typeof(ReadCustomFieldDefinitionReceiptQuery), typeof(ReadOwnGrantedFieldConsentReceiptQuery), typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), - typeof(ReadOwnDataRequestReceiptQuery), typeof(ReadDataRequestReceiptQuery), + typeof(ReadOwnDataRequestReceiptQuery), typeof(ReadDataRequestReceiptQuery), typeof(ReadRetainedDataRequestReceiptQuery), ]; [Fact] @@ -52,6 +52,7 @@ public void Protected_Idempotent_Replay_Reauthorizes_Original_Target() catalog.TryGet(receipt, out var policy).Should().BeTrue("Fix: classify every receipt read explicitly"); policy.Kind.Should().Be(receipt == typeof(ReadOwnWithdrawnFieldConsentReceiptQuery) ? OperationPolicyKind.OwnConsentEntry : receipt == typeof(ReadOwnDataRequestReceiptQuery) ? OperationPolicyKind.OwnDataRequest + : receipt == typeof(ReadRetainedDataRequestReceiptQuery) ? OperationPolicyKind.OwnDataRequestEntry : receipt == typeof(ReadOwnMembershipProfileReceiptQuery) || receipt == typeof(ReadInvitationPolicyReceiptQuery) || receipt == typeof(ReadOwnGrantedFieldConsentReceiptQuery) ? OperationPolicyKind.OwnMembershipRead : OperationPolicyKind.Protected); policy.RequiresOrglessWrite.Should().BeFalse("disclosure is not the original mutation's eligibility"); @@ -197,6 +198,11 @@ private static string[] DispatcherOffenders(ModuleDefinition[] modules) && instruction.Operand is TypeReference target && target.FullName == typeof(ReadOwnWithdrawnFieldConsentReceiptQuery).FullName); if (captured) expected.Remove(typeof(ReadOwnWithdrawnFieldConsentReceiptQuery).FullName!); else constructions = [.. constructions, "missing captured withdrawal receipt"]; + // ADR-0106 § 9: so does the retained own-scope entry, whose receipt read is its own witness's captured query. + var retained = method.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Isinst + && instruction.Operand is TypeReference target && target.FullName == typeof(ReadRetainedDataRequestReceiptQuery).FullName); + if (retained) expected.Remove(typeof(ReadRetainedDataRequestReceiptQuery).FullName!); + else constructions = [.. constructions, "missing captured retained data-request receipt"]; return expected.Except(constructions, StringComparer.Ordinal) .Concat(constructions.Except(expected, StringComparer.Ordinal)) .Concat(constructions.GroupBy(name => name, StringComparer.Ordinal).Where(group => group.Count() != 1).Select(group => group.Key)) @@ -234,6 +240,8 @@ private static string[] DispatcherOffenders(ModuleDefinition[] modules) [ProtectedAdministrationOperation.CreateDataExportForSubject] = typeof(ReadDataRequestReceiptQuery), [ProtectedAdministrationOperation.CancelDataRequest] = typeof(ReadDataRequestReceiptQuery), [ProtectedAdministrationOperation.RevokeDataExport] = typeof(ReadDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateRetainedDataExport] = typeof(ReadRetainedDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CancelRetainedDataRequest] = typeof(ReadRetainedDataRequestReceiptQuery), }; private static string[] AdmissionOffenders(ModuleDefinition[] modules) @@ -384,7 +392,14 @@ private static (string File, string Relation)[] AdmissionGuardRelations() => (AdmissionFile, "ReferenceEquals(http, current) && ReferenceEquals(endpoint, current.GetEndpoint()) && ReferenceEquals(context, scope) && !current.RequestAborted.IsCancellationRequested"), (AdmissionFile, "scope.IsResolved && scope.TenantId == _tenant && scope.OrganizationId == _organization && scope.UserId == _actor && scope.Origin == _origin"), (AdmissionFile, "consent is not null ? candidate is null && consent.Actor == _actor && consent.MatchesScope(current, _tenant, _organization) : candidate is { IsActive: true } && candidate.Actor == _actor && candidate.TenantId == _tenant && candidate.OrganizationId == _organization"), - (AdmissionFile, "fingerprint == currentFingerprint && await consent.MatchesCapturedWithdrawalAsync(http) && IdempotencyFilter.TryReadKey(http, out currentKey) && currentKey == key"), + (AdmissionFile, "fingerprint == currentFingerprint && await CapturedInputMatchesAsync() && IdempotencyFilter.TryReadKey(http, out currentKey) && currentKey == key"), + (AdmissionFile, "Task CapturedInputMatchesAsync() => consent is not null ? consent.MatchesCapturedWithdrawalAsync(http) : dataRequest!.MatchesCapturedMutationAsync(http);"), + // ADR-0106 § 9: the retained entry is admitted by its own witness and keeps its captured mutation and scope. + (AdmissionFile, "if (declared.Kind != OperationPolicyKind.OwnDataRequestEntry || context.Origin != TenantContextOrigin.HostAndOwnDataRequestScope || dataRequest is null || dataRequest.Actor != actor || !dataRequest.MatchesScope(http, context.TenantId, context.OrganizationId)"), + (AdmissionFile, "if (dataRequest is not null && !await dataRequest.MatchesCapturedMutationAsync(http)) return Failure(\"lockey_forbidden\");"), + (AdmissionFile, "if (dataRequest is not null && frozen is not null && (frozen.ReplayTarget is not { } retained || !dataRequest.SelectMutationReceipt(http, retained.Id))) return Failure(\"lockey_forbidden\");"), + (AdmissionFile, "dataRequest is not null ? candidate is null && consent is null && dataRequest.Actor == _actor && dataRequest.MatchesScope(current, _tenant, _organization)"), + (FilterFile, "if (_descriptor.Operation == ProtectedAdministrationOperation.WithdrawOwnFieldConsent || _descriptor.IsRetainedDataRequest) { context.Result = Problem(\"lockey_request_in_progress\"); return; }"), (AdmissionFile, "candidate.Actor == _actor && candidate.TenantId == _tenant && candidate.OrganizationId == _organization"), (AdmissionFile, "descriptor == operation && key == currentKey && fingerprint == currentFingerprint && expected == currentExpected"), (AdmissionFile, "classifier.Classify(endpoint, out var currentPolicy) == HttpOperationClassification.Application && ReferenceEquals(policy, currentPolicy)"), diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 68b00737..ebbbaad6 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -34,6 +34,7 @@ public sealed partial class IdentityAuditConventionTests private const string InvitationAuthorization = "LearnStack.Modules.Identity.Application.Invitations.InvitationAdministrationAuthorization"; private const string FederationAuthorization = "LearnStack.Modules.Identity.Application.Federation.FederationAuthorization"; private const string DataRequestAuthorization = "LearnStack.Modules.Identity.Application.DataRequests.DataRequestAuthorization"; + private const string RetainedDataRequestAdmission = "LearnStack.Modules.Identity.Application.DataRequests.RetainedDataRequestAdmission"; private const string InvitationPolicyAuthorization = "LearnStack.Modules.Tenancy.Application.Settings.InvitationPolicyHandlers"; private const string InvitationEntrySource = "LearnStack.Api.Authentication.InvitationEntrySource"; private const string InvitationEntryAuthorization = "LearnStack.Modules.Identity.Application.Invitations.InvitationEntryAuthorization"; @@ -58,6 +59,8 @@ private static readonly (string Owner, string Method, int Count)[] CurrentInvoca [ (CentralEvidence, "Snapshot", 1), ("LearnStack.Api.Authentication.ConsentSubjectSource", "IsEvidenceCurrent", 1), + ("LearnStack.Api.Authentication.OwnDataRequestSubjectSource", "IsEvidenceCurrent", 1), + (RetainedDataRequestAdmission, "For", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.ReadOwnGrantedFieldConsentReceiptQueryHandler", "Handle", 1), ("LearnStack.Modules.Tenancy.Application.FieldConsents.ReadOwnGrantedFieldConsentReceiptQueryHandler", "Matches", 1), ("LearnStack.Modules.Identity.Application.CustomFields.MembershipCustomFieldCommandExecutor", "ExecuteAsync", 1), @@ -135,6 +138,7 @@ private static readonly (string Owner, string Method, int Count)[] CurrentDecisi (InvitationAuthorization, "Matches", 1), (FederationAuthorization, "Matches", 1), (DataRequestAuthorization, "Matches", 1), + (RetainedDataRequestAdmission, "For", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (ReadAuthorization, "Matches", 1), (NavigationReader, "Matches", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.Http.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.Http.cs index 95aabae0..c678b23e 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.Http.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.Http.cs @@ -7,7 +7,15 @@ namespace LearnStack.Tests.Architecture; public sealed partial class OperationPolicyOwnershipTests { private const string ConsentHttpResponse = """ - policy.Kind == OperationPolicyKind.OwnConsentEntry + policy.Kind == OperationPolicyKind.OwnDataRequestEntry + ? http.Features.Get() is { } dataRequest && dataRequest.IsCurrent(http) + && dataRequest.EffectiveRequestType is { } dataRequestType + ? ProtectedAdministrationDescriptor.ForRequest(policy.RequestType) is not null + ? await ProtectedReplayHttpAdmission.AuthorizeAsync(http, policy, classifier, + tenantContext, store, candidates, operations) + : await operations().CheckHttpAsync(dataRequestType, http.GetEndpoint()!, http.RequestAborted) + : LearnStack.SharedKernel.Results.Result.Fail(TenantContextFactory.Refused) + : policy.Kind == OperationPolicyKind.OwnConsentEntry ? http.Features.Get() is { } consent && consent.IsCurrent(http) && consent.EffectiveRequestType is { } consentType ? ProtectedAdministrationDescriptor.ForRequest(policy.RequestType) is not null @@ -36,6 +44,11 @@ private static void AssertConsentHttpAuthorization() ("http.GetEndpoint()!", "new object()"), ("http.RequestAborted", "CancellationToken.None"), ("ProtectedAdministrationDescriptor.ForRequest(policy.RequestType)", "ProtectedAdministrationDescriptor.ForRequest(consentType)"), + // ADR-0106 § 9: the retained data-request entry reaches HTTP only with its own captured current request. + ("dataRequest.IsCurrent(http)", "dataRequest.IsCurrent(new DefaultHttpContext())"), + ("dataRequest.EffectiveRequestType", "policy.RequestType"), + ("CheckHttpAsync(dataRequestType,", "CheckHttpAsync(policy.RequestType,"), + ("policy.Kind == OperationPolicyKind.OwnDataRequestEntry", "policy.Kind == OperationPolicyKind.OwnDataRequest"), }) { var dirty = source.Replace(before, after, StringComparison.Ordinal); @@ -66,7 +79,7 @@ private static bool ConsentHttpAuthorizationIsConfined(string source) var method = type?.Members.OfType().SingleOrDefault(node => node.Identifier.ValueText == "HandleAsync"); var response = method?.DescendantNodes().OfType().SingleOrDefault(node => node.Identifier.ValueText == "response")?.Initializer?.Value; return response is not null && SyntaxFactory.AreEquivalent(response, SyntaxFactory.ParseExpression(ConsentHttpResponse)) - && method!.DescendantNodes().OfType().Count(node => node.Expression.ToString() == "operations().CheckHttpAsync") == 2; + && method!.DescendantNodes().OfType().Count(node => node.Expression.ToString() == "operations().CheckHttpAsync") == 3; } private static bool ReplayHttpAuthorizationCallsAreConfined(string source) diff --git a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs index 45fb05b1..80881085 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.cs @@ -320,7 +320,7 @@ private static List Offenders(Census census) ("LearnStack.Api.Idempotency.ProtectedReplayHttpAdmission", "AuthorizeAsync", 1)]); Exact(Coordinator, "CheckHttpAsync", [("LearnStack.Api.Idempotency.ProtectedReplayHttpAdmission", "AuthorizeAsync", 4), ("LearnStack.Api.Authentication.OperationClassificationMiddleware", "InvokeAsync", 1), - ("LearnStack.Api.Authentication.OperationAuthorizationHandler", "HandleAsync", 2)]); + ("LearnStack.Api.Authentication.OperationAuthorizationHandler", "HandleAsync", 3)]); Exact(Witness, "TryBindTo", [(Unit, "SetTenantContextCoreAsync", 2)]); Exact(Witness, "IsBoundTo", [(Unit, "SetTenantContextCoreAsync", 1), (Unit, "ValidateOperationReadScope", 1)]); Exact(Invocation, "TryBindRead", [(Witness, "TryBindTo", 1)]); diff --git a/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs index 80abaded..3f92bf8a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs @@ -1,6 +1,8 @@ using System.Reflection; using FluentAssertions; +using LearnStack.Api.Authentication; using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application; using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Permissions; @@ -16,24 +18,38 @@ namespace LearnStack.Tests.Architecture; /// /// ADR-0106 § 9: the retained own data-request scope is the consent subject's model applied to data requests. These -/// rules pin its closed owners — the one definer caller, the one physical owner, the witness's private construction -/// and binding callers — and the fact that, until the native retained-entry operations land with their endpoints, -/// nothing mints the witness and no policy carries either new kind. +/// rules pin its closed owners: the one definer caller, the one HTTP source that observes the scope and mints the +/// witness, the one resolver that builds its context, the one physical owner, the witness's private construction and +/// binding callers, the closed set of request types each policy kind admits, and the one source registration. /// public sealed class OwnDataRequestScopeConventionTests { private const string Witness = "LearnStack.SharedKernel.Identity.OwnDataRequestScopeWitness"; private const string Unit = "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork"; private const string Lookup = "LearnStack.Modules.Identity.Infrastructure.Persistence.OwnDataRequestScopeLookup"; + private const string Source = "LearnStack.Api.Authentication.OwnDataRequestSubjectSource"; [Fact] public void Own_data_request_witness_owner_and_lookup_have_closed_shapes() { var types = ProductionAssemblies.All().SelectMany(assembly => assembly.GetTypes()).ToArray(); + var policies = new IdentityOperationPolicySource().Policies; + policies.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequestEntry).Select(policy => policy.RequestType) + .Should().BeEquivalentTo([typeof(ListRetainedDataRequestScopesQuery), typeof(ListRetainedDataRequestsQuery), + typeof(CreateRetainedDataExportCommand), typeof(CancelRetainedDataRequestCommand), typeof(MintRetainedDataExportTicketCommand), + typeof(ReadRetainedDataExportChunkCommand), typeof(ReadRetainedDataRequestReceiptQuery)], + "the retained entry reaches exactly its six operations and the receipt read of its two keyed ones"); + policies.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequest).Select(policy => policy.RequestType) + .Should().BeEquivalentTo([typeof(CreateOwnDataExportCommand), typeof(ListOwnDataRequestsQuery), typeof(GetOwnDataRequestQuery), + typeof(CancelOwnDataRequestCommand), typeof(RevokeOwnDataExportCommand), typeof(MintOwnDataExportTicketCommand), + typeof(ReadOwnDataExportChunkCommand), typeof(ReadOwnDataRequestReceiptQuery)], "the live kind is unchanged and never a retained type"); + policies.Where(policy => policy.Kind is OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry) + .Should().OnlyContain(policy => policy.Alternatives.IsEmpty && policy.RequiredPermission == null, + "neither kind carries an assignable key (ADR-0106 § 4)"); types.Where(type => !type.IsAbstract && typeof(OwnDataRequestScopeWitness.MintingSource).IsAssignableFrom(type)) - .Should().BeEmpty("the HTTP source that captures the verified subject lands with the native retained-entry endpoints"); + .Should().Equal(typeof(OwnDataRequestSubjectSource)); types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestScopeSource).IsAssignableFrom(type)) - .Should().BeEmpty("no source may answer before the minting source exists"); + .Should().Equal(typeof(OwnDataRequestSubjectSource)); types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestUnitOfWork).IsAssignableFrom(type)) .Should().Equal(typeof(NpgsqlUnitOfWork)); types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestScopeLookup).IsAssignableFrom(type)) @@ -63,7 +79,10 @@ string[] Callers(string targetType, string member) => modules.SelectMany(module .SelectMany(method => method.Definition.Body.Instructions.Where(instruction => instruction.Operand is MethodReference target && target.DeclaringType.FullName == targetType && target.Name == member) .Select(_ => type.FullName + "." + method.DeclaredAs))).Distinct().ToArray(); - Callers(Witness + "/MintingSource", "Capture").Should().BeEmpty(); + Callers(Witness + "/MintingSource", "Capture").Should().Equal(Source + ".ForInvocation"); + Callers(Source, "SelectMutationReceipt").Should().Equal("LearnStack.Api.Idempotency.ProtectedReplayHttpAdmission.AuthorizeAsync"); + Callers(Source, "PrepareAsync").Should().Equal("LearnStack.Api.Tenancy.TenantResolverMiddleware.InvokeAsync"); + Callers(Source, "DownloadCredential").Should().Equal("LearnStack.Api.Authentication.HttpDataExportSessionBinding.CaptureRetained"); Callers(Witness, ".ctor").Should().Equal(Witness + "/MintingSource.Capture"); Callers(Witness, "TryBindTo").Should().Equal(Unit + ".SetTenantContextCoreAsync"); Callers(Witness, "IsBoundTo").Should().BeEquivalentTo(Unit + ".SetTenantContextCoreAsync", @@ -71,23 +90,25 @@ string[] Callers(string targetType, string member) => modules.SelectMany(module Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "BeginOwnDataRequestTransactionAsync") .Should().Equal("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteCoreAsync"); Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "IsOwnDataRequestOwner") - .Should().Equal("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteFrameAsync"); + .Should().BeEquivalentTo("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteFrameAsync", + "LearnStack.Modules.Identity.Application.DataRequests.RetainedDataRequestAdmission.For"); Callers("LearnStack.SharedKernel.Tenancy.TenantContextFactory", "CreateForOwnDataRequestScope") - .Should().BeEmpty("only the native retained-entry resolver may build this context, and it lands with its endpoints"); + .Should().Equal(["LearnStack.Api.Tenancy.TenantResolverMiddleware.InvokeAsync"], + "only the native retained-entry resolver builds this context"); Callers("LearnStack.Modules.Identity.Application.Contracts.DataRequests.IOwnDataRequestScopeLookup", "LookupAsync") - .Should().BeEmpty("only the native retained-entry source may observe the retained groups"); + .Should().Equal([Source + ".PrepareAsync"], "only the native retained-entry source observes the retained groups"); var module = modules.Single(item => item.Assembly.Name.Name == "LearnStack.SharedKernel"); var witnessType = module.Types.SelectMany(Flatten).Single(type => type.FullName == Witness); var minter = witnessType.NestedTypes.Single(type => type.Name == "MintingSource"); TypeDefinition[] Minters() => modules.SelectMany(item => item.Types).SelectMany(Flatten) .Where(type => !type.IsAbstract && type.BaseType?.FullName == minter.FullName).ToArray(); - Minters().Should().BeEmpty(); + Minters().Select(type => type.FullName).Should().Equal(Source); var rogueMinter = new TypeDefinition("ReviewProbe", "DataRequestMinter", Mono.Cecil.TypeAttributes.Class, minter); module.Types.Add(rogueMinter); - Minters().Select(type => type.FullName).Should().Equal("ReviewProbe.DataRequestMinter"); + Minters().Select(type => type.FullName).Should().Contain("ReviewProbe.DataRequestMinter").And.HaveCount(2); module.Types.Remove(rogueMinter); - Minters().Should().BeEmpty(); + Minters().Select(type => type.FullName).Should().Equal(Source); var target = witnessType.Methods.Single(method => method.Name == "TryBindTo"); var probe = new TypeDefinition("ReviewProbe", "DataRequestBinding", Mono.Cecil.TypeAttributes.Class, module.TypeSystem.Object); var method = new MethodDefinition("Bind", Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void); @@ -121,6 +142,52 @@ public void Only_the_confined_lookup_calls_the_retained_scope_definer() "the one statement reads the function's two result columns and nothing else"); } + /// + /// The source's request feature is the very request it captured: a replaced feature, a different captured request or a + /// receipt selection outside a keyed purpose must not retain authority (the consent subject's rule). + /// + [Fact] + public void Retained_entry_request_feature_is_bound_to_the_captured_request() + { + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs")); + RequestFeatureIsBound(source).Should().BeTrue(); + foreach (var (before, after) in new[] + { + ("ReferenceEquals(http.Features.Get(), _requestFeature)", "true"), + ("ReferenceEquals(_requestFeature.Request, _request)", "true"), + ("_native.DataRequestOperation == _purpose", "true"), + ("_purpose?.Purpose is not (OwnDataRequestPurpose.Create or OwnDataRequestPurpose.Cancel)", "false"), + ("_request is not (CreateRetainedDataExportCommand or CancelRetainedDataRequestCommand)", "false"), + ("_requestFeature = new OwnDataRequestEntryRequest(receipt);", "_requestFeature = null;"), + ("http.Features.Set(_requestFeature);\n return true;", "GC.KeepAlive(http);\n return true;"), + }) + { + var dirty = source.Replace(before, after, StringComparison.Ordinal); + dirty.Should().NotBe(source, before); + RequestFeatureIsBound(dirty).Should().BeFalse("a replacement feature or different captured request must not retain authority"); + } + } + + private static bool RequestFeatureIsBound(string source) + { + var root = CSharpSyntaxTree.ParseText(source).GetRoot(); + if (root.ContainsDiagnostics) return false; + var owner = root.DescendantNodes().OfType().SingleOrDefault(type => type.Identifier.ValueText == "OwnDataRequestSubjectSource"); + var current = owner?.Members.OfType().SingleOrDefault(method => method.Identifier.ValueText == "IsCurrent"); + var select = owner?.Members.OfType().SingleOrDefault(method => method.Identifier.ValueText == "SelectMutationReceipt"); + var prepare = owner?.Members.OfType().SingleOrDefault(method => method.Identifier.ValueText == "PrepareAsync"); + if (current is null || select is null || prepare is null) return false; + static string Tokens(Microsoft.CodeAnalysis.SyntaxNode node) => string.Concat(node.DescendantTokens().Select(token => token.Text)); + var live = Tokens(current); var replay = Tokens(select); var initial = Tokens(prepare); + return live.Contains("ReferenceEquals(http.Features.Get(),_requestFeature)", StringComparison.Ordinal) + && live.Contains("ReferenceEquals(_requestFeature.Request,_request)", StringComparison.Ordinal) + && live.Contains("_native.DataRequestOperation==_purpose", StringComparison.Ordinal) + && replay.Contains("!IsCurrent(http)||_purpose?.Purposeisnot(OwnDataRequestPurpose.CreateorOwnDataRequestPurpose.Cancel)", StringComparison.Ordinal) + && replay.Contains("_requestisnot(CreateRetainedDataExportCommandorCancelRetainedDataRequestCommand)", StringComparison.Ordinal) + && replay.Contains("_requestFeature=newOwnDataRequestEntryRequest(receipt);http.Features.Set(_requestFeature);returntrue;", StringComparison.Ordinal) + && initial.Contains("_requestFeature=newOwnDataRequestEntryRequest(input.Request);http.Features.Set(_requestFeature);http.Features.Set(this);", StringComparison.Ordinal); + } + [Fact] public void Retained_scope_lookup_is_scoped_in_the_api_composition_and_nowhere_else() { @@ -139,6 +206,17 @@ static string[] Registrations(string source) => CSharpSyntaxTree.ParseText(sourc Registrations(dirty).Should().HaveCount(2, "an extra witness source must remain visible to the registration census"); var seeder = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Tools.Seeder/SeedComposition.cs")); Registrations(seeder).Should().BeEmpty("the seeder dispatches no data request"); + var live = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs")); + Registrations(live).Should().Equal(["TryAddScoped"], + "the one witness source is the scoped HTTP source, aliased once"); + // The registration census over every production file: exactly one IOwnDataRequestScopeSource registration. + var everywhere = Directory.EnumerateFiles(SourceScan.SourceRoot, "*.cs", SearchOption.AllDirectories) + .Where(path => !path.Contains("/obj/", StringComparison.Ordinal) && !path.Contains("/bin/", StringComparison.Ordinal)) + .SelectMany(path => Registrations(File.ReadAllText(path))).Where(item => item.Contains("IOwnDataRequestScopeSource", StringComparison.Ordinal)) + .ToArray(); + everywhere.Should().Equal(["TryAddScoped"]); + Registrations(live + "\nclass Rogue { void Add(dynamic services) { services.AddScoped(); } }") + .Should().HaveCount(2, "a second witness source must remain visible to the registration census"); } private static IEnumerable Flatten(TypeDefinition type) => new[] { type }.Concat(type.NestedTypes.SelectMany(Flatten)); diff --git a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs index 74249e03..9cc1677b 100644 --- a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs @@ -30,6 +30,95 @@ private sealed record DataRequestOperation(string Path, string Method, string Id new("/api/v1/identity/data-requests/{id}/artifact/revocations", "post", "RevokeDataExport", DataRequestShape.Mutation, "AdministrationVersionReceipt", "EmptyAdministrationInput"), ]; + // ADR-0106 § 9: the retained own-scope native entry. Both credentials on one requirement, a required group on every + // purpose but discovery, a key only on creation and cancellation, If-Match only on cancellation, and no Location. + private static readonly DataRequestOperation[] RetainedDataRequestOperations = + [ + new("/api/v1/identity/data-request-entry/scopes", "get", "ListRetainedDataRequestScopes", DataRequestShape.Read, "RetainedDataRequestScopePageResponse", null), + new("/api/v1/identity/data-request-entry/requests", "get", "ListRetainedDataRequests", DataRequestShape.Read, "OwnDataRequestPage", null), + new("/api/v1/identity/data-request-entry/exports", "post", "CreateRetainedDataExport", DataRequestShape.Create, "DataRequestAcceptedResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/data-request-entry/cancellations", "post", "CancelRetainedDataRequest", DataRequestShape.Mutation, "AdministrationVersionReceipt", "RetainedDataRequestTargetInput"), + new("/api/v1/identity/data-request-entry/tickets", "post", "MintRetainedDataExportTicket", DataRequestShape.Ticket, "DataExportTicketResponse", "RetainedDataRequestTargetInput"), + new("/api/v1/identity/data-request-entry/chunks", "post", "ReadRetainedDataExportChunk", DataRequestShape.Ticket, "DataExportChunkResponse", "RetainedDataExportChunkInput"), + ]; + + private static readonly string[] RetainedDataRequestSchemaNames = + ["RetainedDataRequestScopeResponse", "RetainedDataRequestScopePageResponse", "RetainedDataRequestTargetInput", "RetainedDataExportChunkInput"]; + + private static List RetainedDataRequestContractErrors(JsonNode document) + { + var errors = new List(); + foreach (var contract in RetainedDataRequestOperations) + { + if (document["paths"]?[contract.Path] is not JsonObject item || item.Count != 1 + || item[contract.Method] is not JsonObject operation) { errors.Add("retained-data-request-operations"); continue; } + if (operation["operationId"]?.GetValue() != contract.Id) errors.Add("retained-data-request-operations"); + if (operation["security"] is not JsonArray { Count: 1 } security || security[0] is not JsonObject { Count: 2 } requirement + || requirement["TenantBearer"] is not JsonArray { Count: 0 } || requirement["NativeSessionSource"] is not JsonArray { Count: 0 }) + errors.Add("retained-data-request-security:" + contract.Id); + var parameters = (operation["parameters"]?.AsArray() ?? []).Select(parameter => parameter!["name"]!.GetValue()).ToArray(); + var expected = new List(); + var discovery = contract.Id == "ListRetainedDataRequestScopes"; + if (!discovery) expected.Add("group"); + if (contract.Shape == DataRequestShape.Read) expected.AddRange(["cursor", "limit"]); + if (contract.Shape is DataRequestShape.Create or DataRequestShape.Mutation) expected.Add("Idempotency-Key"); + if (contract.Shape == DataRequestShape.Mutation) expected.Add("If-Match"); + if (!parameters.Order(StringComparer.Ordinal).SequenceEqual(expected.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + errors.Add("retained-data-request-parameters:" + contract.Id); + if (parameters.Any(name => name.Contains("ticket", StringComparison.OrdinalIgnoreCase) || name.StartsWith("X-LearnStack", StringComparison.Ordinal))) + errors.Add("retained-data-request-parameter-leak:" + contract.Id); + if ((contract.Body is null) != (operation["requestBody"] is null) + || contract.Body is not null && operation["requestBody"]?["content"]?["application/json"]?["schema"]?["$ref"]?.GetValue() + != "#/components/schemas/" + contract.Body) errors.Add("retained-data-request-body:" + contract.Id); + var status = contract.Shape == DataRequestShape.Create ? "202" : "200"; + var responses = operation["responses"]!.AsObject(); + if (responses[status]?["content"]?["application/json"]?["schema"]?["$ref"]?.GetValue() != "#/components/schemas/" + contract.Response + || responses.Any(response => response.Key is "200" or "201" or "202" && response.Key != status)) + errors.Add("retained-data-request-success:" + contract.Id); + foreach (var (_, response) in responses) + if (response?["headers"]?["Cache-Control"]?["schema"]?["enum"]?[0]?.GetValue() != "no-store") + errors.Add("retained-data-request-no-store:" + contract.Id); + if ((contract.Shape is DataRequestShape.Create or DataRequestShape.Mutation) != (responses[status]?["headers"]?["ETag"] is not null)) + errors.Add("retained-data-request-etag:" + contract.Id); + if (responses[status]?["headers"]?["Location"] is not null) errors.Add("retained-data-request-location:" + contract.Id); + } + foreach (var name in RetainedDataRequestSchemaNames) + if (document["components"]?["schemas"]?[name] is not JsonObject schema || schema["additionalProperties"]?.GetValue() != false) + errors.Add("retained-data-request-schema:" + name); + return errors; + } + + [Fact] + public async Task Retained_data_request_census_refuses_a_lost_native_credential_group_or_precondition_and_a_location() + { + var clean = await Served(); + RetainedDataRequestContractErrors(clean).Should().BeEmpty(); + + var bearerOnly = clean.DeepClone(); + bearerOnly["paths"]!["/api/v1/identity/data-request-entry/requests"]!["get"]!["security"]![0]!.AsObject().Remove("NativeSessionSource"); + RetainedDataRequestContractErrors(bearerOnly).Should().Contain("retained-data-request-security:ListRetainedDataRequests"); + + var groupless = clean.DeepClone(); + var tickets = groupless["paths"]!["/api/v1/identity/data-request-entry/tickets"]!["post"]!["parameters"]!.AsArray(); + tickets.Remove(tickets.Single(parameter => parameter!["name"]!.GetValue() == "group")); + RetainedDataRequestContractErrors(groupless).Should().Contain("retained-data-request-parameters:MintRetainedDataExportTicket"); + + var selector = clean.DeepClone(); + selector["paths"]!["/api/v1/identity/data-request-entry/chunks"]!["post"]!["parameters"]!.AsArray() + .Add(new JsonObject { ["name"] = "X-LearnStack-Native-Tenant-Id", ["in"] = "header" }); + RetainedDataRequestContractErrors(selector).Should().Contain("retained-data-request-parameter-leak:ReadRetainedDataExportChunk"); + + var unconditional = clean.DeepClone(); + var cancel = unconditional["paths"]!["/api/v1/identity/data-request-entry/cancellations"]!["post"]!["parameters"]!.AsArray(); + cancel.Remove(cancel.Single(parameter => parameter!["name"]!.GetValue() == "If-Match")); + RetainedDataRequestContractErrors(unconditional).Should().Contain("retained-data-request-parameters:CancelRetainedDataRequest"); + + var located = clean.DeepClone(); + located["paths"]!["/api/v1/identity/data-request-entry/exports"]!["post"]!["responses"]!["202"]!["headers"]!.AsObject() + .Add("Location", new JsonObject { ["required"] = true }); + RetainedDataRequestContractErrors(located).Should().Contain("retained-data-request-location:CreateRetainedDataExport"); + } + private static readonly string[] DataRequestSchemaNames = [ "DataRequestAcceptedResponse", "DataRequestRetainedResponse", "DataExportTruncationResponse", "DataExportArtifactResponse", diff --git a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs index 3ae84c9a..82eb6265 100644 --- a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs @@ -182,13 +182,14 @@ private static List ContractErrors(JsonNode document) var errors = new List(); var paths = document["paths"]!.AsObject(); if (!paths.Select(path => path.Key).ToHashSet(StringComparer.Ordinal) - .SetEquals(Operations.Keys.Concat(NativeOperations.Keys).Concat(InvitationEntryOperations.Keys).Concat(AdministrationOperations.Select(operation => operation.Path)).Concat(CustomFieldOperations.Select(operation => operation.Path)).Concat(FederationOperations.Select(operation => operation.Path)).Concat(DataRequestOperations.Select(operation => operation.Path)))) errors.Add("operations"); + .SetEquals(Operations.Keys.Concat(NativeOperations.Keys).Concat(InvitationEntryOperations.Keys).Concat(AdministrationOperations.Select(operation => operation.Path)).Concat(CustomFieldOperations.Select(operation => operation.Path)).Concat(FederationOperations.Select(operation => operation.Path)).Concat(DataRequestOperations.Select(operation => operation.Path)).Concat(RetainedDataRequestOperations.Select(operation => operation.Path)))) errors.Add("operations"); errors.AddRange(NativeContractErrors(document)); errors.AddRange(InvitationEntryContractErrors(document)); errors.AddRange(AdministrationContractErrors(document)); errors.AddRange(CustomFieldContractErrors(document)); errors.AddRange(FederationContractErrors(document)); errors.AddRange(DataRequestContractErrors(document)); + errors.AddRange(RetainedDataRequestContractErrors(document)); var count = 0; foreach (var (path, ids) in Operations) { @@ -372,7 +373,7 @@ private static List SchemaErrors(JsonNode document) .SetEquals(expectedNames.Concat(AccountSchemaNames).Concat(DirectorySchemaNames) .Concat(["IdentitySelfActive", "IdentitySelfMissing", "IdentitySelfState", "NativeSessionScopeAdmission", "SelfContextItem", "SelfContextPage"]) .Concat(AdministrationSchemas.Keys).Concat(InvitationEntrySchemas.Keys).Concat(CustomFieldSchemaNames).Concat(FederationSchemaNames) - .Concat(DataRequestSchemaNames).Append("AdministrationGrantResponse"))) errors.Add("schema-census"); + .Concat(DataRequestSchemaNames).Concat(RetainedDataRequestSchemaNames).Append("AdministrationGrantResponse"))) errors.Add("schema-census"); errors.AddRange(AdministrationSchemaErrors(document)); errors.AddRange(CustomFieldSchemaErrors(document)); foreach (var (name, descriptor) in Dtos) diff --git a/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs b/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs index ca03454b..b25c8e0b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Api/OperationHttpClassificationTests.cs @@ -133,6 +133,13 @@ private sealed record ExpectedAction(Type Controller, string Action, string Name new(typeof(DataRequestsController), "Get", "GetDataRequest", "GET", "identity/data-requests/{id}", typeof(GetDataRequestQuery), "identity.data_request.read"), new(typeof(DataRequestsController), "Cancel", "CancelDataRequest", "POST", "identity/data-requests/{id}/cancellations", typeof(CancelDataRequestCommand), "identity.data_request.cancel", Protected: ProtectedAdministrationOperation.CancelDataRequest), new(typeof(DataRequestsController), "Revoke", "RevokeDataExport", "POST", "identity/data-requests/{id}/artifact/revocations", typeof(RevokeDataExportCommand), "identity.data_request.revoke_export", Protected: ProtectedAdministrationOperation.RevokeDataExport), + // ADR-0106 § 9: the retained own-scope native entry. + new(typeof(DataRequestEntryController), "Scopes", "ListRetainedDataRequestScopes", "GET", "identity/data-request-entry/scopes", typeof(ListRetainedDataRequestScopesQuery), "identity.data_request.list_retained_scopes"), + new(typeof(DataRequestEntryController), "Requests", "ListRetainedDataRequests", "GET", "identity/data-request-entry/requests", typeof(ListRetainedDataRequestsQuery), "identity.data_request.list_retained"), + new(typeof(DataRequestEntryController), "CreateExport", "CreateRetainedDataExport", "POST", "identity/data-request-entry/exports", typeof(CreateRetainedDataExportCommand), "identity.data_request.create_retained_export", Protected: ProtectedAdministrationOperation.CreateRetainedDataExport), + new(typeof(DataRequestEntryController), "Cancel", "CancelRetainedDataRequest", "POST", "identity/data-request-entry/cancellations", typeof(CancelRetainedDataRequestCommand), "identity.data_request.cancel_retained", Protected: ProtectedAdministrationOperation.CancelRetainedDataRequest), + new(typeof(DataRequestEntryController), "MintTicket", "MintRetainedDataExportTicket", "POST", "identity/data-request-entry/tickets", typeof(MintRetainedDataExportTicketCommand), "identity.data_request.mint_retained_export_ticket"), + new(typeof(DataRequestEntryController), "ReadChunk", "ReadRetainedDataExportChunk", "POST", "identity/data-request-entry/chunks", typeof(ReadRetainedDataExportChunkCommand), "identity.data_request.read_retained_export_chunk"), ]; [Fact] @@ -174,10 +181,10 @@ public async Task Every_actual_built_controller_and_infrastructure_endpoint_has_ var endpoints = Endpoints(app); var catalog = Catalog(); var classifier = new OperationHttpClassifier(catalog); - Assert.Equal(84, ExpectedActions.Length); - Assert.Equal(29, ExpectedActions.Count(expected => expected.Protected is not null)); + Assert.Equal(90, ExpectedActions.Length); + Assert.Equal(31, ExpectedActions.Count(expected => expected.Protected is not null)); var actualActions = endpoints.Where(endpoint => endpoint.Metadata.GetMetadata() is not null).ToArray(); - Assert.Equal(84, actualActions.Length); + Assert.Equal(90, actualActions.Length); Assert.Equal(ExpectedActions.Select(expected => expected.Name).Order(StringComparer.Ordinal), actualActions .Select(endpoint => endpoint.Metadata.GetRequiredMetadata().EndpointName).Order(StringComparer.Ordinal)); foreach (var endpoint in endpoints) @@ -314,7 +321,7 @@ public async Task Actual_protected_MVC_metadata_twins_require_the_same_declared_ var endpoints = Endpoints(app); var classifier = new OperationHttpClassifier(Catalog()); var protectedActions = ExpectedActions.Where(expected => expected.Protected is not null).ToArray(); - Assert.Equal(29, protectedActions.Length); + Assert.Equal(31, protectedActions.Length); foreach (var expected in protectedActions) { var original = Assert.Single(endpoints, endpoint => endpoint.Metadata.GetMetadata()?.EndpointName == expected.Name); @@ -343,7 +350,7 @@ public async Task Actual_protected_MVC_metadata_twins_require_the_same_declared_ Assert.Equal(HttpOperationClassification.Application, classifier.Classify(original, out _)); } var unkeyedActions = ExpectedActions.Where(expected => expected.Protected is null).ToArray(); - Assert.Equal(55, unkeyedActions.Length); + Assert.Equal(59, unkeyedActions.Length); foreach (var expected in unkeyedActions) { var original = Assert.Single(endpoints, endpoint => endpoint.Metadata.GetMetadata()?.EndpointName == expected.Name); diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs index 93ed7413..8b8c4188 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs @@ -52,7 +52,8 @@ private static void AssertActionFilters(ControllerActionDescriptor action) { Status = approved.Protected is ProtectedAdministrationOperation.CreateOrganization or ProtectedAdministrationOperation.CreateInvitation or ProtectedAdministrationOperation.RegisterCustomFieldDefinition ? 201 - : approved.Protected is ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CreateDataExportForSubject ? 202 : 200, + : approved.Protected is ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CreateDataExportForSubject + or ProtectedAdministrationOperation.CreateRetainedDataExport ? 202 : 200, ResponseType = response }); actual.Should().Equal(expected, "Fix: preserve the exact effective action filters, factories, ordering and declared response metadata"); diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs index 753c6276..572515a9 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.cs @@ -129,6 +129,13 @@ private sealed record SurfaceAction(string Path, string Verb, Type Controller, s new("identity/data-requests/{id}", "GET", typeof(DataRequestsController), "Get", typeof(GetDataRequestQuery), typeof(DataRequestResponse), "identity.data_request.read"), new("identity/data-requests/{id}/cancellations", "POST", typeof(DataRequestsController), "Cancel", typeof(CancelDataRequestCommand), typeof(AdministrationVersionReceipt), "identity.data_request.cancel", ProtectedAdministrationOperation.CancelDataRequest), new("identity/data-requests/{id}/artifact/revocations", "POST", typeof(DataRequestsController), "Revoke", typeof(RevokeDataExportCommand), typeof(AdministrationVersionReceipt), "identity.data_request.revoke_export", ProtectedAdministrationOperation.RevokeDataExport), + // ADR-0106 § 9: the retained own-scope native entry; each action sends the source's captured request. + new("identity/data-request-entry/scopes", "GET", typeof(DataRequestEntryController), "Scopes", typeof(ListRetainedDataRequestScopesQuery), typeof(RetainedDataRequestScopePageResponse), "identity.data_request.list_retained_scopes"), + new("identity/data-request-entry/requests", "GET", typeof(DataRequestEntryController), "Requests", typeof(ListRetainedDataRequestsQuery), typeof(OwnDataRequestPage), "identity.data_request.list_retained"), + new("identity/data-request-entry/exports", "POST", typeof(DataRequestEntryController), "CreateExport", typeof(CreateRetainedDataExportCommand), typeof(DataRequestAcceptedResponse), "identity.data_request.create_retained_export", ProtectedAdministrationOperation.CreateRetainedDataExport), + new("identity/data-request-entry/cancellations", "POST", typeof(DataRequestEntryController), "Cancel", typeof(CancelRetainedDataRequestCommand), typeof(AdministrationVersionReceipt), "identity.data_request.cancel_retained", ProtectedAdministrationOperation.CancelRetainedDataRequest), + new("identity/data-request-entry/tickets", "POST", typeof(DataRequestEntryController), "MintTicket", typeof(MintRetainedDataExportTicketCommand), typeof(DataExportTicketResponse), "identity.data_request.mint_retained_export_ticket"), + new("identity/data-request-entry/chunks", "POST", typeof(DataRequestEntryController), "ReadChunk", typeof(ReadRetainedDataExportChunkCommand), typeof(DataExportChunkResponse), "identity.data_request.read_retained_export_chunk"), new("public/sign-in", "GET", typeof(PublicSignInController), "Get", typeof(GetPublicSignInQuery), typeof(PublicSignIn)), new("public/sign-in", "HEAD", typeof(PublicSignInController), "Head", typeof(GetPublicSignInQuery), typeof(void)), // ADR-0099: the federation controller holds only FederationOperationRunner; the census observes the runner's sends. @@ -146,7 +153,7 @@ private sealed record SurfaceAction(string Path, string Verb, Type Controller, s ]; private static readonly Type[] ContextControllers = [typeof(MembershipsController), typeof(OwnMembershipController), typeof(RolesController), typeof(OrganizationsController), typeof(DefaultOrganizationController), typeof(InvitationsController), typeof(InvitationPolicyController), typeof(MembershipCustomFieldsController), typeof(ConsentSubjectController), typeof(OwnFieldConsentController), - typeof(OwnDataRequestsController), typeof(DataRequestsController)]; + typeof(OwnDataRequestsController), typeof(DataRequestsController), typeof(DataRequestEntryController)]; private const string CensusTarget = "018f4d40-0000-7000-8000-000000000011"; private static SurfaceAction Approved(ControllerActionDescriptor action) => ApprovedActions.Single(expected => @@ -330,7 +337,7 @@ private static void AssertEndpointAuthorization(ControllerActionDescriptor actio private static void AssertActionInventory(IEnumerable actions) { var actual = actions.ToArray(); - actual.Should().HaveCount(84); + actual.Should().HaveCount(90); actual.Select(action => action.ControllerTypeInfo.FullName + "." + action.MethodInfo.Name).Order(StringComparer.Ordinal) .Should().Equal(ApprovedActions.Select(expected => expected.Controller.FullName + "." + expected.Action).Order(StringComparer.Ordinal), "every convention must reach exactly the approved controller/action multiset"); @@ -448,6 +455,21 @@ private static async Task DispatchedRequest(ControllerActionDescriptor act }; context.Features.Set(new LearnStack.Api.Authentication.InvitationEntryRequest(request)); } + if (controllerType == typeof(DataRequestEntryController)) + { + var organization = LearnStack.SharedKernel.Identifiers.OrganizationId.From(Guid.Parse(CensusTarget)); + object request = expected.Action switch + { + "Scopes" => new ListRetainedDataRequestScopesQuery(null, 20), + "Requests" => new ListRetainedDataRequestsQuery(organization, null, 20), + "CreateExport" => new CreateRetainedDataExportCommand(organization), + "Cancel" => new CancelRetainedDataRequestCommand(organization, Guid.Parse(CensusTarget), 7), + "MintTicket" => new MintRetainedDataExportTicketCommand(organization, Guid.Parse(CensusTarget)), + "ReadChunk" => new ReadRetainedDataExportChunkCommand(organization, Guid.Parse(CensusTarget), new string('A', 43), 0), + _ => throw new InvalidOperationException("Unclassified retained data-request entry action"), + }; + context.Features.Set(new LearnStack.Api.Authentication.OwnDataRequestEntryRequest(request)); + } if (controllerType == typeof(ConsentSubjectController)) { object request = expected.Action switch @@ -482,7 +504,8 @@ private static async Task DispatchedRequest(ControllerActionDescriptor act if (expected.Protected is not (ProtectedAdministrationOperation.CreateOrganization or ProtectedAdministrationOperation.CreateInvitation or ProtectedAdministrationOperation.RegisterCustomFieldDefinition or ProtectedAdministrationOperation.GrantOwnFieldConsent or ProtectedAdministrationOperation.WithdrawOwnFieldConsent or ProtectedAdministrationOperation.CreateOwnDataExport - or ProtectedAdministrationOperation.CreateDataExportForSubject)) context.Request.Headers.IfMatch = "\"7\""; + or ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateRetainedDataExport)) + context.Request.Headers.IfMatch = "\"7\""; } // Federation mutations carry no Idempotency-Key; the connection revision converges them. Configure without // If-Match is the first configuration, the strictest closed input. @@ -590,7 +613,8 @@ public Task GetLimitAsync(LearnStack.SharedKernel.Entitlements.LimitKey ke ProtectedAdministrationOperation.WithdrawOwnFieldConsent => "{}", ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CancelOwnDataRequest or ProtectedAdministrationOperation.RevokeOwnDataExport or ProtectedAdministrationOperation.CancelDataRequest - or ProtectedAdministrationOperation.RevokeDataExport => "{}", + or ProtectedAdministrationOperation.RevokeDataExport or ProtectedAdministrationOperation.CreateRetainedDataExport => "{}", + ProtectedAdministrationOperation.CancelRetainedDataRequest => "{\"requestId\":\"" + CensusTarget + "\"}", ProtectedAdministrationOperation.CreateDataExportForSubject => "{\"membershipId\":\"" + CensusTarget + "\"}", _ => throw new InvalidOperationException("Unclassified protected census input"), }; @@ -607,8 +631,8 @@ private sealed class CensusTenantContext : ITenantContext private static void AssertUnion(IEnumerable actual) { - ApprovedActions.Should().HaveCount(84); - ApprovedActions.Count(expected => expected.Protected is not null).Should().Be(29); + ApprovedActions.Should().HaveCount(90); + ApprovedActions.Count(expected => expected.Protected is not null).Should().Be(31); ApprovedActions.Count(expected => expected.Controller == typeof(FederationController)).Should().Be(11); ApprovedActions.Count(expected => expected.Policy is null).Should().Be(10, "eight public site and course reads plus the sign-in GET and HEAD"); ApprovedActions.Where(expected => expected.Reads is not null).Select(expected => expected.Action) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs new file mode 100644 index 00000000..ad5d9927 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs @@ -0,0 +1,401 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.Api.Tenancy; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Serilog.Core; +using Serilog.Events; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0106 § 9 and ADR-0107 § 4 through the actual Program, signed provider tokens, the native session source and real +/// PostgreSQL as learnstack_app: the retained own-scope native entry of data requests for a Suspended person, a +/// person whose only Membership is Revoked and a person in several groups, with its closed-set and isolation refusals. +/// +public sealed partial class DataRequestHttpTests +{ + private const string EntryPath = "/api/v1/identity/data-request-entry"; + private const string RetainedHop = "data-request-entry-proof-public-hop-separate-purpose"; + private static readonly string RetainedNative = TenantAuthenticationIssuer.Base64Url(Enumerable.Range(81, 32).Select(value => (byte)value).ToArray()); + private static Guid LearnerMembershipId => SeedData.IdentityMemberships[1].MembershipId; + + [Fact] + public async Task A_suspended_person_lists_files_cancels_and_downloads_through_the_retained_entry_only() + { + await using var proof = await CreatePreparedAsync(); + var logs = new RetainedLogCapture(); + using var client = RetainedClient(proof, logs); + var tenant = English.TenantId.Value; + var live = proof.Token(EnglishLearner, English); + var native = NativeToken(proof, EnglishLearner); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + + // A Suspended person has no live data-request authority at all. + using (var refused = await SendAsync(client, live, OwnPath)) + await ProblemAsync(refused, HttpStatusCode.NotFound, "not_found"); + + // Discovery: the tenant-wide group on the real host, nothing else. + using (var scopes = await EntrySendAsync(client, native, "/scopes")) + { + var page = await JsonAsync(scopes); + page.GetProperty("items").EnumerateArray().Select(item => (item.GetProperty("tenantId").GetString(), + item.GetProperty("organizationId").ValueKind)).Should().Equal((tenant.ToString("D"), JsonValueKind.Null)); + page.GetProperty("pageInfo").GetProperty("hasNext").GetBoolean().Should().BeFalse(); + } + + using (var empty = await EntrySendAsync(client, native, "/requests?group=tenant")) + (await JsonAsync(empty)).GetProperty("items").GetArrayLength().Should().Be(0); + + // Creation is keyed and answers 202 with the resource and its ETag, and no Location; an exact replay files nothing. + var key = Key(); + var (cancelled, version) = await EntryFileAsync(client, native, key); + using (var replay = await EntrySendAsync(client, native, "/exports?group=tenant", "{}", key)) + { + (await JsonAsync(replay, HttpStatusCode.Accepted)).GetProperty("id").GetString().Should().Be(cancelled.ToString("D")); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location.Should().BeNull(); + } + + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_export", cancelled.ToString("D"))).Should().Be(1); + + // Cancellation is conditional: a missing precondition is 400, a stale one 409, the current one cancels. + var target = JsonSerializer.Serialize(new { requestId = cancelled }); + using (var unconditional = await EntrySendAsync(client, native, "/cancellations?group=tenant", target, Key())) + await ProblemAsync(unconditional, HttpStatusCode.BadRequest, "validation_failed"); + using (var stale = await EntrySendAsync(client, native, "/cancellations?group=tenant", target, Key(), "\"" + (Number(version) + 1) + "\"")) + await ProblemAsync(stale, HttpStatusCode.Conflict, "concurrency_conflict"); + var cancelKey = Key(); + string after; + using (var cancel = await EntrySendAsync(client, native, "/cancellations?group=tenant", target, cancelKey, "\"" + version + "\"")) + { + after = Version(await JsonAsync(cancel)); + cancel.Headers.ETag!.Tag.Should().Be("\"" + after + "\""); + } + + using (var cancelReplay = await EntrySendAsync(client, native, "/cancellations?group=tenant", target, cancelKey, "\"" + version + "\"")) + { + Version(await JsonAsync(cancelReplay)).Should().Be(after); + cancelReplay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + } + + (await AuditCountAsync(proof, tenant, null, "identity.data_request.cancel", cancelled.ToString("D"))).Should().Be(1); + + // A new export runs, and its artifact downloads through the retained entry with its MUST rows. + var (exported, _) = await EntryFileAsync(client, native, Key()); + await RunExportAsync(proof, tenant, null, exported); + using (var list = await EntrySendAsync(client, native, "/requests?group=tenant")) + { + var items = (await JsonAsync(list)).GetProperty("items").EnumerateArray().ToArray(); + items.Select(item => item.GetProperty("id").GetString()).Should().Equal(exported.ToString("D"), cancelled.ToString("D")); + items[0].GetProperty("status").GetString().Should().Be("completed"); + items[0].GetProperty("artifact").GetProperty("readable").GetBoolean().Should().BeTrue(); + items[1].GetProperty("status").GetString().Should().Be("cancelled"); + items[0].TryGetProperty("membershipIds", out _).Should().BeFalse(); + } + + var (ticket, bundle, chunks) = await EntryDownloadAsync(client, native, exported); + using (var document = JsonDocument.Parse(bundle)) + document.RootElement.GetProperty("request").GetProperty("id").GetString().Should().Be(exported.ToString("D")); + (await AuditCountAsync(proof, tenant, null, "identity.data_export.mint_ticket")).Should().Be(1); + (await AuditCountAsync(proof, tenant, null, "identity.data_export.read_chunk")).Should().Be(chunks); + using (var consumed = await EntryChunkAsync(client, native, exported, ticket, 0)) + await ProblemAsync(consumed, HttpStatusCode.NotFound, "not_found"); + + // Nothing secret reached a log or an idempotency receipt. + var rendered = string.Join('\n', logs.Entries.Select(entry => entry.RenderMessage(System.Globalization.CultureInfo.InvariantCulture) + " " + + string.Join(' ', entry.Properties.Select(property => property.Key + "=" + property.Value)))); + rendered.Should().NotContain(ticket); + rendered.Should().NotContain(Convert.ToBase64String(bundle.AsSpan(0, Math.Min(bundle.Length, 48)))); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.idempotency_keys WHERE convert_from(body, 'UTF8') LIKE '%' || @ticket || '%'", + ("ticket", ticket))).Should().Be(0); + } + + [Fact] + public async Task A_person_whose_only_membership_is_revoked_reads_and_downloads_an_existing_export_and_may_file_again() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var live = proof.Token(EnglishLearner, English); + var (existing, _) = await FileExportAsync(client, live); + await RunExportAsync(proof, tenant, null, existing); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Revoked"); + using (var gone = await SendAsync(client, live, OwnPath + "/" + existing.ToString("D"))) + await ProblemAsync(gone, HttpStatusCode.NotFound, "not_found"); + + var native = NativeToken(proof, EnglishLearner); + using (var scopes = await EntrySendAsync(client, native, "/scopes")) + (await JsonAsync(scopes)).GetProperty("items").GetArrayLength().Should().Be(1, "a Revoked tombstone retains its group"); + using (var list = await EntrySendAsync(client, native, "/requests?group=tenant")) + (await JsonAsync(list)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(existing.ToString("D")); + var (_, bundle, _) = await EntryDownloadAsync(client, native, existing); + bundle.Should().NotBeEmpty(); + + // ADR-0106 § 7: a Revoked tombstone counts as a Membership, so the person may file again in the group. + var (again, _) = await EntryFileAsync(client, native, Key()); + again.Should().NotBe(existing); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE subject_user_id=@subject", + ("subject", EnglishLearner.Value))).Should().Be(2); + } + + [Fact] + public async Task The_retained_entry_reaches_only_the_subjects_own_groups_on_the_real_host_and_only_its_own_requests() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var branch = English.DefaultOrganization.OrganizationId; + var sibling = English.SecondOrganization.OrganizationId; + await proof.Database.AddMembershipAsync(English, EnglishLearner, branch); + var native = NativeToken(proof, EnglishLearner); + + // A tenant host lists every retained group of the tenant, the tenant-wide group first. + using (var scopes = await EntrySendAsync(client, native, "/scopes")) + (await JsonAsync(scopes)).GetProperty("items").EnumerateArray() + .Select(item => item.GetProperty("organizationId").ValueKind == JsonValueKind.Null ? "tenant" : item.GetProperty("organizationId").GetString()) + .Should().Equal("tenant", branch.Value.ToString("D")); + using (var paged = await EntrySendAsync(client, native, "/scopes?limit=1")) + { + var page = await JsonAsync(paged); + page.GetProperty("items").GetArrayLength().Should().Be(1); + page.GetProperty("pageInfo").GetProperty("nextCursor").GetString().Should().Be("tenant"); + } + + using (var next = await EntrySendAsync(client, native, "/scopes?cursor=tenant&limit=1")) + (await JsonAsync(next)).GetProperty("items")[0].GetProperty("organizationId").GetString().Should().Be(branch.Value.ToString("D")); + + // A group the person never held is not found, and so is the tenant-wide group of another tenant. + using (var foreignBranch = await EntrySendAsync(client, native, "/requests?group=" + sibling.Value.ToString("D"))) + await ProblemAsync(foreignBranch, HttpStatusCode.NotFound, "not_found"); + using (var foreignTenant = await EntrySendAsync(client, native, "/requests?group=tenant", host: SeedData.Yoga.Host)) + await ProblemAsync(foreignTenant, HttpStatusCode.NotFound, "not_found"); + using (var foreignScopes = await EntrySendAsync(client, native, "/scopes", host: SeedData.Yoga.Host)) + (await JsonAsync(foreignScopes)).GetProperty("items").GetArrayLength().Should().Be(0); + + // An organization host caps discovery and selection to its own organization. + const string branchHost = "retained-branch.learnstack.local"; + await proof.Database.ExecuteAsync(English, """ + INSERT INTO public.platform_host_to_tenant(host,tenant_id,organization_id,is_active,is_publicly_live) + VALUES(@host,@tenant,@organization,true,true) + """, new Dictionary { ["host"] = branchHost, ["tenant"] = tenant, ["organization"] = branch.Value }); + using (var capped = await EntrySendAsync(client, native, "/scopes", host: branchHost)) + (await JsonAsync(capped)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("organizationId").GetString()) + .Should().Equal(branch.Value.ToString("D")); + using (var tenantWide = await EntrySendAsync(client, native, "/requests?group=tenant", host: branchHost)) + await ProblemAsync(tenantWide, HttpStatusCode.NotFound, "not_found"); + using (var branchList = await EntrySendAsync(client, native, "/requests?group=" + branch.Value.ToString("D"), host: branchHost)) + await JsonAsync(branchList); + + // Another person's request in the same group is absent to every retained operation. + var (foreign, foreignVersion) = await FileExportAsync(client, proof.Token(EnglishAdmin, English)); + await RunExportAsync(proof, tenant, null, foreign); + var target = JsonSerializer.Serialize(new { requestId = foreign }); + using (var cancel = await EntrySendAsync(client, native, "/cancellations?group=tenant", target, Key(), "\"" + foreignVersion + "\"")) + await ProblemAsync(cancel, HttpStatusCode.NotFound, "not_found"); + using (var ticket = await EntrySendAsync(client, native, "/tickets?group=tenant", target)) + await ProblemAsync(ticket, HttpStatusCode.NotFound, "not_found"); + using (var listed = await EntrySendAsync(client, native, "/requests?group=tenant")) + (await JsonAsync(listed)).GetProperty("items").GetArrayLength().Should().Be(0); + + // A request of another group is absent in this one. + var (own, _) = await EntryFileAsync(client, native, Key(), "group=" + branch.Value.ToString("D")); + using (var elsewhere = await EntrySendAsync(client, native, "/tickets?group=tenant", JsonSerializer.Serialize(new { requestId = own }))) + await ProblemAsync(elsewhere, HttpStatusCode.NotFound, "not_found"); + } + + [Fact] + public async Task The_retained_entry_admits_only_its_closed_shape_credential_and_binding_and_a_ticket_never_crosses_paths() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var live = proof.Token(EnglishLearner, English); + var (id, _) = await FileExportAsync(client, live); + await RunExportAsync(proof, tenant, null, id); + var native = NativeToken(proof, EnglishLearner); + + // Without the native session source the retained entry does not exist; with a tenant selector it is malformed. + using (var plain = await SendAsync(client, native, EntryPath + "/scopes")) + await ProblemAsync(plain, HttpStatusCode.NotFound, "not_found"); + using (var selected = await EntrySendAsync(client, native, "/scopes", + mutate: request => request.Headers.Add(NativeSessionSourcePolicy.TenantHeader, tenant.ToString("D")))) + selected.StatusCode.Should().Be(HttpStatusCode.BadRequest); + // The selector-free native credential reaches no live operation. + using (var liveOperation = await EntrySendAsync(client, native, "", path: OwnPath)) + liveOperation.StatusCode.Should().Be(HttpStatusCode.BadRequest); + // Closed shape: no group, an unknown key, a key or precondition where none is taken. + using (var groupless = await EntrySendAsync(client, native, "/requests")) + await ProblemAsync(groupless, HttpStatusCode.BadRequest, "validation_failed"); + using (var extra = await EntrySendAsync(client, native, "/requests?group=tenant&membershipId=" + LearnerMembershipId.ToString("D"))) + await ProblemAsync(extra, HttpStatusCode.BadRequest, "validation_failed"); + var target = JsonSerializer.Serialize(new { requestId = id }); + using (var keyedTicket = await EntrySendAsync(client, native, "/tickets?group=tenant", target, Key())) + await ProblemAsync(keyedTicket, HttpStatusCode.BadRequest, "validation_failed"); + + // A ticket minted through the retained entry is bound to it, and a live ticket to the live path, for the same credential. + using (var retained = await EntrySendAsync(client, live, "/tickets?group=tenant", target)) + { + var ticket = (await JsonAsync(retained)).GetProperty("ticket").GetString()!; + using (var crossed = await ChunkAsync(client, live, id, ticket, 0)) + await ProblemAsync(crossed, HttpStatusCode.NotFound, "not_found"); + var otherSession = AccountSiteHttpTests.Token(proof.Issuer, English, actor: EnglishLearner.Value, + subject: IdentityPublicReadFixture.FoundationSubject(EnglishLearner), tokenId: "another-retained-session"); + using (var foreignSession = await EntryChunkAsync(client, otherSession, id, ticket, 0)) + await ProblemAsync(foreignSession, HttpStatusCode.NotFound, "not_found"); + using (var own = await EntryChunkAsync(client, live, id, ticket, 0)) + await JsonAsync(own); + } + + using (var minted = await SendAsync(client, live, OwnPath + "/" + id.ToString("D") + "/artifact/tickets", "POST", "{}")) + { + var ticket = (await JsonAsync(minted)).GetProperty("ticket").GetString()!; + using (var crossed = await EntryChunkAsync(client, live, id, ticket, 0)) + await ProblemAsync(crossed, HttpStatusCode.NotFound, "not_found"); + } + + // A person whose binding is no longer Active cannot enter at all. + await TransitionUserAsync(proof, EnglishLearner, "Closing"); + using (var closing = await EntrySendAsync(client, native, "/scopes")) + closing.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + private static HttpClient RetainedClient(IdentityAuthorizationHttpProof proof, RetainedLogCapture? logs = null) => + proof.Database.ClientFor(English.Host, services => + { + services.AddSingleton(); + if (logs is not null) services.AddSingleton(logs); + }, builder => + { + builder.UseSetting("Tenancy:TrustedHop:Networks:0", "127.0.0.1/32"); + builder.UseSetting("Tenancy:TrustedHop:Secrets:0", RetainedHop); + builder.UseSetting("Identity:NativeSession:CurrentSecret", RetainedNative); + }); + + /// A selector-free credential: the verified subject and actor, no tenant or organization claim. + private static string NativeToken(IdentityAuthorizationHttpProof proof, UserId actor) + { + using var source = JsonDocument.Parse(proof.Issuer.Payload(("sub", IdentityPublicReadFixture.FoundationSubject(actor)), + ("user_id", actor.Value.ToString("D")))); + var claims = source.RootElement.EnumerateObject().Where(property => property.Name is not ("tenant_id" or "organization_id")) + .ToDictionary(property => property.Name, property => property.Value.Clone(), StringComparer.Ordinal); + return proof.Issuer.Token(JsonSerializer.Serialize(claims)); + } + + private static async Task EntrySendAsync(HttpClient client, string token, string relative, string? body = null, + string? key = null, string? ifMatch = null, string? host = null, string? path = null, Action? mutate = null) + { + using var request = new HttpRequestMessage(body is null ? HttpMethod.Get : HttpMethod.Post, (path ?? EntryPath) + relative); + var effective = host ?? English.Host; + request.Headers.Host = effective; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + request.Headers.Add(TrustedHopOptions.HostHeaderName, effective); + request.Headers.Add(TrustedHopOptions.SecretHeaderName, RetainedHop); + request.Headers.Add("X-LearnStack-Visitor-Address", "198.51.100.24"); + request.Headers.Add(NativeSessionSourcePolicy.SecretHeader, RetainedNative); + if (key is not null) request.Headers.Add("Idempotency-Key", key); + if (ifMatch is not null) request.Headers.TryAddWithoutValidation("If-Match", ifMatch); + if (body is not null) request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + mutate?.Invoke(request); + return await client.SendAsync(request); + } + + private static async Task<(Guid Id, string Version)> EntryFileAsync(HttpClient client, string token, string key, string group = "group=tenant") + { + using var response = await EntrySendAsync(client, token, "/exports?" + group, "{}", key); + var accepted = await JsonAsync(response, HttpStatusCode.Accepted); + accepted.EnumerateObject().Select(property => property.Name).Should().Equal("id", "kind", "status", "version"); + response.Headers.Location.Should().BeNull("the retained entry has no per-request route"); + response.Headers.ETag!.Tag.Should().Be("\"" + Version(accepted) + "\""); + return (Guid.Parse(accepted.GetProperty("id").GetString()!), Version(accepted)); + } + + private static Task EntryChunkAsync(HttpClient client, string token, Guid request, string ticket, int index) => + EntrySendAsync(client, token, "/chunks?group=tenant", JsonSerializer.Serialize(new { requestId = request, ticket, index })); + + private static async Task<(string Ticket, byte[] Bundle, int Chunks)> EntryDownloadAsync(HttpClient client, string token, Guid request) + { + using var minted = await EntrySendAsync(client, token, "/tickets?group=tenant", JsonSerializer.Serialize(new { requestId = request })); + var grant = await JsonAsync(minted); + grant.EnumerateObject().Select(property => property.Name).Should().Equal("ticket", "expiresAt", "chunkCount", "byteCount"); + var ticket = grant.GetProperty("ticket").GetString()!; + var count = grant.GetProperty("chunkCount").GetInt32(); + var bytes = new List(); + for (var index = 0; index < count; index++) + { + using var read = await EntryChunkAsync(client, token, request, ticket, index); + var chunk = await JsonAsync(read); + chunk.GetProperty("index").GetInt32().Should().Be(index); + bytes.AddRange(Convert.FromBase64String(chunk.GetProperty("bytes").GetString()!)); + } + + return (ticket, bytes.ToArray(), count); + } + + /// The English administrator changes the learner's Membership status through the actual administration API. + private static async Task ChangeStatusAsync(HttpClient client, IdentityAuthorizationHttpProof proof, Guid membership, string status) + { + var admin = proof.Token(EnglishAdmin, English); + var path = DirectoryPath + "/" + membership.ToString("D"); + string version; + using (var read = await SendAsync(client, admin, path)) + version = Version(await JsonAsync(read)); + using var changed = await SendAsync(client, admin, path + "/status", "PUT", "{\"status\":\"" + status + "\"}", version, Key()); + await JsonAsync(changed); + } + + /// + /// The production schema has no User closure writer yet (ADR-0107 § 7 lands it): this owner-only fixture + /// accommodation moves the binding out of Active and restores the guard and policy exactly. + /// + private static async Task TransitionUserAsync(IdentityAuthorizationHttpProof proof, UserId user, string status) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.MigrationConnectionString); + var originalCheck = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + try + { + await ExecuteAsync(owner, null, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({originalCheck}) OR + (current_user='learnstack_migration' AND id='{user.Value:D}'::uuid AND status='{status}')); + """); + await ExecuteAsync(owner, null, "UPDATE public.users SET status=@status WHERE id=@user", ("status", status), ("user", user.Value)); + } + finally + { + await ExecuteAsync(owner, null, $""" + ALTER POLICY users_isolation ON public.users WITH CHECK ({originalCheck}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + } + } + + private sealed class RetainedLoopbackPeer : IStartupFilter + { + public Action Configure(Action next) => app => + { + app.Use((context, following) => { context.Connection.RemoteIpAddress = IPAddress.Loopback; return following(context); }); + next(app); + }; + } + + private sealed class RetainedLogCapture : ILogEventSink + { + internal ConcurrentQueue Entries { get; } = new(); + public void Emit(LogEvent logEvent) => Entries.Enqueue(logEvent); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs new file mode 100644 index 00000000..89aaba09 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs @@ -0,0 +1,175 @@ +using System.Reflection; +using System.Text; +using LearnStack.Api.Authentication; +using LearnStack.Api.Identity; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Controllers; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Authentication; + +/// +/// ADR-0106 § 9: the retained own data-request entry's closed purposes and strict request capture, modelled on the +/// consent subject's own operation and input tests. +/// +public sealed class OwnDataRequestEntryInputTests +{ + private const string Organization = "018f4d40-0000-7000-8000-000000000021"; + private const string Request = "018f4d40-0000-7000-8000-000000000031"; + private const string Ticket = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + private const string Root = "/api/v1/identity/data-request-entry/"; + + [Theory] + [InlineData("scopes", "GET", nameof(DataRequestEntryController.Scopes))] + [InlineData("requests", "GET", nameof(DataRequestEntryController.Requests))] + [InlineData("exports", "POST", nameof(DataRequestEntryController.CreateExport))] + [InlineData("cancellations", "POST", nameof(DataRequestEntryController.Cancel))] + [InlineData("tickets", "POST", nameof(DataRequestEntryController.MintTicket))] + [InlineData("chunks", "POST", nameof(DataRequestEntryController.ReadChunk))] + public void Each_closed_purpose_matches_only_its_exact_path_method_action_and_policy(string segment, string method, string action) + { + var operation = OwnDataRequestOperation.ForPath(Root + segment)!; + Assert.NotNull(operation); + var http = new DefaultHttpContext(); + http.Request.Path = Root + segment; + http.Request.Method = method; + http.SetEndpoint(Endpoint(action, operation.RequestType)); + Assert.True(operation.Matches(http)); + http.Request.Method = method == "GET" ? "POST" : "GET"; + Assert.False(operation.Matches(http)); + http.Request.Method = method; + var other = action == nameof(DataRequestEntryController.Scopes) ? nameof(DataRequestEntryController.Requests) : nameof(DataRequestEntryController.Scopes); + http.SetEndpoint(Endpoint(other, operation.RequestType)); + Assert.False(operation.Matches(http), "another action of the same controller is not this purpose"); + http.SetEndpoint(Endpoint(action, typeof(ListOwnDataRequestsQuery))); + Assert.False(operation.Matches(http), "a live request type is not this purpose"); + } + + [Theory] + [InlineData("/api/v1/identity/data-request-entry")] + [InlineData("/api/v1/identity/data-request-entry/")] + [InlineData("/api/v1/identity/data-request-entry/scopes/")] + [InlineData("/api/v1/identity/data-request-entry/SCOPES")] + [InlineData("/api/v1/identity/data-request-entry/artifact/revocations")] + [InlineData("/api/v1/identity/me/data-requests")] + public void The_closed_set_names_no_other_path(string path) => Assert.Null(OwnDataRequestOperation.ForPath(path)); + + [Theory] + [InlineData("scopes", "?group=tenant", "")] + [InlineData("scopes", "?limit=21", "")] + [InlineData("scopes", "?limit=01", "")] + [InlineData("scopes", "?cursor=not-a-group", "")] + [InlineData("requests", "", "")] + [InlineData("requests", "?group=TENANT", "")] + [InlineData("requests", "?group=018f4d40-0000-4000-8000-000000000021", "")] + [InlineData("requests", "?group=tenant&group=tenant", "")] + [InlineData("requests", "?group=tenant&limit=0", "")] + [InlineData("requests", "?group=tenant", "{}")] + [InlineData("exports", "?group=tenant", "{\"x\":1}")] + [InlineData("exports", "?group=tenant&cursor=a", "{}")] + [InlineData("tickets", "?group=tenant", "{}")] + [InlineData("tickets", "?group=tenant", "{\"requestId\":\"" + Request + "\",\"requestId\":\"" + Request + "\"}")] + [InlineData("chunks", "?group=tenant", "{\"requestId\":\"" + Request + "\",\"ticket\":\"" + Ticket + "\",\"index\":-1}")] + [InlineData("chunks", "?group=tenant", "{\"requestId\":\"" + Request + "\",\"ticket\":\"" + Ticket + "\",\"index\":1.0}")] + [InlineData("chunks", "?group=tenant", "{\"requestId\":\"" + Request + "\",\"ticket\":\"" + Ticket + "\"}")] + public async Task Noncanonical_or_extra_input_is_refused(string segment, string query, string body) + { + var http = Http(Root + segment, query, body); + Assert.Null(await OwnDataRequestHttpInput.ReadAsync(http, OwnDataRequestOperation.ForPath(Root + segment)!)); + } + + [Fact] + public async Task Group_selects_the_tenant_wide_group_or_one_organization() + { + var tenantWide = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "requests", "?group=tenant", ""), OwnDataRequestOperation.ForPath(Root + "requests")!); + Assert.NotNull(tenantWide); + Assert.True(tenantWide.SelectsGroup); + Assert.Null(tenantWide.OrganizationId); + Assert.Equal(new ListRetainedDataRequestsQuery(null, null, 20), tenantWide.Request); + var branch = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "requests", "?group=" + Organization + "&limit=5", ""), OwnDataRequestOperation.ForPath(Root + "requests")!); + Assert.NotNull(branch); + Assert.Equal(OrganizationId.From(Guid.Parse(Organization)), branch.OrganizationId); + Assert.Equal(new ListRetainedDataRequestsQuery(OrganizationId.From(Guid.Parse(Organization)), null, 5), branch.Request); + var discovery = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "scopes", "?cursor=tenant", ""), OwnDataRequestOperation.ForPath(Root + "scopes")!); + Assert.NotNull(discovery); + Assert.False(discovery.SelectsGroup); + Assert.Null(discovery.After!.OrganizationId); + } + + [Theory] + [InlineData("exports", true, false)] + [InlineData("cancellations", true, true)] + [InlineData("tickets", false, false)] + [InlineData("chunks", false, false)] + public async Task Keys_and_preconditions_reach_only_the_operations_that_take_them(string segment, bool keyed, bool conditional) + { + var body = segment switch + { + "exports" => "{}", + "chunks" => "{\"requestId\":\"" + Request + "\",\"ticket\":\"" + Ticket + "\",\"index\":0}", + _ => "{\"requestId\":\"" + Request + "\"}", + }; + var operation = OwnDataRequestOperation.ForPath(Root + segment)!; + var http = Http(Root + segment, "?group=tenant", body); + if (conditional) http.Request.Headers.IfMatch = "\"3\""; + Assert.NotNull(await OwnDataRequestHttpInput.ReadAsync(http, operation)); + http = Http(Root + segment, "?group=tenant", body); + if (conditional) http.Request.Headers.IfMatch = "\"3\""; + http.Request.Headers["Idempotency-Key"] = "retained-key-1"; + Assert.Equal(keyed, await OwnDataRequestHttpInput.ReadAsync(http, operation) is not null); + http = Http(Root + segment, "?group=tenant", body); + if (!conditional) http.Request.Headers.IfMatch = "\"3\""; + Assert.Null(await OwnDataRequestHttpInput.ReadAsync(http, operation)); + http = Http(Root + segment, "?group=tenant", body); + if (conditional) http.Request.Headers.IfMatch = "\"3\""; + http.Request.Headers.IfNoneMatch = "*"; + Assert.Null(await OwnDataRequestHttpInput.ReadAsync(http, operation)); + } + + [Fact] + public async Task Cancellation_binds_the_precondition_and_the_captured_input_loses_liveness_when_changed() + { + var operation = OwnDataRequestOperation.ForPath(Root + "cancellations")!; + var http = Http(Root + "cancellations", "?group=" + Organization, "{\"requestId\":\"" + Request + "\"}"); + http.Request.Headers.IfMatch = "\"7\""; + var input = await OwnDataRequestHttpInput.ReadAsync(http, operation); + Assert.NotNull(input); + Assert.Equal(new CancelRetainedDataRequestCommand(OrganizationId.From(Guid.Parse(Organization)), Guid.Parse(Request), 7), input.Request); + Assert.True(input.IsCurrent(http)); + http.Request.Headers.IfMatch = "\"8\""; + Assert.False(input.IsCurrent(http)); + http.Request.Headers.IfMatch = "\"7\""; + http.Request.QueryString = new QueryString("?group=tenant"); + Assert.False(input.IsCurrent(http)); + } + + [Fact] + public async Task The_chunk_body_is_bounded_at_four_kib() + { + var operation = OwnDataRequestOperation.ForPath(Root + "chunks")!; + var body = "{\"requestId\":\"" + Request + "\",\"ticket\":\"" + Ticket + "\",\"index\":0}"; + var http = Http(Root + "chunks", "?group=tenant", body + new string(' ', 4097 - Encoding.UTF8.GetByteCount(body))); + var failure = await Assert.ThrowsAsync(() => OwnDataRequestHttpInput.ReadAsync(http, operation)); + Assert.Equal(413, failure.StatusCode); + } + + private static Endpoint Endpoint(string action, Type policy) + { + var type = typeof(DataRequestEntryController); + var descriptor = new ControllerActionDescriptor { ControllerTypeInfo = type.GetTypeInfo(), MethodInfo = type.GetMethod(action)! }; + return new Endpoint(_ => Task.CompletedTask, + new EndpointMetadataCollection(descriptor, new OperationPolicyAttribute(policy)), "test"); + } + + private static DefaultHttpContext Http(string path, string query, string body) + { + var http = new DefaultHttpContext(); + http.Request.Path = path; + http.Request.QueryString = new QueryString(query); + http.Request.ContentType = "application/json"; + http.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); + return http; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs index d19d37ac..b72950b1 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs @@ -1,3 +1,4 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.CustomFields; using LearnStack.Modules.Tenancy.Application.Contracts.FieldConsents; using LearnStack.Modules.Tenancy.Application.Contracts.Settings; @@ -36,7 +37,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(154, actual.Length); + Assert.Equal(161, actual.Length); Assert.Equal(5, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.PublicRead)); Assert.Single(catalog.All, policy => policy.Kind == OperationPolicyKind.AccountRead); Assert.Equal(67, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.Protected)); @@ -49,6 +50,19 @@ public void Real_sources_cover_every_actual_request_once_without_implicit_grants Assert.Equal(OperationReadScope.Scoped, policy.ReadScope); }); Assert.Equal(8, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.OwnDataRequest)); + // ADR-0106 § 9: the retained own-scope entry's six operations and its keyed receipt read, key-less and grant-less too. + var retained = catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequestEntry).ToArray(); + Assert.Equal(new[] { typeof(ListRetainedDataRequestScopesQuery), typeof(ListRetainedDataRequestsQuery), typeof(CreateRetainedDataExportCommand), + typeof(CancelRetainedDataRequestCommand), typeof(MintRetainedDataExportTicketCommand), typeof(ReadRetainedDataExportChunkCommand), + typeof(ReadRetainedDataRequestReceiptQuery) }.OrderBy(type => type.FullName, StringComparer.Ordinal), + retained.Select(policy => policy.RequestType)); + Assert.All(retained, policy => + { + Assert.StartsWith("identity.data_request.", policy.Id, StringComparison.Ordinal); + Assert.Null(policy.RequiredPermission); + Assert.Empty(policy.Alternatives); + Assert.Equal(OperationReadScope.Scoped, policy.ReadScope); + }); var ownReads = catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnMembershipRead).ToArray(); Assert.Equal(new[] { typeof(GetOwnMembershipProfileQuery), typeof(ReadOwnMembershipProfileReceiptQuery), typeof(ReadOwnGrantedFieldConsentReceiptQuery), typeof(GetOwnMembershipContextsQuery), typeof(GetOwnCapabilitiesQuery), typeof(GetOwnMembershipCustomFieldsQuery), typeof(GetOwnMembershipFieldConsentQuery), typeof(GetTenantInvitationPolicyQuery), typeof(ReadInvitationPolicyReceiptQuery) } diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index 9391ed2c..3f9ab80f 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -882,6 +882,54 @@ exact wire shapes. cross-aggregate census of [ADR-0042](../../decisions/0042-tenant-provisioning-cross-aggregate-transaction.md) counts every data-request handler as a single-root writer. +#### Retained own-scope native entry (P03-10 Step 1) + +The retained own scope of [ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) +§ 9, modelled on the consent subject's entry: a person reads and files data requests after their +Membership is gone, and a Suspended person does so at all. The +[permission matrix](permissions.md#subject-data-request-bindings) owns who may call each operation, the +[audit matrix](audit.md#data-request-bindings) its classification, and +[Database Standards § Retained own data-request scope](../../standards/05-database.md#retained-own-data-request-scope) +the definer and the setter. + +| Route (under `/api/v1/identity/data-request-entry`) | Operation | Request | +|---|---|---| +| `GET scopes` | `identity.data_request.list_retained_scopes` | `ListRetainedDataRequestScopesQuery` | +| `GET requests?group=` | `identity.data_request.list_retained` | `ListRetainedDataRequestsQuery` | +| `POST exports?group=` | `identity.data_request.create_retained_export` | `CreateRetainedDataExportCommand` | +| `POST cancellations?group=` | `identity.data_request.cancel_retained` | `CancelRetainedDataRequestCommand` | +| `POST tickets?group=` | `identity.data_request.mint_retained_export_ticket` | `MintRetainedDataExportTicketCommand` | +| `POST chunks?group=` | `identity.data_request.read_retained_export_chunk` | `ReadRetainedDataExportChunkCommand` | +| (keyed replay only) | `identity.data_request.read_retained_receipt` | `ReadRetainedDataRequestReceiptQuery` | + +- **Entry.** The six paths are the closed set `OwnDataRequestOperation.ForPath`: exact path, method, + action and request type. `NativeSessionSourceMiddleware` admits them selector-free (a tenant or + organization header is `400`) with the separate native session credential, `ValidatedOwnDataRequestCredential` + captures the stock-validated bearer credential of exactly these requests, and binding normalization + must find an existing Active global binding, so a Closing, Closed or unknown binding is `401`. +- **Group.** Every purpose but discovery names one group in the single `group` query value: `tenant` + for the real host's tenant-wide group or an organization's canonical UUIDv7. Before any context exists, + `OwnDataRequestSubjectSource.PrepareAsync` reads the strict input (`OwnDataRequestHttpInput`), and the + confined lookup proves the group for the normalized actor under the host ceiling (on an organization + host only that organization's group). `TenantResolverMiddleware` then builds the context with + `TenantContextFactory.CreateForOwnDataRequestScope`. A group the person does not retain is `404`; + discovery pages at most twenty groups with the last group's key as `nextCursor`. +- **Captured request.** Each action sends exactly the request the source captured, read from its + `OwnDataRequestEntryRequest` feature; the source mints the witness only for that request object on + that endpoint, and the thin handlers (`RetainedDataRequestAdmission`) consume only that witness on its + physical owner, build the subject's caller and hand over to the same cores as the live path. +- **Keyed operations.** Creation and cancellation are `ProtectedAdministrationOperation`s 30 and 31. + Creation answers `202` with `{id, kind, status, version}` and its `ETag` and no `Location` (there is no + per-request route); cancellation needs `If-Match`. A replay rereads the captured input, selects the + witness's own receipt read and discloses the stored receipt only through it; a completed key found + only at claim time answers `request_in_progress`, as the consent withdrawal does. +- **Download binding.** `HttpDataExportSessionBinding` binds a retained-entry ticket under its own domain + (`learnstack.data_export.retained_session.v1`) to the group, the actor, the verified issuer and subject + and the digest of the exact `Authorization` header the retained credential capture recorded, and only + while the source is current on a ticket or chunk purpose. A ticket minted here is never honoured on the + live path, nor the reverse. When the BFF's entry handle refreshes the credential the binding no longer + matches, that download's cursor ends, and the resumed download mints a new ticket. + ## Entity-relationship diagram ```mermaid diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index b21135a9..0217b627 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -111,6 +111,21 @@ as the other own reads are. | DataSubjectRequest | `identity.data_request.read` | **MUST** (`read-sensitive`) | `GetDataRequestQuery`: an administrator's read of another person's request (ADR-0106 § 13), status and counts only. | | Original DataSubjectRequest outcome | `identity.data_request.read_receipt` | **MUST** (`read-sensitive`) | `ReadDataRequestReceiptQuery`: fresh disclosure admission of the original request before an administrator's keyed replay; never reruns the mutation. | +### Retained own-scope entry + +The retained own-scope native entry of [ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) +§ 9 writes exactly the live path's rows under the same names: its creation, cancellation, ticket mint and +chunk read register the operations above (`CreateRetainedDataExportCommand` → +`identity.data_request.create_export`, `CancelRetainedDataRequestCommand` → `identity.data_request.cancel`, +`MintRetainedDataExportTicketCommand` → `identity.data_export.mint_ticket`, +`ReadRetainedDataExportChunkCommand` → `identity.data_export.read_chunk`), each MUST with the same class, +on the transaction of the group the witness proved. Its group discovery, its group's request list and its +replay-receipt read (`ListRetainedDataRequestScopesQuery`, `ListRetainedDataRequestsQuery`, +`ReadRetainedDataRequestReceiptQuery`) are explicit Off registrations, as the subject's own live reads are. +The transport provenance of each row is the retained entry's own: `HttpAuthorizationTransportSource` +captures it only while the request's `OwnDataRequestSubjectSource` is current for the invocation's actor +and group. + `AcceptInvitationCommandHandler` is the only added two-root exception: central plural MUST intents for Invitation and the actual Membership share one ordinary unit of work. No User/provider transaction joins it. A missing required row or diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md index b2288c15..ec3d409a 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -199,6 +199,27 @@ announced group, and a request of another group, person or tenant is absent (`no | `ListDataRequestsQuery`, `GetDataRequestQuery`, `ReadDataRequestReceiptQuery` | Same | The group's exports and erasures, status and counts only, never a closure; MUST sensitive read | | `CancelDataRequestCommand`, `RevokeDataExportCommand` | Same, and the actor filed the request | Another administrator reads the request but cannot cancel it or revoke its artifact | +**Retained own-scope entry ([ADR-0106](../../decisions/0106-subject-data-requests-authority-and-status.md) § 4, § 9).** +Six further key-less operations use the `OwnDataRequestEntry` kind, plus the receipt read of its two keyed +ones. No Membership admits them: each is admitted only by a live `OwnDataRequestScopeWitness` that the one +HTTP source, `OwnDataRequestSubjectSource`, minted for its exact invocation after +`fn_identity_own_data_request_scopes` proved the group for the verified subject on the real host, under the +`HostAndOwnDataRequestScope` origin, which reaches no other kind. So a Suspended person, a person whose +Membership is Revoked and a group where only a request survives are served, and a Closing, Closed or +unknown binding, the system actor and a person with no retained group are not. The selector-free native +session source is required; a tenant or organization selector header is refused. On an organization host +the group is that organization's or none. No operation of any other kind is reachable under this origin, +and no retained operation under any other. + +| Application consumer | Capability / exact authority | Boundary | +|---|---|---| +| `ListRetainedDataRequestScopesQuery` | `OwnDataRequestEntry` (List) | The subject's retained groups on the real host, at most twenty per page; physically read-only; Off | +| `ListRetainedDataRequestsQuery` | `OwnDataRequestEntry` (Read) | Only requests about the actor, in the one selected group; physically read-only; Off | +| `CreateRetainedDataExportCommand` | `OwnDataRequestEntry` (Create) | As `CreateOwnDataExportCommand`, in the selected group; a Revoked tombstone counts as a Membership; keyed, 202 without `Location` | +| `CancelRetainedDataRequestCommand` | `OwnDataRequestEntry` (Cancel) | As `CancelOwnDataRequestCommand`, in the selected group, with `If-Match`; keyed | +| `MintRetainedDataExportTicketCommand`, `ReadRetainedDataExportChunkCommand` | `OwnDataRequestEntry` (Ticket, Chunk) and the retained session binding | Subject only; the ticket binds the retained-entry credential under its own domain and is never honoured on the live path, nor a live ticket here | +| `ReadRetainedDataRequestReceiptQuery` | `OwnDataRequestEntry` (the keyed purpose's witness) | Disclosure of the original request a keyed replay names; Off | + ## Proof ownership P03-1 Step 4 proves actual command metadata, the nonempty five-pair registry, diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index b09a069c..c351243a 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6683,7 +6683,10 @@ READ ONLY, `create`, `cancel`, `ticket` and `chunk` ordinary READ WRITE. It anno exactly the witness's group through the one witness-aware core, never joins or retargets an owner, and supplies no Membership, ordinary native session or tenant-wide `app.scope`. Its context origin, `HostAndOwnDataRequestScope`, reaches only operations -of the `OwnDataRequestEntry` policy kind. +of the `OwnDataRequestEntry` policy kind. Its one minter is the native retained-entry source, +`OwnDataRequestSubjectSource`, which is also the function's one observer through the +confined lookup and runs before the context exists; the entry itself is owned by +[Security § Retained consent-subject admission](11-security.md#retained-consent-subject-admission). ### Proof diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 1c91ef3e..8de8dbd3 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -1956,6 +1956,25 @@ census, including distinct own/admin custom-value PATCH requests; no generic native proxy or arbitrary dispatcher follows. The three global-self descriptors, roles and four physical context writers remain unchanged. +The retained own data-request entry of +[ADR-0106 § 9](../decisions/0106-subject-data-requests-authority-and-status.md) is the +same model for data requests, and the closed native retained-entry set grows by exactly its +six operations (list, create, read, cancel, ticket, chunk) under +`/api/v1/identity/data-request-entry/`. They are selector-free native requests: the native +session source credential and a stock-validated bearer credential, which +`ValidatedOwnDataRequestCredential` captures for exactly these requests, and an existing +Active global binding; a tenant or organization selector header is refused, and a +Closing/Closed or unknown binding never reaches them. Every purpose but discovery names its +one group, and `fn_identity_own_data_request_scopes` proves it for the normalized actor under +the independently classified host ceiling before the context exists; no submitted field +names the actor or widens the host. The `OwnDataRequestScope` witness is minted only by +`OwnDataRequestSubjectSource` for the exact captured request on the exact endpoint, admits +only `OwnDataRequestEntry` operations under the `HostAndOwnDataRequestScope` origin, and +supplies no Membership authority, ordinary native session or tenant-wide `app.scope`. A +download ticket minted here binds the retained credential under its own domain and is +never honoured on the live path, nor a live ticket here. The three global-self descriptors, +roles and four physical context writers remain unchanged. + New P03-5 body-bearing replay uses only the [scoped versioned HMAC ring and metadata read](05-database.md#custom-field-replay-key-custody). Existing fingerprint bytes and unrelated route behavior remain unchanged. Key IDs/HMAC and retained diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 639ce78a..c8214790 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 -**399 test methods run in +**401 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, @@ -5531,14 +5531,16 @@ structural test proves — and what it does not. #### `Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly` -- **Asserts:** the production census closes the finite HTTP surface at 84 MVC - actions and 79 distinct `IRequest` roots (both totals asserted on the literal census +- **Asserts:** the production census closes the finite HTTP surface at 90 MVC + actions and 85 distinct `IRequest` roots (both totals asserted on the literal census that the rule binds to production), including the public and authenticated - reads, the anonymous sign-in read, 29 protected keyed writes, native + reads, the anonymous sign-in read, 31 protected keyed writes, native session-scope admission, the eleven ADR-0099 federation actions, which reach - their requests only through `FederationOperationRunner`, and the twelve + their requests only through `FederationOperationRunner`, the twelve live ADR-0106/ADR-0107 data-request actions (six of them keyed; the ticket mint and - the chunk read each sit on a controller of their own, unkeyed). It also + the chunk read each sit on a controller of their own, unkeyed), and the six + ADR-0106 § 9 retained-entry actions on one controller (two keyed), each of which + sends exactly the request its source captured. It also checks the separate three exact GlobalSelf middleware routes. The canonical name is historical: administration includes writes, and sensitive reads can require a ReadWrite owner to commit MUST audit evidence. AccountSite and public @@ -7994,20 +7996,33 @@ names for the package's obligations are assigned with the step that introduces t admitted only by a live `OwnDataRequestScopeWitness` under the `HostAndOwnDataRequestScope` origin, which the fifteenth logical tenant setter consumes on a fresh owner announcing exactly the witness's group; the `OwnDataRequest` kind - requires the actor's Active Membership in exactly the announced group. Until the - native retained-entry operations land with their endpoints, no production type mints - the witness, builds the context, observes the groups or registers either kind. + requires the actor's Active Membership in exactly the announced group. The native + retained-entry operations (P03-10 Step 1, unit 4b) close the chain: exactly six + selector-free operations and the receipt read of their two keyed ones carry the + `OwnDataRequestEntry` kind; `OwnDataRequestSubjectSource` is the one minter and the one + registered `IOwnDataRequestScopeSource`, the one caller of the lookup and the one source of + the captured request feature; `TenantResolverMiddleware` is the one builder of the context; + and through the actual Program a Suspended person, a person whose only Membership is + Revoked and a person in several groups list, file, cancel and download in exactly their own + groups on the real host, while another person's request, an unretained group, a selector, a + missing native source, a non-Active binding and a ticket of the other path are refused. - **Source:** [ADR-0106 § 4 and § 9](../decisions/0106-subject-data-requests-authority-and-status.md), [Database Standards § Retained own data-request scope](05-database.md#retained-own-data-request-scope), [Security § The out-of-band setters](11-security.md#the-out-of-band-setters). - **Type:** real app-role PostgreSQL behaviour, refusals, ACL and policy oracle with a dirty probe of the arms; compiled minter, binder, owner and caller censuses with planted - minters and binders; coordinator and evaluator behaviour for both kinds. **Kind:** both. + minters and binders; coordinator and evaluator behaviour for both kinds; the retained + entry's syntax-confined authority exceptions with substituted values, its request-feature + binding with planted replacements, its closed paths and strict input, and its HTTP + behaviour end to end. **Kind:** both. - **Status:** **Implemented** (`OwnDataRequestScopeTests`); companion owners below. - **Test owners:** [OwnDataRequestScopeTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs), [OwnDataRequestScopeConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs), - [OwnDataRequestPolicyTests.cs](../../backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs). + [OwnDataRequestPolicyTests.cs](../../backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs), + [OwnDataRequestEntryInputTests.cs](../../backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs), + [AuthenticationAuthorityTests.DataRequest.cs](../../backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.DataRequest.cs), + [DataRequestHttpTests.RetainedEntry.cs](../../backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs). - **Phase:** 03 (P03-10, retained own scope). #### `Every_Module_With_A_Person_Reference_Registers_One_User_Data_Participant` diff --git a/frontend/packages/sdk/src/administration-contract.ts b/frontend/packages/sdk/src/administration-contract.ts index d89e4374..6f1b37d3 100644 --- a/frontend/packages/sdk/src/administration-contract.ts +++ b/frontend/packages/sdk/src/administration-contract.ts @@ -98,4 +98,6 @@ export const ADMINISTRATION_GET_CONTRACTS = Object.freeze({ '/api/v1/identity/me/data-requests/{id}': 'GetOwnDataRequest', '/api/v1/identity/data-requests': 'ListDataRequests', '/api/v1/identity/data-requests/{id}': 'GetDataRequest', + '/api/v1/identity/data-request-entry/scopes': 'ListRetainedDataRequestScopes', + '/api/v1/identity/data-request-entry/requests': 'ListRetainedDataRequests', } as const); diff --git a/frontend/packages/sdk/src/authenticated-contract.test.ts b/frontend/packages/sdk/src/authenticated-contract.test.ts index ec02908a..1484ff30 100644 --- a/frontend/packages/sdk/src/authenticated-contract.test.ts +++ b/frontend/packages/sdk/src/authenticated-contract.test.ts @@ -88,6 +88,8 @@ describe('generated GET contract ownership', () => { '/api/v1/identity/me/data-requests/{id}': 'GetOwnDataRequest', '/api/v1/identity/data-requests': 'ListDataRequests', '/api/v1/identity/data-requests/{id}': 'GetDataRequest', + '/api/v1/identity/data-request-entry/scopes': 'ListRetainedDataRequestScopes', + '/api/v1/identity/data-request-entry/requests': 'ListRetainedDataRequests', }); expect(PUBLIC_GET_CONTRACTS).toEqual({ '/api/v1/public/site': 'GetPublicSite', @@ -131,6 +133,8 @@ describe('generated GET contract ownership', () => { | 'GetOwnDataRequest' | 'ListDataRequests' | 'GetDataRequest' + | 'ListRetainedDataRequestScopes' + | 'ListRetainedDataRequests' >(); expect(RootContracts).toBe(AUTHENTICATED_GET_CONTRACTS); expectTypeOf().toEqualTypeOf(); diff --git a/frontend/packages/sdk/src/generated/schema.d.ts b/frontend/packages/sdk/src/generated/schema.d.ts index 7d079931..d4f595fe 100644 --- a/frontend/packages/sdk/src/generated/schema.d.ts +++ b/frontend/packages/sdk/src/generated/schema.d.ts @@ -267,6 +267,108 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/identity/data-request-entry/scopes": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description The retained own scope of ADR-0106 § 9: the groups on the real host where the verified subject holds or held a Membership of any status or has a data request. On an organization host only that organization's group. No Active Membership, no ordinary native session and no tenant or organization selector. Audit Off. No request body. */ + get: operations["ListRetainedDataRequestScopes"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-request-entry/requests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description The subject's own requests in one retained group, newest first, for a Suspended person, a person whose Membership was revoked or a group where only a request survives. A request whose job died is shown failed. Audit Off. No request body. */ + get: operations["ListRetainedDataRequests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-request-entry/exports": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject files an export of their own data in one retained group (ADR-0106 § 3, § 9). Refused when the subject holds no Membership of any status there. Strict empty JSON object. MUST audited. */ + post: operations["CreateRetainedDataExport"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-request-entry/cancellations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject cancels their own requested export in one retained group (requested to cancelled). Strict JSON object with requestId only. MUST audited. */ + post: operations["CancelRetainedDataRequest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-request-entry/tickets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description The subject mints a fifteen-minute download cursor over their own available, unexpired artifact in one retained group, bound to this retained-entry credential; never honoured on the live path. Strict JSON object with requestId only. Not keyed and never replayed; no If-Match. MUST read-sensitive audited; refused when the row cannot be written. */ + post: operations["MintRetainedDataExportTicket"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/data-request-entry/chunks": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Reads one decrypted chunk through a ticket presented in the body, never the URL, with the retained-entry credential that minted it. Serving the final chunk consumes the ticket. Every refusal is the same not_found. Not keyed. MUST read-sensitive audited per read; refused when the row cannot be written. */ + post: operations["ReadRetainedDataExportChunk"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/identity/me/data-requests/exports": { parameters: { query?: never; @@ -2181,6 +2283,28 @@ export interface components { foreground: string; muted: string; }; + RetainedDataExportChunkInput: { + /** Format: uuid */ + requestId: string; + /** @description Sensitive opaque download ticket: canonical unpadded base64url of 32 bytes. Body only; never a route, query or log. */ + ticket: string; + /** Format: int32 */ + index: number; + }; + RetainedDataRequestScopePageResponse: { + items: components["schemas"]["RetainedDataRequestScopeResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + RetainedDataRequestScopeResponse: { + /** Format: uuid */ + tenantId: string; + /** Format: uuid */ + organizationId: null | string; + }; + RetainedDataRequestTargetInput: { + /** Format: uuid */ + requestId: string; + }; RoleDetailResponse: { /** Format: uuid */ roleId: string; @@ -4951,6 +5075,782 @@ export interface operations { }; }; }; + ListRetainedDataRequestScopes: { + parameters: { + query?: { + /** @description The previous page's nextCursor: the last group's key (tenant or an organization UUIDv7). */ + cursor?: string; + /** @description Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse. */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The subject's retained groups on the real host, in order. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RetainedDataRequestScopePageResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ListRetainedDataRequests: { + parameters: { + query: { + /** @description The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found. */ + group: string; + /** @description Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse. */ + cursor?: string; + /** @description Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse. */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current receipt-safe projection: status and counts, never content. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OwnDataRequestPage"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CreateRetainedDataExport: { + parameters: { + query: { + /** @description The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found. */ + group: string; + }; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Accepted: the request's initial resource. Its export runs as a background job; read the group's requests for its status. */ + 202: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataRequestAcceptedResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CancelRetainedDataRequest: { + parameters: { + query: { + /** @description The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found. */ + group: string; + }; + header: { + /** @description Exactly one printable ASCII nonce, scoped to actor, tenant/organization, operation, method/path/query/body and canonical precondition. No automatic mutation retry. */ + "Idempotency-Key": string; + /** @description One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409. */ + "If-Match": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["RetainedDataRequestTargetInput"]; + }; + }; + responses: { + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + MintRetainedDataExportTicket: { + parameters: { + query: { + /** @description The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found. */ + group: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["RetainedDataRequestTargetInput"]; + }; + }; + responses: { + /** @description The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataExportTicketResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ReadRetainedDataExportChunk: { + parameters: { + query: { + /** @description The one retained group the operation acts in: tenant for the real host's tenant-wide group, or the organization's canonical UUIDv7. On an organization host only that organization. A group the subject does not retain is not_found. */ + group: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["RetainedDataExportChunkInput"]; + }; + }; + responses: { + /** @description One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["DataExportChunkResponse"]; + }; + }; + /** @description validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier host, credential and scope gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; request bodies are at most 4 KiB. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by the existing visitor/subject admission. */ + 429: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested retry delay in seconds for the first refusing admission boundary. A capacity hint does not promise an available registry slot; quota hints do not guarantee admission. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; CreateOwnDataExport: { parameters: { query?: never; From ae5b7323f62ce0d4982d6063e5398a99a92bbcaa Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 11:14:50 +0300 Subject: [PATCH 09/61] test(identity): pin the retained handlers and read-only list queries Review round 1 of P03-10 Step 1: the write-port census now counts the seven retained-entry handlers beside the fourteen live ones, the explicit read-only census names the two retained list queries, and the database standard no longer restates census counts that the tests own. ADR: 0106 Module: Identity Co-Authored-By: Claude Sonnet 5.5 --- .../AggregateWriteTests.cs | 24 ++++++++++++++++--- .../PersistenceConventionTests.ReadModes.cs | 9 +++++-- docs/standards/05-database.md | 9 ++++--- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs index adebd592..9628ae24 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs @@ -229,14 +229,32 @@ private static void AssertDataRequestPorts(HashSet identityDomains) .Where(type => type.Namespace == typeof(DataRequestService).Namespace && IsMessageHandler(type) && type != typeof(DataExportJobHandlers)) .ToList(); - handlers.Should().HaveCount(14, "the fourteen live-session data-request operations each have one thin handler"); - foreach (var handler in handlers) + static List ParameterTypes(Type handler) => + handler.GetConstructors().Single().GetParameters().Select(parameter => parameter.ParameterType).ToList(); + var live = handlers.Where(handler => ParameterTypes(handler).Contains(typeof(LiveDataRequestAdmission))).ToList(); + var retained = handlers.Where(handler => ParameterTypes(handler).Contains(typeof(RetainedDataRequestAdmission))).ToList(); + live.Should().HaveCount(14, "the fourteen live-session data-request operations each have one thin handler"); + retained.Should().HaveCount(7, "the seven retained-entry data-request operations each have one thin handler"); + handlers.Should().BeEquivalentTo(live.Concat(retained), + "every data-request handler is admitted by exactly one of the two admissions"); + foreach (var handler in live) { - var parameters = handler.GetConstructors().Single().GetParameters().Select(parameter => parameter.ParameterType).ToList(); + var parameters = ParameterTypes(handler); parameters.Should().HaveCount(2).And.Contain(typeof(LiveDataRequestAdmission), handler.Name); parameters.Should().ContainSingle(type => type == typeof(DataRequestService) || type == typeof(DataExportDownloadService), $"{handler.Name} delegates only to one countable single-root executor"); } + + foreach (var handler in retained) + { + var parameters = ParameterTypes(handler); + parameters.Should().ContainSingle(type => type == typeof(RetainedDataRequestAdmission), handler.Name); + parameters.Count(type => type == typeof(DataRequestService) || type == typeof(DataExportDownloadService)) + .Should().BeLessThanOrEqualTo(1, $"{handler.Name} delegates to at most one countable single-root executor"); + parameters.Should().OnlyContain(type => type == typeof(RetainedDataRequestAdmission) + || type == typeof(DataRequestService) || type == typeof(DataExportDownloadService), + $"{handler.Name} takes no write port of its own"); + } } /// Exercise the same handler predicate and constructor scan as production. diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.ReadModes.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.ReadModes.cs index 5c780d10..d009d130 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.ReadModes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.ReadModes.cs @@ -1,6 +1,7 @@ using LearnStack.Modules.Identity.Application.Contracts.CustomFields; using LearnStack.Modules.Tenancy.Application.Contracts.FieldConsents; using FluentAssertions; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Infrastructure.Bindings; @@ -44,6 +45,9 @@ private static readonly (string Owner, string Request, string Assembly)[] ReadOn // ADR-0099: the administrator's federation detail is audit Off and physically ReadOnly. (OwnProfileReadOnlyRegistration + ".AddIdentityContextualFoundation", typeof(LearnStack.Modules.Identity.Application.Contracts.Federation.GetFederationConnectionQuery).FullName!, "LearnStack.Modules.Identity.Application.Contracts"), + // ADR-0106 § 9: the retained discovery and status reads run on a physically read-only owner, as their witness requires. + (OwnProfileReadOnlyRegistration + ".AddIdentityContextualFoundation", typeof(ListRetainedDataRequestScopesQuery).FullName!, "LearnStack.Modules.Identity.Application.Contracts"), + (OwnProfileReadOnlyRegistration + ".AddIdentityContextualFoundation", typeof(ListRetainedDataRequestsQuery).FullName!, "LearnStack.Modules.Identity.Application.Contracts"), ]; // The shared persistence seam stays module-independent. Each of the eleven exact @@ -57,7 +61,7 @@ private static void AssertExplicitReadOnlyComposition() .Which.SetMethod.Should().BeNull(); typeof(GetAccountSiteQuery).IsDefined(typeof(LearnStack.SharedKernel.Tenancy.PublicSurfaceAttribute), false) .Should().BeFalse("the authenticated read does not acquire anonymous authority"); - foreach (var request in new[] { typeof(GetOwnMembershipProfileQuery), typeof(GetOwnMembershipContextsQuery), typeof(GetOwnCapabilitiesQuery), typeof(GetTenantInvitationPolicyQuery), typeof(InspectInvitationQuery), typeof(GetOwnInvitationResultQuery), typeof(GetOwnMembershipCustomFieldsQuery), typeof(GetOwnMembershipFieldConsentQuery), typeof(ListOwnFieldConsentScopesQuery), typeof(ListOwnMembershipFieldConsentsQuery) }) + foreach (var request in new[] { typeof(GetOwnMembershipProfileQuery), typeof(GetOwnMembershipContextsQuery), typeof(GetOwnCapabilitiesQuery), typeof(GetTenantInvitationPolicyQuery), typeof(InspectInvitationQuery), typeof(GetOwnInvitationResultQuery), typeof(GetOwnMembershipCustomFieldsQuery), typeof(GetOwnMembershipFieldConsentQuery), typeof(ListOwnFieldConsentScopesQuery), typeof(ListOwnMembershipFieldConsentsQuery), typeof(ListRetainedDataRequestScopesQuery), typeof(ListRetainedDataRequestsQuery) }) request.IsDefined(typeof(LearnStack.SharedKernel.Tenancy.PublicSurfaceAttribute), false) .Should().BeFalse("own Membership coverage does not acquire anonymous authority"); @@ -132,7 +136,8 @@ private static void AssertExplicitReadOnlyComposition() foreach (var request in new[] { typeof(GetAccountSiteQuery), typeof(GetOwnMembershipProfileQuery), typeof(GetOwnMembershipContextsQuery), typeof(GetOwnCapabilitiesQuery), typeof(GetTenantInvitationPolicyQuery), typeof(ReadInvitationPolicyReceiptQuery), typeof(InspectInvitationQuery), typeof(GetOwnInvitationResultQuery), typeof(AcceptInvitationCommand), - typeof(ListOrganizationsQuery), typeof(GetOrganizationDetailQuery) }) + typeof(ListOrganizationsQuery), typeof(GetOrganizationDetailQuery), + typeof(ListRetainedDataRequestScopesQuery), typeof(ListRetainedDataRequestsQuery) }) { var hardcoded = Instruction.Create(OpCodes.Isinst, behavior.Module.ImportReference(request)); handle.Body.Instructions.Add(hardcoded); diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index c351243a..b369d361 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -6358,7 +6358,7 @@ answers exactly that: - **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 body, ACL, owner and - volatility are pinned by the definer census (sixteen definers), and the callers of the + volatility are pinned by the definer census in `GlobalIdentitySchemaTests`, 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). @@ -6515,8 +6515,7 @@ after the change), `IdentityAuthorityRebindTests` (the run end to end, every ref 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`. +counts are in `GlobalIdentitySchemaTests` and the head pin in `MigrationRollbackTests`. ## Operator recovery storage @@ -6697,5 +6696,5 @@ request-only group retained, every refused state and argument, the function's AC owner, the two arms shut to a session and to every other role, a dirty probe that states exactly what the arms admit, the request policy against an independent canonicalized oracle, the confined lookup, and the setter's captured owner. The Membership policy -oracle is in `GlobalIdentitySchemaTests`, and the census counts are there too -(thirty-nine functions, seventeen definers); the head pin is in `MigrationRollbackTests`. +oracle is in `GlobalIdentitySchemaTests`, and the census counts are there too; the head +pin is in `MigrationRollbackTests`. From 810d1a46cfd897ea0c99f67c4e58422f5b383771 Mon Sep 17 00:00:00 2001 From: Cemil ILIK Date: Sun, 22 Nov 2026 11:37:22 +0300 Subject: [PATCH 10/61] fix(identity): harden the export store, tickets and contract Review round 1 of P03-10 Step 1, area A. An artifact is inserted only while its export is fulfilling and commits only with it completed (no xid cast); chunk and ticket guards read the artifact FOR SHARE and a chunk leaves only a withdrawn artifact; the job-phase and group-page reads gain indexes and the lists project only their columns; artifact timestamps come from the database clock; storage failures map to 503; the cipher disposal race is gated; a missing key refuses the mint and answers a chunk as an absence; a ticket is bounded to three open ones; buffers are pooled and cleared; the OpenAPI text states the ticket and paging semantics. Adds the data-export runbook and the leak, splice and interleaving tests. ADR: 0106, 0107 Module: Identity, Api, Infrastructure Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +- backend/openapi/v1.json | 36 ++--- .../Common/AdministrationHttpInput.cs | 65 +++++++- .../DataRequestDocumentTransformer.cs | 38 +++-- .../Identity/DataRequestsController.cs | 9 +- .../DataProtection/PlaintextSegmentBuffer.cs | 64 +++++++- .../DataProtection/DataExportCipher.cs | 58 +++++-- ...000_add_data_request_protected_receipts.cs | 9 ++ .../IDataExportArtifactStore.cs | 13 +- .../DataProtection/UserDataExportRecord.cs | 11 +- .../Authorization/IdentityPolicyEvaluation.cs | 24 ++- .../DataRequests/DataExportDownloadService.cs | 20 ++- .../DataRequestFailureReconciler.cs | 16 +- .../DataRequests/DataRequestService.cs | 17 +- .../DataRequests/IDataRequestStore.cs | 34 +++- .../RetainedDataRequestHandlers.cs | 7 +- .../DataRequests/DataExportTicketStore.cs | 14 ++ .../DataRequests/DataRequestReader.cs | 19 ++- .../DataRequests/DataRequestStore.cs | 42 ++--- .../PostgresDataExportArtifactStore.cs | 94 +++++++---- .../Persistence/DataRequestStorageDdl.cs | 69 ++++++-- .../BackgroundJobProductionManifestTests.cs | 19 +++ .../Database/DataExportArtifactStoreTests.cs | 117 +++++++++++++- .../Database/DataExportTestKit.cs | 3 + .../Database/DataRequestHttpTests.Export.cs | 91 ++++++++++- .../Database/DataRequestHttpTests.Tickets.cs | 33 ++-- .../Database/DataRequestHttpTests.cs | 4 +- .../DataRequestServiceStorageTests.cs | 152 ++++++++++++++++++ .../DataRequestStorageControlTests.cs | 67 +++++++- .../Database/DataRequestStorageTests.cs | 96 ++++++++--- .../Common/AdministrationHttpInputTests.cs | 43 +++++ .../PlaintextSegmentBufferTests.cs | 128 +++++++++++++++ .../Identity/DataRequestServiceTests.cs | 63 +++++++- .../Identity/OwnDataRequestPolicyTests.cs | 37 ++++- .../DataProtection/DataExportCipherTests.cs | 63 +++++++- docs/architecture/23-data-protection.md | 8 + docs/modules/identity/README.md | 15 +- docs/modules/identity/providers.md | 13 +- docs/runbooks/README.md | 1 + docs/runbooks/data-export.md | 119 ++++++++++++++ docs/standards/05-database.md | 1 + 41 files changed, 1520 insertions(+), 217 deletions(-) create mode 100644 backend/tests/LearnStack.Tests.Unit/Application/DataProtection/PlaintextSegmentBufferTests.cs create mode 100644 docs/runbooks/data-export.md diff --git a/README.md b/README.md index 1ea676dc..56851b96 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,10 @@ refusal, safe secret recovery and qualification details. API startup also requires the fixed [invitation SMTP settings and encryption key ring](docs/modules/identity/providers.md#configuration-surface-and-source-bindings). Prepare these operator-owned values before starting the API or demo; an older -private file is not silently supplied with a replacement encryption key. +private file is not silently supplied with a replacement encryption key. The API +also refuses to start without the data export key ring `DataExport__KeyRing` (same +JSON shape; `DataExport__MaxBytes` is optional), whose +[runbook](docs/runbooks/data-export.md) covers rotation and key loss. Keycloak's separate [account-verification sender](infra/keycloak/README.md#invitation-email-and-recipient-verification) must also work for the complete new-recipient journey. diff --git a/backend/openapi/v1.json b/backend/openapi/v1.json index c1b5e300..c8a0b6de 100644 --- a/backend/openapi/v1.json +++ b/backend/openapi/v1.json @@ -6196,7 +6196,7 @@ { "name": "limit", "in": "query", - "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", "schema": { "maximum": 20, "minimum": 1, @@ -6457,7 +6457,7 @@ "tags": [ "DataRequestEntry" ], - "description": "The subject\u0027s own requests in one retained group, newest first, for a Suspended person, a person whose Membership was revoked or a group where only a request survives. A request whose job died is shown failed. Audit Off. No request body.", + "description": "The subject\u0027s own requests in one retained group, newest first, for a Suspended person or a person whose Membership was revoked. A request whose job died is shown failed. Audit Off. No request body.", "operationId": "ListRetainedDataRequests", "parameters": [ { @@ -6485,7 +6485,7 @@ { "name": "limit", "in": "query", - "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + "description": "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", "schema": { "maximum": 20, "minimum": 1, @@ -7537,7 +7537,7 @@ } }, "404": { - "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. A ticket is bound to the credential that minted it, so a not_found during a download may only mean the session credential changed (a refresh or a new sign-in): mint a new ticket and resume from the index that failed. If that mint answers 409 with data_export_unavailable, the artifact is really gone (revoked, expired, purged, or no longer readable).", "headers": { "Cache-Control": { "required": true, @@ -7679,7 +7679,7 @@ } }, "409": { - "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact, when the key it was sealed under is no longer in the export key ring, or when the artifact already holds three unconsumed, unexpired tickets (a slot frees when one is consumed by its final chunk or expires after fifteen minutes).", "headers": { "Cache-Control": { "required": true, @@ -7742,7 +7742,7 @@ }, "responses": { "200": { - "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. Decoding every chunk\u0027s bytes and concatenating them in index order yields the bundle: one UTF-8 JSON document, served as application/json; charset=utf-8, whose top-level member schema_version names its format.", "headers": { "Cache-Control": { "required": true, @@ -7835,7 +7835,7 @@ } }, "404": { - "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike.", + "description": "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike. A ticket is bound to the credential that minted it, so a not_found during a download may only mean the session credential changed (a refresh or a new sign-in): mint a new ticket and resume from the index that failed. If that mint answers 409 with data_export_unavailable, the artifact is really gone (revoked, expired, purged, or no longer readable).", "headers": { "Cache-Control": { "required": true, @@ -8331,7 +8331,7 @@ { "name": "limit", "in": "query", - "description": "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + "description": "Canonical positive ASCII decimal Int32, default 20; a page holds at most 100 items and a larger value is clamped to 100 (API Design \u00A7 Pagination), unlike the retained entry, whose page size is 1 through 20. Signs, leading zeros and repeats refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", "schema": { "maximum": 2147483647, "minimum": 1, @@ -9234,7 +9234,7 @@ { "name": "If-Match", "in": "header", - "description": "One canonical strong quoted decimal artifact version (the receipt\u0027s artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "description": "One canonical strong quoted decimal ARTIFACT version: the receipt\u0027s artifact.version, not the request\u0027s version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale artifact version is 409.", "required": true, "schema": { "maxLength": 21, @@ -9268,7 +9268,7 @@ } }, "ETag": { - "description": "The artifact\u0027s version after the revocation.", + "description": "The artifact\u0027s version after the revocation (artifact.version), not the request\u0027s.", "required": true, "schema": { "maxLength": 21, @@ -9664,7 +9664,7 @@ } }, "404": { - "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike. A ticket is bound to the credential that minted it, so a not_found during a download may only mean the session credential changed (a refresh or a new sign-in): mint a new ticket and resume from the index that failed. If that mint answers 409 with data_export_unavailable, the artifact is really gone (revoked, expired, purged, or no longer readable).", "headers": { "Cache-Control": { "required": true, @@ -9806,7 +9806,7 @@ } }, "409": { - "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + "description": "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact, when the key it was sealed under is no longer in the export key ring, or when the artifact already holds three unconsumed, unexpired tickets (a slot frees when one is consumed by its final chunk or expires after fifteen minutes).", "headers": { "Cache-Control": { "required": true, @@ -9867,7 +9867,7 @@ }, "responses": { "200": { - "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + "description": "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. Decoding every chunk\u0027s bytes and concatenating them in index order yields the bundle: one UTF-8 JSON document, served as application/json; charset=utf-8, whose top-level member schema_version names its format.", "headers": { "Cache-Control": { "required": true, @@ -9960,7 +9960,7 @@ } }, "404": { - "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike.", + "description": "not_found without an Active Membership in exactly the context\u0027s group, for a request about another person or of another group, and for every ticket or chunk refusal alike. A ticket is bound to the credential that minted it, so a not_found during a download may only mean the session credential changed (a refresh or a new sign-in): mint a new ticket and resume from the index that failed. If that mint answers 409 with data_export_unavailable, the artifact is really gone (revoked, expired, purged, or no longer readable).", "headers": { "Cache-Control": { "required": true, @@ -10455,7 +10455,7 @@ { "name": "limit", "in": "query", - "description": "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + "description": "Canonical positive ASCII decimal Int32, default 20; a page holds at most 100 items and a larger value is clamped to 100 (API Design \u00A7 Pagination), unlike the retained entry, whose page size is 1 through 20. Signs, leading zeros and repeats refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", "schema": { "maximum": 2147483647, "minimum": 1, @@ -11358,7 +11358,7 @@ { "name": "If-Match", "in": "header", - "description": "One canonical strong quoted decimal artifact version (the receipt\u0027s artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", + "description": "One canonical strong quoted decimal ARTIFACT version: the receipt\u0027s artifact.version, not the request\u0027s version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale artifact version is 409.", "required": true, "schema": { "maxLength": 21, @@ -11392,7 +11392,7 @@ } }, "ETag": { - "description": "The artifact\u0027s version after the revocation.", + "description": "The artifact\u0027s version after the revocation (artifact.version), not the request\u0027s.", "required": true, "schema": { "maxLength": 21, @@ -28516,7 +28516,7 @@ "maxLength": 174764, "minLength": 4, "type": "string", - "description": "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk in index order yields the bundle." + "description": "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk\u0027s decoded bytes in index order yields the bundle: one UTF-8 JSON document (application/json; charset=utf-8) whose top-level member schema_version names its format." } }, "additionalProperties": false diff --git a/backend/src/LearnStack.Api/Common/AdministrationHttpInput.cs b/backend/src/LearnStack.Api/Common/AdministrationHttpInput.cs index a3d46f2d..9e1dbb1a 100644 --- a/backend/src/LearnStack.Api/Common/AdministrationHttpInput.cs +++ b/backend/src/LearnStack.Api/Common/AdministrationHttpInput.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using System.Globalization; +using System.Security.Cryptography; using System.Text; using System.Text.Json; using LearnStack.SharedKernel.Domain; @@ -25,6 +26,17 @@ internal static bool TryId(string? text, out Guid id) => Guid.TryParseExact(text && string.Equals(text, id.ToString("D"), StringComparison.Ordinal) && text![19] is '8' or '9' or 'a' or 'b'; internal static async Task ReadBodyBytesAsync(HttpContext http) + { + var (buffer, count) = await ReadBodyAsync(http); + try { return buffer[..count]; } + finally { CryptographicOperations.ZeroMemory(buffer); } + } + + /// + /// The body into one fixed buffer the caller owns and clears: nothing is copied out of it, so clearing it is all the + /// clearing this read owes. The request's own buffering stream is the host's and is not reachable from here. + /// + private static async Task<(byte[] Buffer, int Count)> ReadBodyAsync(HttpContext http) { if (http.Request.ContentLength > MaxBodyBytes) throw TooLarge(); http.Request.EnableBuffering(); @@ -40,7 +52,12 @@ internal static async Task ReadBodyBytesAsync(HttpContext http) count += read; } if (count > MaxBodyBytes) throw TooLarge(); - return bytes[..count]; + return (bytes, count); + } + catch + { + CryptographicOperations.ZeroMemory(bytes); + throw; } finally { http.Request.Body.Position = 0; } } @@ -63,6 +80,31 @@ internal static async Task ReadBodyBytesAsync(HttpContext http) return null; } + /// + /// for a body that carries a secret (a download ticket): the document parses the read + /// buffer in place and disposing the result overwrites that buffer with zeros, on every path. Best effort: a string + /// the caller takes from the document is a managed copy this cannot clear. + /// + internal static async Task ReadSensitiveObjectAsync(HttpContext http, params string[] fields) + { + if (http.Request.Query.Count != 0 || !SupportsJsonMedia(http.Request)) return null; + var (buffer, count) = await ReadBodyAsync(http); + var body = buffer.AsMemory(0, count); + JsonDocument? document = null; + try + { + _ = StrictUtf8.GetCharCount(body.Span); + document = JsonDocument.Parse(body, new JsonDocumentOptions { MaxDepth = 5 }); + if (HasFields(document.RootElement, fields)) return new SensitiveJsonBody(document, buffer); + } + catch (JsonException) { } + catch (DecoderFallbackException) { } + catch (InvalidOperationException) { } + document?.Dispose(); + CryptographicOperations.ZeroMemory(buffer); + return null; + } + internal static bool SupportsJsonMedia(HttpRequest request) => MediaTypeHeaderValue.TryParse(request.ContentType, out var contentType) && string.Equals(contentType.MediaType.Value, "application/json", StringComparison.OrdinalIgnoreCase) @@ -169,3 +211,24 @@ private static bool TryString(JsonElement item, int maximum, out string? value) private static BadHttpRequestException TooLarge() => new("Administration request body exceeds its limit.", StatusCodes.Status413PayloadTooLarge); } + +/// A parsed request body over a buffer that is overwritten with zeros when the body is disposed. +internal sealed class SensitiveJsonBody(JsonDocument document, byte[] buffer) : IDisposable +{ + private bool _disposed; + + public JsonElement RootElement => document.RootElement; + + /// The read buffer itself, exposed so a test can prove it is cleared. + internal ReadOnlyMemory Buffer => buffer; + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + document.Dispose(); + CryptographicOperations.ZeroMemory(buffer); + } + + public override string ToString() => nameof(SensitiveJsonBody); +} diff --git a/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs index 7b5066a1..42bdedfb 100644 --- a/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs @@ -19,6 +19,15 @@ private enum Shape { Read, Page, Create, Mutation, Ticket, Chunk } private static readonly string[] SuccessStatuses = ["200", "201", "202"]; + /// What a client does with a ticket or chunk refusal (ADR-0107 § 4). + private const string DownloadRecovery = " A ticket is bound to the credential that minted it, so a not_found during a download may only mean the " + + "session credential changed (a refresh or a new sign-in): mint a new ticket and resume from the index that failed. If that mint " + + "answers 409 with data_export_unavailable, the artifact is really gone (revoked, expired, purged, or no longer readable)."; + + /// The assembled bundle's shape, stated on both chunk routes. + private const string BundleShape = "Decoding every chunk's bytes and concatenating them in index order yields the bundle: one UTF-8 JSON " + + "document, served as application/json; charset=utf-8, whose top-level member schema_version names its format."; + private sealed record Contract(string Path, HttpMethod Method, string Name, Shape Shape, string Response, string? Body, bool Own); private static readonly Contract[] Contracts = @@ -114,7 +123,7 @@ [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, Name = "limit", In = ParameterLocation.Query, Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = "20", Default = JsonValue.Create(20) }, - Description = "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse.", + Description = "Canonical positive ASCII decimal Int32 from 1 through 20, default 20. Signs, leading zeros, repeats and larger values refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", }); } if (contract.Body is not null) @@ -152,7 +161,7 @@ [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, { Shape.Create => "Accepted: the request's initial resource. Its export runs as a background job; read the group's requests for its status.", Shape.Ticket => "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", - Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. " + BundleShape, Shape.Mutation => "Committed receipt, or the retained receipt of a completed exact-key replay.", _ => discovery ? "The subject's retained groups on the real host, in order." : "Current receipt-safe projection: status and counts, never content.", }, @@ -164,7 +173,8 @@ [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, ("400", "validation_failed for malformed or noncanonical input, a missing or extra group, extra or repeated query, an unexpected body, a tenant or organization selector header, an invalid key or precondition, or a key or precondition on an operation that takes none."), ("401", "unauthorized for present invalid, expired or undecidable credentials, a missing or invalid native session source, or a binding that is not Active; bare Bearer challenge."), ("403", "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed."), - ("404", "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike."), + ("404", "not_found for a group the subject does not retain on this host, a request about another person or of another group, and for every ticket or chunk refusal alike." + + (contract.Shape is Shape.Ticket or Shape.Chunk ? DownloadRecovery : string.Empty)), ("405", "method_not_allowed after earlier host, credential and scope gates."), ("413", "payload_too_large; request bodies are at most 4 KiB."), ("429", "rate_limited by the existing visitor/subject admission."), @@ -176,7 +186,7 @@ [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, Description = contract.Shape switch { Shape.Create => "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", - Shape.Ticket => "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + Shape.Ticket => TicketConflict, _ => "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", }, Headers = new Dictionary { ["Cache-Control"] = new OpenApiHeader { Required = true, Schema = Enum("no-store") } }, @@ -200,7 +210,7 @@ [new OpenApiSecuritySchemeReference(NativeEntryDocumentTransformer.SourceScheme, private static string RetainedDescription(Contract contract) => contract.Name switch { "ListRetainedDataRequestScopes" => "The retained own scope of ADR-0106 § 9: the groups on the real host where the verified subject holds or held a Membership of any status or has a data request. On an organization host only that organization's group. No Active Membership, no ordinary native session and no tenant or organization selector. Audit Off. No request body.", - "ListRetainedDataRequests" => "The subject's own requests in one retained group, newest first, for a Suspended person, a person whose Membership was revoked or a group where only a request survives. A request whose job died is shown failed. Audit Off. No request body.", + "ListRetainedDataRequests" => "The subject's own requests in one retained group, newest first, for a Suspended person or a person whose Membership was revoked. A request whose job died is shown failed. Audit Off. No request body.", "CreateRetainedDataExport" => "The subject files an export of their own data in one retained group (ADR-0106 § 3, § 9). Refused when the subject holds no Membership of any status there. Strict empty JSON object. MUST audited.", "CancelRetainedDataRequest" => "The subject cancels their own requested export in one retained group (requested to cancelled). Strict JSON object with requestId only. MUST audited.", "MintRetainedDataExportTicket" => "The subject mints a fifteen-minute download cursor over their own available, unexpired artifact in one retained group, bound to this retained-entry credential; never honoured on the live path. Strict JSON object with requestId only. Not keyed and never replayed; no If-Match. MUST read-sensitive audited; refused when the row cannot be written.", @@ -235,7 +245,7 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op Name = "limit", In = ParameterLocation.Query, Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32", Minimum = "1", Maximum = "2147483647", Default = JsonValue.Create(20) }, - Description = "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + Description = "Canonical positive ASCII decimal Int32, default 20; a page holds at most 100 items and a larger value is clamped to 100 (API Design § Pagination), unlike the retained entry, whose page size is 1 through 20. Signs, leading zeros and repeats refuse. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", }); } if (contract.Body is not null) @@ -260,7 +270,7 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op Required = true, Schema = EntityTag(), Description = contract.Name.StartsWith("Revoke", StringComparison.Ordinal) - ? "One canonical strong quoted decimal artifact version (the receipt's artifact.version). Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409." + ? "One canonical strong quoted decimal ARTIFACT version: the receipt's artifact.version, not the request's version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale artifact version is 409." : "One canonical strong quoted decimal request version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale version is 409.", }); } @@ -275,7 +285,7 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op { Shape.Create => "Accepted: the request's initial resource. Its export runs as a background job; read the Location for its status.", Shape.Ticket => "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", - Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext.", + Shape.Chunk => "One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. " + BundleShape, Shape.Mutation => "Committed receipt, or the retained receipt of a completed exact-key replay.", _ => "Current receipt-safe projection: status and counts, never content.", }, @@ -289,6 +299,7 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op ("403", contract.Own ? "forbidden when the request carries no live session the ticket can bind." : "forbidden without current identity.membership.admin covering the context's group."), ("404", contract.Own ? "not_found without an Active Membership in exactly the context's group, for a request about another person or of another group, and for every ticket or chunk refusal alike." + + (contract.Shape is Shape.Ticket or Shape.Chunk ? DownloadRecovery : string.Empty) : "not_found for noncoverage, for a request or Membership of another group, a closure, or a request another administrator filed (cancel, revoke)."), ("405", "method_not_allowed after earlier host, credential and scope gates."), ("413", "payload_too_large; request bodies are at most 16 KiB."), @@ -301,7 +312,7 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op Description = contract.Shape switch { Shape.Create => "business_rule_violation: errors.$ carries request_already_active (a request of this kind is still active in the group) or blocked_hold; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", - Shape.Ticket => "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact.", + Shape.Ticket => TicketConflict, Shape.Chunk => "Never: a chunk refusal is not_found.", _ => "concurrency_conflict for a valid stale version; business_rule_violation for a status the transition does not admit (errors.artifact carries data_export_unavailable for an artifact already revoked, expired or purged); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", }, @@ -316,7 +327,8 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op { Required = true, Schema = EntityTag(), - Description = contract.Name.StartsWith("Revoke", StringComparison.Ordinal) ? "The artifact's version after the revocation." : "The request's version.", + Description = contract.Name.StartsWith("Revoke", StringComparison.Ordinal) + ? "The artifact's version after the revocation (artifact.version), not the request's." : "The request's version.", }; if (contract.Shape is Shape.Create or Shape.Mutation) success.Headers[IdempotentAttribute.ReplayedHeaderName] = new OpenApiHeader { @@ -337,6 +349,10 @@ private static void Describe(OpenApiDocument document, IOpenApiPathItem path, Op }; } + private const string TicketConflict = "business_rule_violation: errors.artifact carries data_export_unavailable when the request has no " + + "available, unexpired artifact, when the key it was sealed under is no longer in the export key ring, or when the artifact already " + + "holds three unconsumed, unexpired tickets (a slot frees when one is consumed by its final chunk or expires after fifteen minutes)."; + private static string Description(Contract contract) => contract.Shape switch { Shape.Create when contract.Own => "The subject files an export of their own data in the session's group (ADR-0106 § 3). Requires an Active Membership in exactly that group; no permission key. The request holds the frozen snapshot of the subject's Memberships of any status in the group and its job is submitted on the same transaction. Strict empty JSON object. MUST audited.", @@ -410,7 +426,7 @@ private static void Schemas(OpenApiDocument document) ContentEncoding = "base64", MinLength = 4, MaxLength = 174764, - Description = "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk in index order yields the bundle." + Description = "Base64 of one chunk of the decrypted bundle, at most 128 KiB of plaintext. Concatenating every chunk's decoded bytes in index order yields the bundle: one UTF-8 JSON document (application/json; charset=utf-8) whose top-level member schema_version names its format." })); } diff --git a/backend/src/LearnStack.Api/Identity/DataRequestsController.cs b/backend/src/LearnStack.Api/Identity/DataRequestsController.cs index 3e0471f3..c4cd0ee7 100644 --- a/backend/src/LearnStack.Api/Identity/DataRequestsController.cs +++ b/backend/src/LearnStack.Api/Identity/DataRequestsController.cs @@ -107,7 +107,8 @@ public sealed class OwnDataExportTicketsController(ISender sender) : ApiControll [ProducesResponseType(StatusCodes.Status200OK)] public async Task MintTicket(string id, CancellationToken cancellationToken) { - using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + // The body is the empty object, but it is read through the clearing reader like the chunk body it pairs with. + using var body = await AdministrationHttpInput.ReadSensitiveObjectAsync(HttpContext); if (body is null || !AdministrationHttpInput.TryId(id, out var target) || DataExportDownloadInput.HasPrecondition(Request)) return AdministrationHttpInput.Invalid(); var result = await sender.Send(new MintOwnDataExportTicketCommand(target), cancellationToken); @@ -119,7 +120,8 @@ public async Task MintTicket(string id, CancellationToken cancell /// /// ADR-0107 § 4: one decrypted chunk through a ticket presented in the body, never in the URL. Not keyed and not -/// conditional; the plaintext buffer is cleared once written. +/// conditional; the request body's read buffer and the plaintext buffer are cleared once used (best effort: managed +/// strings and the host's own buffers are beyond reach). /// [Route("identity/me/data-requests")] public sealed class OwnDataExportChunksController(ISender sender) : ApiControllerBase @@ -131,7 +133,8 @@ public sealed class OwnDataExportChunksController(ISender sender) : ApiControlle [ProducesResponseType(StatusCodes.Status200OK)] public async Task ReadChunk(string id, CancellationToken cancellationToken) { - using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext, "ticket", "index"); + // The ticket is a secret: its read buffer is overwritten when the body is disposed. + using var body = await AdministrationHttpInput.ReadSensitiveObjectAsync(HttpContext, "ticket", "index"); if (body is null || !AdministrationHttpInput.TryId(id, out var target) || DataExportDownloadInput.HasPrecondition(Request) || !AdministrationHttpInput.TryText(body.RootElement, "ticket", false, 64, out var ticket) || body.RootElement.GetProperty("index") is not { ValueKind: JsonValueKind.Number } index diff --git a/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs b/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs index 72208673..5beb192f 100644 --- a/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs +++ b/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs @@ -12,21 +12,43 @@ namespace LearnStack.Application.DataProtection; /// /// /// A writer is handed one scratch buffer; copies what it wrote into the segments and -/// overwrites the scratch with zeros. Every segment is overwritten with zeros on . +/// overwrites the scratch with zeros. Each segment is rented from an (the shared pool in +/// production) and exactly of it is used; on +/// every rented array is overwritten with zeros in full before it is returned, so the pool never +/// hands a later renter the bundle's plaintext. A chunk from is valid only until then. +/// +/// +/// Hygiene is best effort: the buffers this type owns are cleared, the JSON writer's own state and any copy a reader +/// makes are not. /// /// /// The limit never throws inside a writer. Bytes past it are dropped and is set, /// so a JSON writer flushing past the ceiling leaves the caller a refusal to read, not a half-written state. /// /// -internal sealed class PlaintextSegmentBuffer(long limit) : IBufferWriter, IDisposable +internal sealed class PlaintextSegmentBuffer : IBufferWriter, IDisposable { private const int MinimumScratch = 4096; + private readonly long _limit; + private readonly ArrayPool _pool; private readonly List _segments = []; private byte[] _scratch = []; private int _tail = DataRequestLimits.ChunkPlaintextBytes; private bool _disposed; + public PlaintextSegmentBuffer(long limit) + : this(limit, ArrayPool.Shared) + { + } + + /// A buffer over a given pool; the production constructor passes the shared one. + internal PlaintextSegmentBuffer(long limit, ArrayPool pool) + { + ArgumentNullException.ThrowIfNull(pool); + _limit = limit; + _pool = pool; + } + /// The bytes stored. public long Length { get; private set; } @@ -44,7 +66,7 @@ public void Advance(int count) ArgumentOutOfRangeException.ThrowIfGreaterThan(count, _scratch.Length); try { - if (Overflowed || Length + count > limit) + if (Overflowed || Length + count > _limit) { Overflowed = true; return; @@ -55,12 +77,24 @@ public void Advance(int count) { if (_tail == DataRequestLimits.ChunkPlaintextBytes) { - _segments.Add(new byte[DataRequestLimits.ChunkPlaintextBytes]); + // A rented array may be larger and may hold a former renter's bytes: only its first chunk-size + // bytes are used, each written before it is read. + var segment = _pool.Rent(DataRequestLimits.ChunkPlaintextBytes); + try + { + _segments.Add(segment); + } + catch + { + Release(segment); + throw; + } + _tail = 0; } var take = Math.Min(source.Length, DataRequestLimits.ChunkPlaintextBytes - _tail); - source[..take].CopyTo(_segments[^1].AsSpan(_tail)); + source[..take].CopyTo(_segments[^1].AsSpan(_tail, take)); _tail += take; source = source[take..]; } @@ -77,12 +111,19 @@ public void Advance(int count) public IEnumerable> Chunks() { ObjectDisposedException.ThrowIf(_disposed, this); - for (var index = 0; index < _segments.Count; index++) + for (var index = 0; ; index++) { + // Checked before the bound: a reader that outlives the buffer is told so, never handed a returned array + // and never shown a shortened bundle as if it had ended. ObjectDisposedException.ThrowIf(_disposed, this); + if (index >= _segments.Count) + { + yield break; + } + yield return index == _segments.Count - 1 ? _segments[index].AsMemory(0, _tail) - : _segments[index]; + : _segments[index].AsMemory(0, DataRequestLimits.ChunkPlaintextBytes); } } @@ -96,7 +137,7 @@ public void Dispose() _disposed = true; foreach (var segment in _segments) { - CryptographicOperations.ZeroMemory(segment); + Release(segment); } CryptographicOperations.ZeroMemory(_scratch); @@ -105,6 +146,13 @@ public void Dispose() Length = 0; } + /// Overwrites the whole rented array, not only the part used, and only then returns it. + private void Release(byte[] segment) + { + CryptographicOperations.ZeroMemory(segment); + _pool.Return(segment); + } + private byte[] Scratch(int sizeHint) { ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs index 93c13387..f12d75e2 100644 --- a/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs +++ b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs @@ -64,8 +64,14 @@ public sealed record DataExportSealedChunk(string KeyVersion, byte[] Nonce, byte /// /// /// No secret leaves. Every refusal is one fixed message with no key, label, plaintext or position; -/// prints the type name; key buffers are overwritten on , and -/// intermediate plaintext is overwritten on failure. +/// a refused construction names only the setting, DataExport:KeyRing, so an operator knows what to +/// supply. prints the type name; key buffers are overwritten on , +/// and intermediate plaintext is overwritten on failure. +/// +/// +/// Disposal. Each seal or open copies its key into its own under the gate that +/// takes before it overwrites the ring, so a call racing host shutdown either refuses or +/// works with the real key; it never seals under a key that is being zeroed. /// /// public sealed class DataExportCipher : IDisposable @@ -77,7 +83,8 @@ public sealed class DataExportCipher : IDisposable public const byte FormatVersion = 1; private readonly FrozenDictionary _keys; - private bool _disposed; + private readonly Lock _gate = new(); + private volatile bool _disposed; /// The key ring is absent or malformed. public DataExportCipher(ISecretProvider secrets) @@ -129,13 +136,16 @@ public DataExportCipher(ISecretProvider secrets) CryptographicOperations.ZeroMemory(key); } - throw Refused(); + throw RingRefused(); } } /// The label new chunks are sealed under; a label, never key material. public string ActiveKeyVersion { get; } = string.Empty; + /// Whether the ring holds the key names; a label check, no key leaves. + public bool HoldsKey(string? keyVersion) => !_disposed && keyVersion is not null && _keys.ContainsKey(keyVersion); + /// Seals one chunk of at most under the active key. /// The chunk is empty or too large, or the cipher is disposed. public DataExportSealedChunk Seal(DataExportChunkBinding binding, ReadOnlySpan plaintext) @@ -150,7 +160,7 @@ public DataExportSealedChunk Seal(DataExportChunkBinding binding, ReadOnlySpan + /// An over its own copy of , made under the gate + /// takes: the copy is taken from a live ring, or the call refuses. + /// + private AesGcm Keyed(byte[] key) + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + return new AesGcm(key, DataRequestLimits.TagBytes); + } + } + private static InvalidOperationException Refused() => new("Data export custody unavailable."); + + /// The startup refusal: it names the setting, never its value or which rule it broke. + private static InvalidOperationException RingRefused() => new( + "Data export custody unavailable: the setting " + KeyRingSecret + " (environment DataExport__KeyRing) is absent or malformed. " + + "It must hold one JSON object " + + "{ \"active\": \"